
Andrew
Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com.
As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.
When not pushing the boundaries of what’s possible with code, Andrew shares his knowledge and insights through his writing, contributing to the growth and success of Ataiva.com’s projects.
Hivemind – Distributed Task Processing Framework
April 17, 2025
What is Hivemind? Hivemind is a distributed task processing framework designed for scalability, fault tolerance, and ease of use. It enables efficient distribution of computational workloads across multiple nodes, making it ideal for data processing, machine learning, and other compute-intensive tasks. How does it work? Hivemind uses a coordinator-worker architecture to distribute tasks across a cluster of nodes. Tasks are broken down into smaller units of work, distributed to available workers, and results are aggregated back to provide a unified output.
Read More
Pyroid – Python on Rust-Powered Steroids
April 17, 2025
What is Pyroid? Pyroid is a collection of blazing fast Rust-powered utilities designed to eliminate Python’s performance bottlenecks. It provides high-performance implementations across multiple domains with a focus on memory safety, efficiency, and ease of use. How does it work? Pyroid leverages Rust’s performance and memory safety guarantees to accelerate CPU-heavy tasks in Python. It provides a simplified architecture with minimal dependencies and a domain-driven design for better organization, all while maintaining an easy-to-use Python interface.
Read More
Rustainer – Lightweight Container Runtime in Rust
April 17, 2025
What is Rustainer? Rustainer is a lightweight container runtime written in Rust, designed for security, performance, and simplicity. It provides a minimalist approach to containerization with a focus on memory safety and efficient resource utilization. How does it work? Rustainer leverages Rust’s memory safety guarantees and zero-cost abstractions to create a secure container environment. It uses Linux namespaces, cgroups, and seccomp filters to isolate containers while maintaining minimal overhead. Key features include:
Read More
Microservices Monitoring Strategies: Observability in Distributed Systems
April 15, 2025
- Monitoring , Observability , Distributed tracing , Metrics , Logging , Alerting , Service mesh , Open telemetry , Slos , Dashboards
Microservices architectures have transformed how organizations build and deploy applications, enabling greater agility, scalability, and resilience. However, this architectural shift introduces significant complexity in monitoring and troubleshooting. With dozens or hundreds of services communicating across complex dependency chains, traditional monitoring approaches fall short. Organizations need comprehensive observability strategies that provide visibility into service health, performance, and interactions. This guide explores microservices monitoring strategies, covering observability principles, instrumentation techniques, monitoring tools, and best practices.
Read More
Rust's Standard Library: Essential Tools for Every Project
April 15, 2025
Rust’s standard library is a carefully curated collection of core components that provide essential functionality for almost every Rust program. Unlike some languages that include “batteries” for nearly every use case, Rust’s standard library is intentionally focused, offering only the most fundamental tools while leaving more specialized functionality to the crate ecosystem. This design philosophy ensures that the standard library remains lean, well-maintained, and suitable for a wide range of environments, from embedded systems to web servers.
Read More
Quantum Computing in Distributed Systems: Preparing for the Quantum Future
April 10, 2025
Quantum computing represents one of the most significant technological revolutions on the horizon, with the potential to transform how we approach complex computational problems. As quantum computers continue to advance, their integration with distributed systems will create new possibilities and challenges for system architects and developers. While fully fault-tolerant quantum computers are still developing, organizations should begin preparing for the quantum future today. This article explores the intersection of quantum computing and distributed systems, examining how quantum technologies will impact distributed architectures and providing practical guidance on preparing for the quantum advantage.
Read More
Incident Management for SRE: Building Resilient Response Systems
April 8, 2025
In today’s digital landscape, incidents are inevitable. Even with the most robust architecture and rigorous testing, complex systems will experience failures. What separates mature engineering organizations from the rest is not the absence of incidents, but rather how effectively they detect, respond to, and learn from them. This is where structured incident management becomes crucial, especially for Site Reliability Engineering (SRE) teams. This comprehensive guide explores best practices for building resilient incident management systems.
Read More
Building Fault-Tolerant Distributed Systems: Strategies and Patterns
April 5, 2025
In distributed systems, failures are not just possible—they’re inevitable. Networks partition, servers crash, disks fail, and software bugs manifest in production. Building systems that can withstand these failures while maintaining acceptable service levels is the essence of fault tolerance. As distributed architectures become increasingly complex, mastering fault tolerance has never been more critical. This article explores strategies, patterns, and practical techniques for building fault-tolerant distributed systems that can gracefully handle failures without catastrophic service disruptions.
Read More
Macros in Rust: Metaprogramming Made Simple
April 5, 2025
Macros are one of Rust’s most powerful features, enabling metaprogramming—code that writes code. Unlike macros in C and C++, which are simple text substitution mechanisms, Rust’s macros are hygienic and operate on the abstract syntax tree (AST), making them both powerful and safe. They allow you to extend the language, reduce boilerplate, create domain-specific languages, and implement compile-time code generation without sacrificing Rust’s safety guarantees. In this comprehensive guide, we’ll explore Rust’s macro system in depth, from basic declarative macros to advanced procedural macros.
Read More
Rust for Blockchain in 2025: Libraries, Tools, and Best Practices
April 5, 2025
Blockchain development presents unique challenges that demand high performance, reliability, and security guarantees. From public cryptocurrencies and smart contract platforms to private enterprise blockchains, these systems must process transactions securely and efficiently while ensuring data integrity. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for blockchain development. In this comprehensive guide, we’ll explore Rust’s ecosystem for blockchain as it stands in early 2025.
Read More
API Security Best Practices: Protecting Your Digital Interfaces
April 1, 2025
- API security , Authentication , Authorization , Oauth , JWT , Rate limiting , Input validation , API gateway , Owasp API , Zero trust
As organizations increasingly expose their services and data through APIs, these interfaces have become prime targets for attackers. According to recent studies, API attacks have grown by over 300% in the past two years, with the average organization experiencing dozens of API security incidents annually. The consequences of API breaches can be severe, ranging from data theft and service disruption to regulatory penalties and reputational damage. This comprehensive guide explores API security best practices, covering authentication, authorization, encryption, rate limiting, input validation, and monitoring.
Read More
Cloud Performance Tuning Tips: Optimizing for Speed, Scale, and Cost
April 1, 2025
In today’s cloud-first world, application performance directly impacts user experience, business outcomes, and operational costs. While cloud platforms offer tremendous scalability, achieving optimal performance requires deliberate tuning across multiple layers of your architecture. The default configurations provided by cloud services are designed for general use cases, not your specific application’s needs. This comprehensive guide explores practical performance tuning strategies across AWS, Azure, and Google Cloud Platform, providing actionable tips to optimize compute resources, storage, networking, databases, and application code.
Read More
Rust's Memory Safety Guarantees: How the Compiler Protects Your Code
March 29, 2025
Memory-related bugs are among the most pernicious issues in software development. Buffer overflows, use-after-free errors, double frees, and data races have plagued systems programming for decades, leading to security vulnerabilities, crashes, and unpredictable behavior. Traditional approaches to solving these problems involve either manual memory management (prone to human error) or garbage collection (which introduces runtime overhead and unpredictable pauses). Rust takes a revolutionary approach to memory safety by enforcing strict rules at compile time through its ownership system, borrow checker, and type system.
Read More
LLM Production Deployment: Architectures, Strategies, and Best Practices
March 25, 2025
Large Language Models (LLMs) have revolutionized natural language processing and AI applications, enabling capabilities that were previously impossible. However, deploying these powerful models in production environments presents unique challenges due to their size, computational requirements, and the complexity of the systems needed to serve them efficiently. This comprehensive guide explores the architectures, strategies, and best practices for deploying LLMs in production. Whether you’re working with open-source models like Llama 2 or Mistral, fine-tuned variants, or commercial APIs like OpenAI’s GPT-4, this guide will help you navigate the complexities of building robust, scalable, and cost-effective LLM-powered applications.
Read More
Rust for Robotics in 2025: Libraries, Tools, and Best Practices
March 25, 2025
Robotics development presents unique challenges that demand high performance, reliability, and safety guarantees. From industrial automation and autonomous vehicles to consumer robots and drones, these systems must interact with the physical world in real-time while ensuring predictable behavior. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for robotics development. In this comprehensive guide, we’ll explore Rust’s ecosystem for robotics as it stands in early 2025.
Read More
Concurrency in Rust: Fearless Parallelism
March 22, 2025
Concurrency is notoriously difficult to get right. Race conditions, deadlocks, and other concurrency bugs are among the most insidious issues in software development, often manifesting only under specific timing conditions that are hard to reproduce and debug. Rust tackles this challenge head-on with a concurrency model that leverages the type system and ownership rules to prevent data races and other concurrency errors at compile time. In this comprehensive guide, we’ll explore Rust’s approach to concurrency, from basic threads to advanced asynchronous programming.
Read More
Data Partitioning Strategies in Distributed Systems
March 18, 2025
As data volumes grow exponentially, traditional single-server database solutions often struggle to keep up with performance and storage demands. Data partitioning—the practice of dividing a dataset across multiple storage units—has emerged as a fundamental technique for building scalable distributed systems. By strategically splitting data, organizations can overcome hardware limitations, improve query performance, and enable horizontal scaling. This article explores various data partitioning strategies, their implementation approaches, and the trade-offs involved in choosing the right strategy for your distributed system.
Read More
Case Study: How We Cut Cloud Costs by 30% Without Sacrificing Performance
March 15, 2025
- Cloud costs , Aws optimization , Fin ops , Case study , Resource optimization , Cloud architecture , Cost management , Cloud efficiency
Cloud cost optimization is a critical concern for organizations of all sizes, but particularly for growing companies that experience the shock of rapidly escalating cloud bills as they scale. At Ataiva, we recently worked with TechNova, a mid-sized SaaS company experiencing this exact challenge. Their monthly AWS bill had grown from $50,000 to over $200,000 in just 18 months as their customer base expanded, putting significant pressure on margins and raising concerns among investors.
Read More
Lifetimes in Rust: Managing References Safely
March 15, 2025
Lifetimes are one of Rust’s most distinctive and initially challenging features. While other aspects of Rust’s ownership system deal with who owns a value, lifetimes address how long references to that value remain valid. This mechanism ensures memory safety without a garbage collector by validating at compile time that no reference outlives the data it points to—a common source of bugs in languages like C and C++. In this comprehensive guide, we’ll explore Rust’s lifetime system in depth, from basic concepts to advanced patterns.
Read More
Rust for Computer Vision in 2025: Libraries, Tools, and Best Practices
March 15, 2025
Computer vision and image processing applications demand high performance, reliability, and often real-time capabilities. From autonomous vehicles and robotics to augmented reality and medical imaging, these systems process enormous amounts of visual data and must do so efficiently and safely. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for computer vision development. In this comprehensive guide, we’ll explore Rust’s ecosystem for computer vision and image processing as it stands in early 2025.
Read More
Blockchain in Enterprise Distributed Systems: Beyond Cryptocurrencies
March 10, 2025
While blockchain technology first gained prominence as the foundation for cryptocurrencies like Bitcoin, its potential applications extend far beyond digital currencies. At its core, blockchain is a distributed ledger technology that provides a secure, transparent, and immutable record of transactions across a decentralized network. These properties make it particularly valuable for enterprise distributed systems that require trust, transparency, and data integrity across multiple parties. This article explores practical enterprise applications of blockchain technology in distributed systems, examining implementation patterns, challenges, and best practices for organizations looking to leverage this transformative technology.
Read More
Infrastructure as Code Best Practices: Beyond the Basics
March 10, 2025
Infrastructure as Code (IaC) has revolutionized how organizations manage their cloud resources, enabling teams to provision and manage infrastructure through machine-readable definition files rather than manual processes. While most teams have adopted basic IaC practices, many struggle to implement the advanced patterns and workflows that lead to truly maintainable, secure, and efficient infrastructure management. This comprehensive guide explores advanced Infrastructure as Code best practices that go beyond the basics. We’ll cover strategies for testing, security, modularity, team workflows, and more—all designed to help you elevate your IaC implementation from functional to exceptional.
Read More
Distributed Caching Strategies for High-Performance Applications
March 7, 2025
In today’s digital landscape, where milliseconds can make the difference between user engagement and abandonment, caching has become an indispensable technique for building high-performance applications. As systems scale and distribute across multiple servers or regions, simple in-memory caching is no longer sufficient. This is where distributed caching comes into play—providing a shared cache that spans multiple servers, enabling consistent performance across distributed applications. This article explores distributed caching strategies, patterns, and implementations that can help you build faster, more scalable applications while reducing the load on your databases and backend services.
Read More
Rust for Audio Programming in 2025: Libraries, Tools, and Best Practices
March 5, 2025
Audio programming presents unique challenges that demand both high performance and reliability. From real-time digital signal processing to music creation tools, audio applications require low latency, predictable memory usage, and freedom from unexpected crashes or glitches. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for audio development. In this comprehensive guide, we’ll explore Rust’s ecosystem for audio programming as it stands in early 2025.
Read More
Traits in Rust: Interfaces with Superpowers
March 5, 2025
In object-oriented programming, interfaces define a contract that implementing classes must fulfill. Rust’s trait system serves a similar purpose but goes far beyond traditional interfaces, offering a powerful mechanism for defining shared behavior, enabling polymorphism, and creating flexible abstractions—all while maintaining Rust’s guarantees of memory safety and performance. Traits are one of Rust’s most distinctive and powerful features, enabling code reuse without inheritance and polymorphism without runtime overhead. In this comprehensive guide, we’ll explore Rust’s trait system in depth, from basic usage to advanced patterns.
Read More
Reducing Cloud Waste with Monitoring Tools: Strategies for Cost Optimization
March 1, 2025
Cloud computing has revolutionized how organizations build and deploy applications, offering unprecedented flexibility and scalability. However, this flexibility comes with a significant challenge: cloud waste. According to industry research, organizations waste an estimated 30-35% of their cloud spend on unused or underutilized resources. This waste represents billions of dollars annually across the industry—money that could be better invested in innovation and growth. The good news is that with the right monitoring tools and strategies, you can identify and eliminate cloud waste, optimizing your cloud spending while maintaining performance and reliability.
Read More
Working with Structs and Enums in Rust: Building Robust Data Models
February 28, 2025
Data modeling is at the heart of software development, and the tools a language provides for representing data significantly impact code quality, maintainability, and correctness. Rust offers two powerful constructs for modeling data: structs and enums. These complementary tools allow developers to express complex data relationships with precision while leveraging Rust’s type system to prevent entire categories of bugs at compile time. In this comprehensive guide, we’ll explore Rust’s structs and enums in depth, from basic usage to advanced patterns.
Read More
SLO and SLI Implementation Guide: Building Reliable Services
February 25, 2025
In today’s digital landscape, reliability has become a critical differentiator for services and products. Users expect systems to be available, responsive, and correct—all the time. However, pursuing 100% reliability is not only prohibitively expensive but often unnecessary. This is where Service Level Objectives (SLOs) and Service Level Indicators (SLIs) come in, providing a framework to define, measure, and maintain appropriate reliability targets that balance user expectations with engineering costs. This comprehensive guide explores the practical aspects of implementing SLOs and SLIs in your organization.
Read More
Rust's Module System Explained: Organizing Code for Clarity and Reuse
February 22, 2025
As projects grow in size and complexity, organizing code becomes increasingly important. Rust’s module system provides a powerful framework for structuring your code into logical units, controlling visibility, and managing dependencies. Unlike some languages where organization is merely a convention, Rust’s module system is a core language feature that enforces boundaries and visibility rules at compile time, leading to more maintainable and understandable codebases. In this comprehensive guide, we’ll explore Rust’s module system in depth, from basic concepts to advanced techniques.
Read More
Distributed Consensus Algorithms: The Backbone of Reliable Distributed Systems
February 18, 2025
In distributed systems, one of the most fundamental challenges is achieving agreement among multiple nodes that may fail independently or experience network issues. This challenge—known as the consensus problem—lies at the heart of building reliable distributed systems. From distributed databases to blockchain networks, consensus algorithms provide the critical foundation that enables these systems to function correctly despite failures and network partitions. This article explores the most important distributed consensus algorithms, their implementations, trade-offs, and practical applications.
Read More
Pattern Matching in Rust: Powerful, Expressive, and Safe
February 15, 2025
Pattern matching stands as one of Rust’s most powerful and distinctive features, elevating it beyond a mere control flow mechanism to a fundamental aspect of the language’s design philosophy. Unlike the simple switch statements found in many languages, Rust’s pattern matching system provides a rich, expressive way to destructure complex data types, handle multiple conditions, and ensure exhaustive checking of all possible cases. This combination of power and safety makes pattern matching an essential tool in every Rust programmer’s toolkit.
Read More
Rust's Blockchain Development Ecosystem in 2025
February 15, 2025
Blockchain technology has evolved significantly since the introduction of Bitcoin in 2009, expanding beyond cryptocurrencies to encompass smart contracts, decentralized finance (DeFi), non-fungible tokens (NFTs), and various forms of decentralized applications (dApps). As blockchain systems have grown more complex and demanding, the need for programming languages that prioritize safety, performance, and reliability has become increasingly apparent. Rust, with its focus on memory safety without sacrificing performance, has emerged as a leading language for blockchain development.
Read More
Scaling Startups with Cloud Best Practices
February 15, 2025
Scaling a startup’s technical infrastructure is one of the most challenging aspects of company growth. As user numbers increase, feature sets expand, and market demands evolve, the technology decisions made in the early days are put to the test. Cloud computing has revolutionized how startups scale, offering unprecedented flexibility and power—but also introducing complexity and potential pitfalls. This comprehensive guide explores cloud best practices for scaling startups, covering everything from architectural patterns and cost optimization to security, DevOps, and organizational strategies.
Read More
MLOps Pipeline Architecture: Building Production-Ready ML Systems
February 12, 2025
Machine learning has moved beyond research and experimentation to become a critical component of many production systems. However, successfully deploying and maintaining ML models in production requires more than just good data science—it demands robust engineering practices, automated pipelines, and governance frameworks. This is where MLOps (Machine Learning Operations) comes in, bridging the gap between ML development and operational excellence. This comprehensive guide explores the architecture of production-grade MLOps pipelines, covering everything from data preparation to model monitoring.
Read More
Event-Driven Architecture Patterns for Distributed Systems
February 8, 2025
In the world of distributed systems, event-driven architecture (EDA) has emerged as a powerful paradigm for building scalable, loosely coupled, and responsive applications. By centering communication around events—significant changes in state or notable occurrences within a system—EDA enables organizations to create systems that can evolve independently while maintaining coherence across complex domains. This article explores the essential patterns of event-driven architecture, providing practical guidance on when and how to implement them in distributed systems.
Read More
Error Handling in Rust: Mastering Result and Option Types
February 5, 2025
Error handling is a critical aspect of writing reliable software, yet it’s often treated as an afterthought in many programming languages. Some languages rely on exceptions that can be easily overlooked, while others use error codes that can be ignored. Rust takes a fundamentally different approach by making error handling explicit through its type system, primarily using the Result and Option types. This approach ensures that errors are handled deliberately rather than by accident or omission.
Read More
Rust's Distributed Systems Ecosystem in 2025
February 5, 2025
Distributed systems have become the backbone of modern computing infrastructure, powering everything from cloud services and microservices architectures to blockchain networks and IoT platforms. Building these systems presents unique challenges: network partitions, partial failures, consistency issues, and the inherent complexity of coordinating multiple nodes. Rust, with its focus on reliability, performance, and fine-grained control, has emerged as an excellent language for tackling these challenges. In this comprehensive guide, we’ll explore Rust’s ecosystem for building distributed systems as it stands in early 2025.
Read More
Kubernetes vs. Serverless Architectures: Choosing the Right Compute Platform
February 1, 2025
- Kubernetes , Serverless , Aws lambda , Azure functions , Google cloud functions , Cloud architecture , Dev ops
In today’s cloud-native landscape, organizations face a critical decision when deploying applications: should they use container orchestration platforms like Kubernetes or embrace serverless computing models? This choice significantly impacts development workflows, operational overhead, scalability, and costs. While both approaches enable modern cloud-native applications, they represent fundamentally different philosophies for application deployment and management. This comprehensive guide explores Kubernetes and serverless architectures in depth, comparing their strengths, limitations, and ideal use cases to help you make an informed decision for your specific requirements.
Read More
Quantum Computing for Enterprises: Preparing for the Next Computing Revolution
February 1, 2025
- Quantum computing , Enterprise technology , Quantum algorithms , Quantum ready , Quantum use cases , Quantum strategy , Quantum advantage
Quantum computing represents one of the most significant technological shifts on the horizon, promising computational capabilities that could revolutionize industries from pharmaceuticals to finance, logistics to cybersecurity. While widespread quantum advantage—where quantum computers outperform classical systems for practical business problems—is still emerging, forward-thinking enterprises are already developing quantum strategies, building expertise, and identifying potential use cases to ensure they’re prepared when quantum technologies mature. This comprehensive guide explores quantum computing from an enterprise perspective, covering key concepts, potential applications, implementation strategies, and practical steps for preparing your organization.
Read More
Rust's Type System: A Deep Dive into Safety and Expressiveness
January 31, 2025
Rust’s type system stands as one of its most powerful features, combining the expressiveness of modern languages with the safety guarantees that systems programming demands. Unlike dynamically typed languages that defer type checking to runtime, or statically typed languages with escape hatches that can lead to undefined behavior, Rust’s type system is designed to catch errors at compile time while remaining flexible enough for real-world programming challenges. In this comprehensive exploration, we’ll dive deep into Rust’s type system, examining how it balances safety and expressiveness.
Read More
GitOps Workflow Implementation: A Practical Guide
January 28, 2025
GitOps has emerged as a powerful paradigm for managing infrastructure and application deployments, particularly in Kubernetes environments. By using Git as the single source of truth for declarative infrastructure and applications, GitOps enables teams to increase deployment velocity while improving reliability and auditability. However, implementing GitOps workflows requires careful planning and consideration of tools, processes, and organizational factors. This comprehensive guide explores the practical aspects of implementing GitOps workflows, from selecting the right tools to establishing effective processes and addressing common challenges.
Read More
Advanced Rust Performance Optimization Techniques in 2025
January 25, 2025
Performance optimization is a critical aspect of software development, particularly for systems programming, data processing, and other performance-sensitive applications. Rust, with its focus on zero-cost abstractions and fine-grained control over system resources, provides an excellent foundation for building high-performance software. However, achieving optimal performance often requires going beyond the basics and applying specialized optimization techniques tailored to your specific use case. In this comprehensive guide, we’ll explore advanced performance optimization techniques for Rust applications as they stand in early 2025.
Read More
Borrowing and References in Rust: The Art of Safe Memory Sharing
January 25, 2025
In our previous exploration of Rust’s ownership system, we established how Rust manages memory through a set of compile-time rules that track the ownership of values. While ownership provides the foundation for Rust’s memory safety guarantees, constantly transferring ownership would make code unnecessarily complex and inefficient. This is where Rust’s borrowing system comes into play—a sophisticated mechanism that allows you to use values without transferring ownership. Borrowing, implemented through references, is what makes Rust’s ownership model practical for everyday programming.
Read More
Implementing Distributed Tracing: A Practical Guide for Modern Applications
January 20, 2025
In today’s world of distributed systems and microservices architectures, understanding the flow of requests across dozens or even hundreds of services has become increasingly challenging. When a user experiences a slow response or an error, pinpointing the root cause can feel like searching for a needle in a haystack. This is where distributed tracing comes in—providing a powerful lens through which we can observe, understand, and optimize our distributed applications.
Read More
Rust Security Features and Best Practices in 2025
January 20, 2025
Security has become a paramount concern in software development, with vulnerabilities and exploits causing billions in damages annually. As systems become more interconnected and complex, the need for programming languages that prioritize security by design has never been greater. Rust, with its focus on memory safety without sacrificing performance, has positioned itself as a leading language for security-critical applications. By eliminating entire classes of bugs at compile time, Rust provides developers with powerful tools to write secure code from the ground up.
Read More
Kubernetes Pod Security Policies: Best Practices for Cluster Protection
January 15, 2025
As Kubernetes adoption continues to grow across organizations of all sizes, securing containerized workloads has become a critical concern. Pod Security Policies (PSPs) and their successor, Pod Security Admission, represent Kubernetes’ native approach to enforcing security best practices at the pod level. By controlling the security-sensitive aspects of pod specifications, these mechanisms help prevent privilege escalation and limit the potential damage from container-based attacks. This comprehensive guide explores how to implement effective pod security controls in Kubernetes, covering both the legacy Pod Security Policies and the newer Pod Security Standards and Admission Controller.
Read More
Understanding Rust's Ownership System: The Key to Memory Safety
January 15, 2025
Rust’s ownership system stands as one of the language’s most revolutionary contributions to systems programming. While other languages rely on garbage collection or manual memory management, Rust introduces a third approach: ownership with borrowing. This system enables Rust to guarantee memory safety at compile time without runtime overhead, preventing entire categories of bugs that plague other languages. For developers coming from languages like C++, Java, or Python, understanding ownership is the key to unlocking Rust’s full potential.
Read More
Microservices vs. Monoliths: Choosing the Right Architecture for Your Application
January 10, 2025
One of the most significant architectural decisions in modern software development is choosing between microservices and monolithic architectures. This choice impacts everything from development speed and team structure to scalability and operational complexity. Despite the hype around microservices in recent years, the reality is that neither approach is universally superior—each has distinct advantages and challenges that make it suitable for different scenarios. This comprehensive guide explores both architectural patterns in depth, providing a balanced comparison to help you make an informed decision for your specific context.
Read More
Distributed Systems Fundamentals: Core Concepts Every Developer Should Know
January 7, 2025
In today’s interconnected world, distributed systems have become the backbone of modern software architecture. From global e-commerce platforms to real-time collaboration tools, distributed systems enable applications to scale beyond the confines of a single machine, providing resilience, performance, and global reach. However, with these benefits come significant challenges that every developer must understand to build effective distributed applications. This article explores the fundamental concepts of distributed systems, providing a solid foundation for developers looking to navigate this complex but essential domain.
Read More
Getting Started with Rust: A Comprehensive Installation and Setup Guide
January 5, 2025
Rust has emerged as one of the most promising programming languages of the decade, offering an unparalleled combination of performance, reliability, and productivity. Whether you’re a seasoned developer looking to expand your toolkit or a newcomer to systems programming, setting up Rust correctly is your first step toward mastering this powerful language. This comprehensive guide will walk you through the installation process across different operating systems, help you configure your development environment, and introduce you to essential tools in the Rust ecosystem.
Read More
Rust Interoperability: Seamlessly Working with Other Languages in 2025
January 5, 2025
In today’s complex software landscape, few applications are built using a single programming language. Different languages offer different strengths, and existing codebases represent significant investments that can’t be rewritten overnight. This reality makes language interoperability—the ability for code written in different languages to work together seamlessly—a critical feature for any modern programming language. Rust, with its focus on safety, performance, and practicality, has developed robust interoperability capabilities that allow it to integrate smoothly with a wide range of other languages.
Read More
Rust's unwrap: Unlocking Its Potential and Avoiding Pitfalls
December 30, 2024
Learn how to effectively use Rust’s unwrap method, including its benefits, risks, and safer alternatives, in this comprehensive guide. At the heart of its error-handling mechanism lie the Option and Result types, which provide developers with tools to explicitly manage the presence or absence of values and handle potential errors in computations. However, there exists a method—unwrap—that offers a shortcut for extracting values from these types. While powerful, its misuse can lead to unexpected panics, making it a topic of both fascination and caution among Rustaceans.
Read More
Optimizing the Two Sum Problem: Techniques, Trade-offs, and Performance
December 13, 2024
The Problem Statement One of the classic algorithm problems frequently encountered in interviews is the Two Sum problem. It challenges you to find two indices in an array such that the sum of the elements at these indices equals a given target. It seems simple, but the real depth lies in optimizing its solution. There is this common programming question that goes something like this: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Read More
Chaos Engineering Practices: Building Resilient Systems Through Controlled Failure
December 10, 2024
In today’s complex distributed systems, failures are inevitable. Networks partition, services crash, dependencies slow down, and hardware fails. Traditional testing approaches often fall short in identifying how these systems behave under unexpected conditions. Chaos Engineering has emerged as a disciplined approach to identify weaknesses in distributed systems by deliberately injecting failures in a controlled manner. This comprehensive guide explores chaos engineering principles, tools, implementation strategies, and real-world examples. Whether you’re just starting your reliability journey or looking to enhance your existing practices, these approaches will help you build more resilient systems that can withstand the turbulence of production environments.
Read More
Low-Code/No-Code Platforms: Democratizing Application Development
November 15, 2024
- Low code , No code , Citizen developers , Rapid application development , Digital transformation , Enterprise architecture , Shadow it , Governance , Automation , Business process management
The demand for software applications continues to outpace the availability of professional developers, creating significant backlogs and slowing digital transformation initiatives. Low-code and no-code development platforms have emerged as powerful solutions to this challenge, enabling both professional developers and business users to build applications with minimal traditional coding. By abstracting away complex technical details through visual interfaces and pre-built components, these platforms democratize application development and accelerate delivery. This comprehensive guide explores low-code and no-code platforms, covering their capabilities, use cases, implementation strategies, governance, and best practices.
Read More
Observability Platforms Comparison: Choosing the Right Monitoring Solution
November 5, 2024
As systems grow more complex and distributed, traditional monitoring approaches fall short. Modern observability platforms have emerged to provide deeper insights into system behavior, performance, and health. However, choosing the right observability solution for your organization can be challenging given the wide range of options available, each with different strengths, architectures, and pricing models. This comprehensive guide compares leading observability platforms including Prometheus, Grafana, Datadog, New Relic, Elastic Observability, and Dynatrace.
Read More
How to Migrate Docker Repositories to a New DockerHub Username
November 4, 2024
If you’ve ever tried to rename your DockerHub username, you know there’s no direct way to do it. For many users, creating a new DockerHub account and transferring all their repositories is the best option. This guide walks you through automating the process of migrating all Docker images from an old username to a new one. We’ll share a complete shell script, so you don’t have to manually tag and push each image, saving you time and effort.
Read More
Python 3.13 No-GIL Mode: How to Unlock True Multi-Threading and Boost Performance
November 1, 2024
Python 3.13 has quietly introduced a game-changing experimental feature: no-GIL mode! For years, the Global Interpreter Lock (GIL) has been a barrier to true parallelism in Python, limiting Python threads to one at a time. But with Python 3.13, you can now compile Python to run without the GIL, allowing Python threads to fully utilize multiple cores. Let’s dive into why this matters, how to try it out, and what kinds of performance gains you might see.
Read More
Benefits of Cloud-Native Applications: Building for the Modern Infrastructure
October 15, 2024
The landscape of application development and deployment has undergone a profound transformation over the past decade. Traditional monolithic applications hosted on physical servers have given way to cloud-native applications designed specifically to leverage the capabilities of modern cloud infrastructure. This shift isn’t merely a change in hosting environment—it represents a fundamental reimagining of how applications are built, deployed, and operated. Cloud-native applications are specifically designed to thrive in cloud environments, embracing principles like containerization, microservices architecture, declarative APIs, and immutable infrastructure.
Read More
AI-Powered Distributed Systems: Architectures and Implementation Patterns
October 5, 2024
The integration of artificial intelligence (AI) with distributed systems represents one of the most significant technological advancements in recent years. As distributed systems grow in complexity, traditional management approaches struggle to keep pace. AI offers powerful capabilities to enhance these systems with self-healing, intelligent scaling, anomaly detection, and automated optimization. This convergence is creating a new generation of distributed systems that are more resilient, efficient, and adaptive than ever before.
Read More
How to Create Your Own Programming Language
September 19, 2024
A programming language is a system of communication and computation used to control a computer. Languages allow us to write instructions in a format that computers can understand and execute. While many popular languages like Python, Java, and JavaScript already exist, you may want to create your own for learning purposes or to solve a specific problem. Here is an overview of the key steps involved in designing a custom programming language.
Read More
Poetry vs Pip: Comparing Python Dependency Management and Packaging Tools
September 13, 2024
Poetry and Pip are two popular tools for managing Python dependencies and packaging Python projects. Both have their own sets of advantages and disadvantages. This guide will provide a technical comparison of the two tools and demonstrate why Poetry has more features and is generally preferable to Pip for most use cases. Key Differences Some of the key differences between Poetry and Pip include: Dependency resolution: Poetry uses a resolver to find the best combination of package versions to meet your requirements.
Read More
Sustainable Cloud Computing for Distributed Systems
September 12, 2024
As distributed systems increasingly rely on cloud computing resources, their environmental impact has become a growing concern. The global IT industry accounts for approximately 2-3% of worldwide carbon emissions—comparable to the aviation industry—with data centers alone consuming about 1% of global electricity. With the exponential growth of distributed systems and cloud computing, implementing sustainable practices is not just an environmental imperative but also a business necessity. This article explores practical strategies and technologies for implementing sustainable cloud computing in distributed systems, helping organizations reduce their environmental impact while maintaining performance, reliability, and cost-effectiveness.
Read More
API Design Principles: Building Interfaces That Last
September 10, 2024
Application Programming Interfaces (APIs) have become the foundation of modern software development, enabling seamless integration between systems, powering microservices architectures, and facilitating third-party ecosystems. However, designing APIs that are intuitive, efficient, secure, and able to evolve over time requires careful consideration of numerous principles and best practices. This comprehensive guide explores API design principles that lead to robust, developer-friendly interfaces. We’ll cover RESTful design, GraphQL, versioning strategies, authentication methods, documentation approaches, and patterns for creating APIs that stand the test of time.
Read More
A Complete DevOps Guide for Beginners
September 5, 2024
Are you looking to improve your software development workflow and increase efficiency? Look no further than DevOps! In this comprehensive guide, we’ll explore what DevOps means, its benefits, and how to get started with implementing it in your own organization. Hello there! My name is Andrew, and I’m excited to share my expertise on DevOps Engineering with you. As someone who has spent years working in the field, I’ve seen firsthand how it can transform organizations and bring people together.
Read More
Creating a Docker Alternative in Python
August 26, 2024
Docker is a popular containerization platform that allows developers to easily package applications into lightweight containers that can run isolated on any system. Containers provide a convenient way to deploy and scale applications by bundling together all the dependencies and configurations needed to run the app. In this guide, we will walk through how to create a simple docker alternative in Python. The goal is to build a basic container runtime that can build images, run containers, and manage containers lifecycles.
Read More
Why Different Programming Languages Need to Exist
August 26, 2024
Programming languages allow us to communicate with computers by writing code. There are hundreds of programming languages in use today, and new ones are constantly being created. But why do we need so many different languages? Here are some key reasons: Different Levels of Abstraction Programming languages operate at different levels of abstraction from the underlying machine code that computers understand. Lower level languages like C and Assembly provide direct access to computer hardware and memory.
Read More
Database Scaling Strategies: From Gigabytes to Petabytes
August 15, 2024
As applications grow in popularity and data volumes expand, database performance often becomes a critical bottleneck. What worked perfectly during development or early production can quickly become inadequate as user numbers increase and data accumulates. Scaling database systems effectively requires a deep understanding of various strategies, their trade-offs, and implementation approaches. This comprehensive guide explores database scaling strategies from vertical scaling to distributed systems, covering relational and NoSQL approaches, replication, sharding, and cloud-native solutions.
Read More
Rust for Quantum Computing in 2024: Libraries, Tools, and Best Practices
August 10, 2024
Quantum computing represents one of the most exciting frontiers in computer science, promising computational capabilities that could revolutionize fields from cryptography to drug discovery. As quantum hardware continues to advance, there’s a growing need for robust software tools to bridge the gap between quantum algorithms and physical quantum processors. Rust, with its combination of performance comparable to C/C++ and memory safety guarantees without garbage collection, has emerged as an excellent choice for quantum computing development.
Read More
The Future of AI in Software Development: What to Expect in 2025
August 8, 2024
As we stand on the cusp of a new era in technology, the integration of Artificial Intelligence (AI) into software development is poised to revolutionize the way we create, maintain, and evolve digital solutions. By 2025, the landscape of software engineering is expected to undergo a dramatic transformation, with AI playing a pivotal role in every aspect of the development lifecycle. From intelligent code generation to predictive maintenance and beyond, the fusion of AI and software development promises to enhance productivity, improve code quality, and accelerate innovation at an unprecedented scale.
Read More
Auth
July 30, 2024
Welcome to Auth, your ultimate solution for seamless authentication integration. Simplify your development process and enhance security with our robust authentication platform. Key Features Dashboard Overview: Get a high-level view of your authentication metrics, user activity, and security status. Real-Time Data: Monitor authentication events and user activity in real-time. User Authentication Sign-Up & Login: Easily integrate user registration and login functionalities. Multi-Factor Authentication: Enhance security with optional multi-factor authentication (MFA). Authorization Role-Based Access Control: Define and manage user roles and permissions.
Read More
CloudZen
July 30, 2024
Welcome to CloudZen, your ultimate solution for mastering cloud cost management. Streamline your spending, optimize resources, and gain full visibility into your cloud expenses with our intuitive platform. Key Features Dashboard Overview: Get a high-level view of your cloud spending, with key metrics and trends. Alerts: Receive notifications for budget breaches or unusual spending patterns. Cost Tracking Detailed Breakdown: View costs by service, project, or department. Historical Data: Access past spending data for analysis and comparison.
Read More
Uptime Monitor
July 30, 2024
Welcome to Uptime Monitor, your essential tool for ensuring the reliability and availability of your websites and services. Stay ahead of downtime with real-time monitoring and instant alerts. Key Features Dashboard Overview: Get a high-level view of your website’s uptime and performance, with key metrics and trends. Real-Time Data: Monitor uptime and response times in real-time. Uptime Monitoring Global Checks: Perform checks from multiple global locations to ensure your website is accessible worldwide.
Read More
Website Analytics
July 30, 2024
Welcome to Website Analytics, your ultimate solution for real-time website analytics. Understand your audience, optimize user experience, and drive growth with our comprehensive platform. Key Features Dashboard Overview: Get a high-level view of your website’s performance, with key metrics and trends. Real-Time Data: Monitor your website traffic and user behavior in real-time. Traffic Analysis Visitor Insights: Understand who your visitors are, where they come from, and what they do on your site.
Read More
Learn Concurrency in Go
July 22, 2024
Concurrency in Go is one of its most powerful features, designed to make it easy to write concurrent programs. Go’s concurrency model is based on goroutines and channels, which provide a simple and efficient way to manage multiple tasks running in parallel. Goroutines A goroutine is a lightweight thread managed by the Go runtime. You can start a new goroutine using the go keyword followed by a function call. Goroutines run concurrently with other goroutines.
Read More
Learn Go as a DevOps Engineer
July 18, 2024
Go, also known as Golang, is an open-source programming language designed for simplicity, efficiency, and reliability. It has become increasingly popular in the DevOps community due to its powerful standard library, ease of use, and performance capabilities. This guide aims to provide DevOps engineers with a comprehensive understanding of Go, from basic syntax to advanced topics, complete with practical examples and code snippets. 1. Introduction to Go What is Go? Go is a statically typed, compiled programming language designed by Google.
Read More
How to Run Technical Discovery Sessions: A Comprehensive Guide
July 5, 2024
Technical discovery sessions are the foundation of successful software projects. These structured conversations between technical teams, stakeholders, and subject matter experts uncover requirements, constraints, and context that shape the entire project lifecycle. When done well, discovery sessions align expectations, identify risks early, and create a shared understanding that guides implementation. When done poorly, they lead to misaligned expectations, missed requirements, and ultimately, project failure. This comprehensive guide explores how to plan and facilitate effective technical discovery sessions.
Read More
Secrets Management in Cloud Environments: Best Practices and Tools
July 1, 2024
In today’s cloud-native world, applications require access to numerous secrets—API keys, database credentials, encryption keys, and other sensitive information. Managing these secrets securely is one of the most critical aspects of cloud security. Poor secrets management can lead to data breaches, unauthorized access, and compliance violations that can severely impact your organization. This comprehensive guide explores best practices, tools, and implementation strategies for effective secrets management across AWS, Azure, and Google Cloud Platform (GCP), helping you build a robust security posture for your cloud environments.
Read More
Developing a Custom Kubernetes Controller in Go
June 20, 2024
A custom Kubernetes controller manages custom resources within a Kubernetes cluster, allowing for extended functionalities and custom automation. Step-by-Step Guide Define Custom Resource: Define a custom resource definition (CRD) in a YAML file. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: myresources.mydomain.com spec: group: mydomain.com versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: size: type: integer scope: Namespaced names: plural: myresources singular: myresource kind: MyResource shortNames: - mr Generate Clientset: Use kubebuilder to generate clientset, informers, and listers for your CRD.
Read More
Rust for IoT Development in 2024: Frameworks, Tools, and Best Practices
June 18, 2024
The Internet of Things (IoT) continues to transform our world, connecting billions of devices that collect, process, and exchange data. As IoT deployments grow in scale and complexity, the need for reliable, secure, and efficient software becomes increasingly critical. Rust, with its unique combination of memory safety without garbage collection, predictable performance, and modern language features, has emerged as an excellent choice for IoT development. In this comprehensive guide, we’ll explore Rust’s ecosystem for IoT development as it stands in mid-2024.
Read More
Creating a Monitoring Agent in Go
June 18, 2024
Building a monitoring agent involves collecting metrics from a system and sending them to a monitoring server or displaying them on a dashboard. Step-by-Step Guide Define Metrics Structure: Create a structure to store metrics. type Metric struct { Name string Value float64 } Collect Metrics: Implement functions to collect various system metrics (CPU usage, memory usage, etc.). import ( "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/mem" ) func collectCPUMetrics() Metric { usage, _ := cpu.Percent(0, false) return Metric{Name: "cpu_usage", Value: usage[0]} } func collectMemoryMetrics() Metric { v, _ := mem.
Read More
Building a CI/CD Pipeline Tool in Go
June 15, 2024
Developing a custom CI/CD pipeline tool in Go can help automate the processes of building, testing, and deploying applications. This project involves setting up pipelines, triggering builds, running tests, and deploying applications. Step-by-Step Guide Define the Pipeline Structure: Create a structure to define pipeline stages, jobs, and steps. type Step struct { Name string Command string } type Job struct { Name string Steps []Step } type Pipeline struct { Name string Jobs []Job } Parse Configuration: Write a function to parse a pipeline configuration file (e.
Read More
Cloud Networking Best Practices: Designing Secure and Scalable Architectures
June 10, 2024
Networking is the foundation of cloud infrastructure, connecting your applications, services, and data across regions and to the internet. As organizations migrate more workloads to the cloud, designing secure, scalable, and high-performance network architectures becomes increasingly critical. Poor network design can lead to security vulnerabilities, performance bottlenecks, and operational challenges that impact your entire cloud environment. This comprehensive guide explores cloud networking best practices across major cloud providers, covering VPC design, security controls, connectivity options, performance optimization, and monitoring strategies.
Read More
GoFlood – A Powerful HTTP Load Testing Tool
June 2, 2024
What is GoFlood? GoFlood is a high-performance, concurrent HTTP load testing tool written in Go. It allows you to simulate real-world traffic scenarios and stress-test your web applications, APIs, and servers by flooding them with a configurable number of concurrent requests. Key Features Concurrent Requests: GoFlood can generate a large number of concurrent HTTP requests, simulating high-traffic scenarios. Gradual Concurrency Increase: You can configure GoFlood to start with a base concurrency level and gradually increase the concurrency by a specified step, allowing you to observe the system’s behavior under varying load conditions.
Read More
Everything you need to know to Master API Creation
May 31, 2024
Introduction to APIs An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. APIs can be categorized into various types, including REST, SOAP, GraphQL, and RPC. Among these, REST (Representational State Transfer) is the most widely used due to its simplicity and scalability. This guide focuses primarily on RESTful APIs, which adhere to a set of constraints that make them efficient and easy to use.
Read More
WebAssembly in the Enterprise: Beyond the Browser
May 18, 2024
- Web assembly , Wasm , Wasi , Edge computing , Containerization , Rust , Assembly script , Serverless , Microservices , Portable execution
WebAssembly (Wasm) has evolved far beyond its origins as a browser technology. Initially designed to enable high-performance code execution in web browsers, Wasm has expanded into server-side applications, edge computing, containerization alternatives, and more. Its unique combination of near-native performance, sandboxed security, language-agnostic design, and compact binary format makes it increasingly attractive for enterprise applications seeking portability, security, and efficiency. This comprehensive guide explores WebAssembly’s role in enterprise applications, covering server-side Wasm, edge computing use cases, containerization alternatives, multi-language development, and security considerations.
Read More
Building CI/CD Pipelines with GitHub Actions: A Comprehensive Guide
May 15, 2024
Continuous Integration and Continuous Deployment (CI/CD) have revolutionized how software teams deliver value. By automating the build, test, and deployment processes, CI/CD enables faster, more reliable software delivery with fewer manual interventions. Among the various CI/CD tools available today, GitHub Actions has emerged as a powerful and flexible solution, particularly for teams already using GitHub for source control. This comprehensive guide will walk you through building effective CI/CD pipelines with GitHub Actions, from basic concepts to advanced implementation strategies, helping you accelerate your software delivery while maintaining quality and security.
Read More
How to AWS Assume Role and then revert to the previous role after
May 1, 2024
If you need to assume a role in AWS and then revert back to the previous role once complete, you can use the following snippet of code: # Save original environment variables ORIGINAL_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" ORIGINAL_AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" ORIGINAL_AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" # Assume the role and store the output in a variable assume_role_output=$(aws sts assume-role --role-arn arn:aws:iam::12345678912:role/YourCrossAccountAccessRole --role-session-name "AssumeRoleSession") # Extract temporary credentials from the assume role output using jq (JSON processor) export AWS_ACCESS_KEY_ID=$(echo "$assume_role_output" | jq -r '.
Read More
Infrastructure as Code with Terraform: From Basics to Best Practices
April 12, 2024
In today’s cloud-centric world, managing infrastructure manually is no longer feasible. As organizations scale their cloud presence, the complexity of managing resources across multiple providers and environments becomes overwhelming. Infrastructure as Code (IaC) has emerged as the solution to this challenge, with Terraform standing out as one of the most powerful and flexible IaC tools available. This comprehensive guide will take you through the journey of mastering Terraform—from understanding core concepts to implementing advanced techniques and best practices that enable you to manage infrastructure at scale with confidence and efficiency.
Read More
Essential Policies for Administering an AWS EKS Cluster
March 22, 2024
So, what policies does my role need to create an AWS EKS cluster and be the admin? AmazonEKSClusterPolicy: This policy grants permissions to create and manage EKS clusters. It includes actions like eks:CreateCluster, eks:DescribeCluster, eks:UpdateClusterConfig, eks:DeleteCluster, etc. AmazonEKSServicePolicy: This policy allows the necessary permissions for the EKS service to manage resources on your behalf. It includes actions like eks:DescribeUpdates, eks:ListClusters, eks:ListUpdates, etc. AmazonEKSServiceRolePolicy: This policy is attached to the IAM role assumed by the EKS service.
Read More
Show the Top 10 Largest Directories on Linux
March 13, 2024
If you need to see the top 10 largest directories on your Linux system, you can use the following command: du -h --max-depth=1 / | sort -rh | head -n 11 Alternative If you are okay to install additional software, then you can use a tool like ncdu to do the same, but with a lot more options and more features. Installing ncdu ncdu is a software package that standards for “NCurses Disk Usage” and is a disk utility tool for Unix based systems.
Read More
Cloud Cost Optimization Strategies: Maximizing ROI in the Cloud
March 1, 2024
As organizations continue to migrate workloads to the cloud, many are experiencing the phenomenon known as “cloud shock”—the realization that cloud costs are significantly higher than anticipated. While the cloud offers tremendous benefits in terms of agility, scalability, and innovation, these advantages can come at a substantial cost if not managed properly. According to Gartner, through 2024, nearly 60% of organizations will encounter public cloud cost overruns that negatively impact their budgets.
Read More
Retrieve the Latest Versioned Tag from AWS ECR in Bash
February 21, 2024
Managing Docker images in Amazon Elastic Container Registry (ECR) is a common task for many developers and DevOps practitioners. Often, you need to retrieve the latest versioned tag from a repository to streamline deployment processes or ensure compatibility with the most recent features or fixes. In this post, we’ll explore a simple Bash command using the AWS CLI and jq to fetch the latest versioned tag from an ECR repository.
Read More
Designing Scalable Systems in AWS: Architecture Patterns for Growth
February 5, 2024
In today’s digital landscape, building systems that can scale effectively is no longer a luxury—it’s a necessity. Whether you’re launching a startup that might experience overnight success or managing enterprise applications with predictable but substantial growth, your architecture must be designed to scale seamlessly. Amazon Web Services (AWS) provides a rich ecosystem of services and tools to build highly scalable systems, but knowing how to leverage these resources effectively requires understanding key architectural patterns and best practices.
Read More
How to install MySQL on AmazonLinux2023
January 29, 2024
If you are using Amazon Linux 2023 base-image, and you have tried to run yum install -y mysql, you will soon realize that it doesn’t work. Instead install MySQL on Amazon Linux 2023 like this: sudo dnf update -y sudo dnf install mariadb105-server For advanced use-cases where you are installing this in a Docker-in-Docker environment, do it without the sudo, as follows: dnf update -y dnf install mariadb105-server Now if you run mysql, you will no longer get the mysql: command not found message.
Read More
Choosing the Right Cloud Architecture: A Decision Framework for Modern Applications
January 15, 2024
In today’s rapidly evolving technology landscape, selecting the right cloud architecture is one of the most consequential decisions that organizations face. The architecture you choose not only impacts your application’s performance, scalability, and reliability but also significantly affects your development velocity, operational overhead, and total cost of ownership. With multiple architectural patterns available—from traditional monoliths to microservices, serverless, and various hybrid approaches—making an informed decision requires a structured approach that considers your specific business context, technical requirements, and organizational constraints.
Read More
Run any version of Terrform using Docker
December 22, 2023
So our friend Docker comes around for another usecase. Run Terraform (any version) from Docker In this example, we will try and configure Terraform 1.4.0 through Docker, so that we don’t need to install it on our host system. alias terraform14='docker run --rm -it -w $PWD:$PWD -v $PWD:$PWD hashicorp/terraform:1.4.0' To use it, we simply run a Terraform command: terraform14 -version Next let’s try another Terraform version as well alias terraform15='docker run --rm -it -w $PWD:$PWD -v $PWD:$PWD hashicorp/terraform:1.
Read More
Select * to Show Database Table Sizes MariaDB
December 21, 2023
In database management, understanding the size of your tables is crucial for optimizing performance and ensuring efficient resource utilization. If you’re a technical enthusiast or a seasoned database administrator working with MariaDB, this blog post is tailored just for you. Today, we’ll unravel the mystery behind MariaDB database table sizes using a powerful SQL query. SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024/1024/1024 AS TABLE_SIZE_in_MB FROM information_schema.TABLES ORDER BY TABLE_SIZE_in_MB DESC Exploring MariaDB Table Sizes MariaDB stands out as a robust and reliable option.
Read More
The Future Prospects of DevOps in an AI World
November 20, 2023
Abstract DevOps has become an integral part of modern software development, emphasizing communication and collaboration between software developers and IT operations professionals. However, with the rise of artificial intelligence (AI), the future role and necessity of devops has been brought into question. This paper explores the prospects for devops in an increasingly AI-driven world, including devops’ potential contributions to and collaboration with AI, as well as the possibility of eventual replacement by intelligent systems.
Read More
Supercharge Your Code with Amazon CodeWhisperer
October 29, 2023
Amazon CodeWhisperer is a cutting-edge service that leverages advanced AI and machine learning to provide real-time code generation, recommendations, and security analysis. As a developer, CodeWhisperer can supercharge your productivity and code quality. Key Capabilities Neural Code Generation CodeWhisperer utilizes powerful neural networks to generate code snippets and entire functions on demand. The advanced models are trained on millions of code samples and can produce idiomatic, human-readable code for a wide variety of programming languages.
Read More
A Deep Dive into Machine Learning Algorithms
October 28, 2023
Machine learning algorithms are the backbone of modern artificial intelligence. They enable computers to learn and make predictions or decisions without being explicitly programmed. In this comprehensive guide, we will delve into common machine learning algorithms, providing detailed explanations and code examples to help you understand their inner workings. Whether you’re a beginner or an experienced data scientist, this post will be a valuable resource to enhance your understanding of machine learning.
Read More
What is GitHub? A Comprehensive Guide from Basics to Advanced
October 27, 2023
GitHub is a platform that has revolutionized the world of software development, enabling individuals and teams to collaborate efficiently on projects of all sizes. In this comprehensive guide, we’ll explore GitHub from the very basics to the most advanced features. Whether you’re a novice or an experienced developer, you’ll find valuable insights and tips to enhance your understanding of GitHub. Part 1: Git Basics Before diving into GitHub, it’s essential to grasp the fundamental concepts of Git, the version control system that underlies GitHub.
Read More
Connect IPv4 and IPv6 Networks Seamlessly with Amazon VPC Lattice
October 26, 2023
As the internet continues to grow, the transition from IPv4 to IPv6 has become more critical. Organizations need to manage both IP stacks efficiently and ensure seamless connectivity. Amazon Web Services (AWS) offers a groundbreaking solution: Amazon VPC Lattice. In this advanced guide, we’ll delve deeper into Amazon VPC Lattice, its technical details, and provide code examples for advanced users. A Lattice of Connectivity Amazon VPC Lattice simplifies the coexistence of IPv4 and IPv6 stacks within your Virtual Private Cloud (VPC).
Read More
Building Event-Driven Architectures with Amazon EventBridge
October 25, 2023
In the realm of real-time data streaming applications, managing the routing and processing of events efficiently is a complex challenge. Amazon Web Services (AWS) has a powerful solution: Amazon EventBridge. In the realm of real-time data streaming applications, managing the routing and processing of events efficiently is a complex challenge. Amazon Web Services (AWS) has a powerful solution: Amazon EventBridge. In this advanced guide, we’ll delve deeper into EventBridge, its key concepts, and provide code examples for advanced users.
Read More
Splitting Terraform Modules into Separate Git Repositories
October 24, 2023
In the world of Infrastructure as Code (IaC) , Terraform has emerged as a powerful tool for managing infrastructure resources. As your Terraform codebase grows, managing monolithic code can become challenging. In this advanced-level blog post, we will explore the process of moving Terraform modules into separate Git repositories and referencing these modules across multiple repositories. This approach can help you achieve better code organization, reusability, and collaboration in your infrastructure provisioning projects.
Read More
Accelerating Machine Learning with SageMaker Jumpstart
October 22, 2023
Machine learning (ML) projects can be complex, time-consuming, and resource-intensive. Amazon SageMaker Jumpstart aims to change that by providing pre-built solutions, pre-trained models, and end-to-end ML capabilities. In this advanced guide, we’ll dive deep into SageMaker Jumpstart and provide code examples to illustrate its power. Unleashing ML Potential Amazon SageMaker Jumpstart is designed to accelerate your ML journey. It offers a wide range of pre-built solutions and pre-trained models for various ML use cases, including natural language processing, computer vision, and more.
Read More
Understanding the AWS Well-Architected Framework
October 19, 2023
The AWS Well-Architected Framework is more than just a set of best practices; it’s a blueprint for success in the cloud. It offers a comprehensive guide to building high-quality, efficient, and cost-effective architectures on Amazon Web Services (AWS). In this blog post, we’ll delve into the key principles and pillars of the AWS Well-Architected Framework and explore how you can leverage it to ensure your cloud infrastructure is robust and resilient.
Read More
Mastering Advanced Networking in EKS and Kubernetes
October 16, 2023
Kubernetes has revolutionized container orchestration, and Amazon’s Elastic Kubernetes Service (EKS) is one of the most popular managed Kubernetes solutions available today. While getting started with EKS and Kubernetes is relatively straightforward, mastering advanced networking topics is essential for managing complex workloads and achieving optimal performance. In this comprehensive guide, we will explore advanced networking concepts in EKS and Kubernetes, accompanied by code examples and practical insights. 1. VPC Design and EKS Setup When working with EKS , it’s crucial to have a well-architected VPC.
Read More
How to Ignore SSL Certificates Globally in Git
October 14, 2023
In the world of software development, Git is an indispensable tool for version control. However, when working with repositories that use SSL certificates , you might encounter situations where you need to ignore SSL certificate verification globally. Whether it’s for testing or debugging purposes, this guide will show you how to ignore SSL certificates globally in Git and even disable SSL certificate checks altogether. We’ll cover everything from the basics to advanced configurations to help you manage SSL certificates effectively in your Git workflow .
Read More
Semantic Versioning with npm
October 13, 2023
Semantic Versioning, often referred to as SemVer, is a crucial convention within the Node.js ecosystem. It provides a clear and structured way of versioning software, ensuring that developers can easily understand the impact of version changes. In this blog post, we’ll explore the principles of Semantic Versioning and how npm (Node Package Manager ) leverages it to manage packages effectively. Understanding Semantic Versioning Semantic Versioning is based on a three-digit version number, often expressed as x.
Read More
Understanding Peer Dependencies in Node Modules
October 12, 2023
When working with Node.js and managing packages for your projects, you’re likely familiar with the dependencies and devDependencies sections in a package.json file. These sections define the packages your project depends on for both production and development purposes. However, there’s another crucial field often overlooked but equally important: peerDependencies. In this blog post, we will delve into the concept of peerDependencies and how they differ from regular dependencies and devDependencies.
Read More
How to Programmatically get Amazon IP Ranges/CIDRs
October 11, 2023
Amazon Web Services (AWS) operates an extensive network infrastructure with a vast number of IP addresses and CIDR blocks. As a developer or network administrator, you may need to programmatically retrieve the IP ranges or CIDRs associated with AWS regions and services for various reasons, such as configuring firewall rules or network security groups. In this guide, we’ll show you how to accomplish this using Python. Prerequisites Before we dive into the code, make sure you have the following prerequisites in place:
Read More
The Ultimate Guide to Emacs: Mastering the Art of CLI Programming
October 10, 2023
In the realm of command-line interface (CLI) programming, Emacs stands as a legendary text editor, known for its immense power and unparalleled extensibility. For decades, Emacs has been the tool of choice for seasoned CLI programmers who demand efficiency and customization. In this ultimate guide, we will explore advanced and expert ways to harness the full potential of Emacs, helping you become an amazing CLI programmer. Introduction to Emacs What is Emacs?
Read More
The Ultimate Guide to VI: Mastering the Art of CLI Programming
October 9, 2023
In the world of command-line interface (CLI) programming, efficiency is paramount. And when it comes to text editing in the CLI, there’s no tool more legendary than VI. This powerful, yet enigmatic text editor has been the choice of seasoned CLI programmers for decades. In this ultimate guide, we will explore advanced and expert ways to harness the full potential of VI, helping you become an amazing CLI programmer. Introduction to VI What is VI?
Read More
AWS Assume to another role
October 8, 2023
OUT=$(aws sts assume-role --role-arn arn:aws:iam::0123456789:role/OrganizationAccountAccessRole --role-session-name test) export AWS_ACCESS_KEY_ID=$(echo $OUT | cut -d '"' -f 6 ) export AWS_SECRET_ACCESS_KEY=$(echo $OUT | cut -d '"' -f 10 ) export AWS_SESSION_TOKEN=$(echo $OUT | cut -d '"' -f 14 ) aws sts get-caller-identity
Read More
Programming Languages Series
October 2, 2023
1. Introduction Welcome to our Programming Languages Series! In this series, we’ll explore various programming languages, understand their purposes, provide code examples, and discuss when to use each one. Let’s begin with an introduction to programming languages. What Are Programming Languages? Programming languages are a means of communication between humans and computers. They allow developers to instruct computers to perform specific tasks, ranging from simple calculations to complex data processing and application development.
Read More
Docker Deep Dive Series
September 22, 2023
1. Getting Started In this first part of the series, we will kick things off by getting Docker installed and running on your system. Docker makes it easy to package and distribute applications as containers, ensuring consistent environments across different stages of the development and deployment pipeline. Let’s jump right in and get Docker up and running! Prerequisites Before we start, ensure that you have the following prerequisites installed on your system:
Read More
Machine Learning Mastery Series
September 13, 2023
Part 1. Introduction to Machine Learning Welcome to the Machine Learning Mastery Series, a comprehensive journey into the exciting world of machine learning. In this first installment, we’ll lay the foundation by exploring the fundamentals of machine learning, its types, and the essential concepts that underpin this transformative field. What is Machine Learning? Machine learning is a subfield of artificial intelligence (AI) that focuses on developing algorithms and models that enable computers to learn from and make predictions or decisions based on data.
Read More
Kubernetes Mastery
September 3, 2023
Part 1. Introduction Welcome to the Kubernetes Mastery Series! In this first part, we’ll set up a Kubernetes cluster using KinD (Kubernetes in Docker). Prerequisites: Docker kubectl KinD # Step 1: Install Docker # Step 2: Install kubectl # Step 3: Install KinD # Step 4: Create a KinD cluster kind create cluster --name my-cluster --config - <<EOF kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane - role: worker - role: worker EOF # Step 5: Set kubectl context kubectl cluster-info --context kind-my-cluster # Step 6: Verify cluster nodes kubectl get nodes Part 2.
Read More
Managing Multiple Environments with Terraform Workspaces
September 2, 2023
Managing infrastructure across multiple environments such as development, staging, and production can be a daunting task. Terraform, a popular Infrastructure as Code (IaC) tool, offers a powerful feature known as workspaces that can help you efficiently manage and maintain separate environments within a single configuration. In this technical blog post, we’ll explore Terraform workspaces, how they work, and best practices for utilizing them effectively. Understanding Terraform Workspaces Terraform workspaces provide a way to manage distinct instances of the same infrastructure configuration.
Read More
Controlling and Understanding Parallelism Impact on the DAG
September 1, 2023
When working with large-scale infrastructure deployments, managing the provisioning and orchestration of resources efficiently becomes crucial. Terraform, a widely-used Infrastructure as Code (IaC) tool, offers a feature known as parallelism to accelerate the deployment process. In this blog post, we’ll delve into parallelism in Terraform, how it affects the Directed Acyclic Graph (DAG), and how you can control and optimize its usage. Understanding Parallelism and the DAG Parallelism refers to the ability to execute multiple tasks simultaneously.
Read More
How to add Payment Subscriptions with Stripe in Django
August 31, 2023
Integrating Stripe subscriptions into your Django site involves several steps. Here’s a high-level overview of the process. Please note that the exact implementation can vary based on your specific requirements. Steps involved Sign Up and Set Up Stripe Account If you haven’t already, sign up for a Stripe account at https://stripe.com . Once you’ve signed up, you’ll need your API keys: a Publishable Key (for the client-side) and a Secret Key (for server-side interactions).
Read More
Private Application Load Balancer for EKS in Terraform
August 30, 2023
Amazon Web Services (AWS) provides a powerful combination of services for building, deploying, and managing applications. Amazon Elastic Kubernetes Service (EKS) is a managed Kubernetes service that simplifies the process of deploying, managing, and scaling containerized applications using Kubernetes. In certain scenarios, you might want to deploy a private Application Load Balancer (ALB) in front of your private EKS cluster to handle incoming traffic efficiently. In this guide, we’ll walk through the process of setting up a private ALB for your private EKS cluster using Terraform, along with best practices and intricate details.
Read More
Kubernetes vs Docker Swarm for Container Orchestration
August 29, 2023
Container orchestration has become a cornerstone of modern application deployment and management. Two prominent contenders in the realm of container orchestration are Kubernetes and Docker Swarm. Both offer powerful solutions for automating the deployment, scaling, and management of containerized applications. In this in-depth comparison, we’ll delve into the strengths, features, and nuances of Kubernetes and Docker Swarm to help you make an informed choice for your container orchestration needs. Understanding Kubernetes Kubernetes, often referred to as K8s, has emerged as a de facto standard for container orchestration.
Read More
Setting Comprehensive CI/CD Pipeline with Jenkins and Docker
August 28, 2023
In today’s dynamic software landscape, the fusion of Continuous Integration and Continuous Deployment (CI/CD) pipelines with robust tools like Jenkins and Docker has emerged as a cornerstone of efficient and reliable application delivery. This detailed tutorial will provide you with an in-depth walkthrough, guiding you step by step through the intricate process of configuring a comprehensive CI/CD pipeline using Jenkins and Docker. By the end of this tutorial, you’ll be equipped to seamlessly incorporate DevOps practices, elevating your software delivery process to new heights.
Read More
Navigating Microsoft Azure for Seasoned AWS Experts
August 27, 2023
In the ever-evolving landscape of cloud computing, two mammoth players, Amazon Web Services (AWS) and Microsoft Azure, have emerged as titans, offering an extensive array of services that cater to a diverse spectrum of business needs. If you’ve already amassed a wealth of knowledge and experience in AWS and are now yearning to broaden your cloud horizons, this comprehensive guide is designed to be your compass. Together, we’ll embark on a journey to seamlessly transition your AWS proficiency into the realm of Microsoft Azure, unraveling parallels between their services and enriching your cloud expertise.
Read More
Navigating Google Cloud Platform (GCP) for AWS Experts
August 26, 2023
In today’s rapidly evolving landscape of cloud computing, Amazon Web Services (AWS) and Google Cloud Platform (GCP) have emerged as prominent contenders, furnishing an extensive array of services tailored to cater to the dynamic requirements of modern businesses. If you’re already versed in the intricacies of AWS and are now seeking to broaden your cloud horizons, this comprehensive guide is poised to be your beacon. We’ll embark on a journey of bridging the gap between your existing AWS proficiency and your newfound GCP expertise, ensuring your transition is not just smooth, but also illuminating.
Read More
Create a slug from a name in MySQL/MariaDB
August 25, 2023
How to create a slug from the name of an item in MySQL/MariaDB. UPDATE my_table SET slug = LOWER(REGEXP_REPLACE(REPLACE(REPLACE(REPLACE(name, ' ', '-'), 'and', '-'), '[^a-zA-Z0-9-]', ''), '-+', '-'));
Read More
How to Get a List of Available Regions from AWS CLI
August 23, 2023
AWS (Amazon Web Services) is a prominent cloud service provider that offers a wide range of services to businesses and individuals worldwide. One of the fundamental concepts in AWS is regions, which are distinct geographical locations hosting AWS infrastructure. Understanding regions is crucial for optimizing your cloud infrastructure’s performance, data residency, and compliance requirements. In this blog post, we’ll dive into the world of AWS regions, learn how to list available regions using the AWS CLI, and explore a handy command to fetch region details in a more reader-friendly format.
Read More
[Solved] A Number After a Double Reversal in Python
August 22, 2023
The problem Reversing an integer means to reverse all its digits. For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false. Example 1: Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.
Read More
Common Issues and Mastering Effective Debugging Techniques
August 21, 2023
While Kubernetes offers a powerful platform for deploying containerized applications, managing complex clusters can sometimes lead to challenges and errors. In this comprehensive blog post, we will delve into common issues that arise in Kubernetes clusters and equip you with effective troubleshooting and debugging methodologies. By the end, you’ll be empowered to unravel the mysteries of Kubernetes troubleshooting and confidently resolve issues to ensure the seamless operation of your clusters.
Read More
K8s CI/CD: GitOps with Jenkins, GitLab, Argo CD
August 20, 2023
Continuous Integration and Continuous Deployment (CI/CD) pipelines are fundamental to the success of Kubernetes deployments , enabling fast and reliable application delivery. In this comprehensive blog post, we will explore CI/CD pipelines customized for Kubernetes, including the GitOps approach, and how to leverage popular tools like Jenkins, GitLab, and Argo CD. By the end, you’ll be equipped with actionable insights to build efficient CI/CD pipelines that seamlessly integrate with your Kubernetes ecosystem.
Read More
K8s Monitoring & Logging: Best Practices & Top Tools
August 19, 2023
Monitoring and logging are critical components of a successful Kubernetes deployment , providing insights into the health, performance, and behavior of your clusters and applications. In this comprehensive blog post, we will cover best practices for monitoring Kubernetes, including node and pod metrics, as well as exploring popular monitoring and logging tools such as Prometheus, Grafana, and Elasticsearch. By the end, you’ll be equipped with actionable knowledge to set up robust observability for your Kubernetes ecosystem, enabling you to detect issues proactively and ensure smooth operations.
Read More
K8s Upgrades & Rollbacks Guide to Compatibility & Strategies
August 18, 2023
Keeping your Kubernetes cluster up-to-date is crucial for security, performance, and accessing the latest features. However, orchestrating Kubernetes upgrades and rollbacks can be a challenging endeavor. In this all-encompassing blog post, we will dive into the complexities of Kubernetes upgrades, exploring version compatibility considerations, the power of rolling updates, and the importance of robust rollback strategies. By the end, you’ll be equipped with actionable insights to navigate Kubernetes upgrades and rollbacks with confidence, ensuring your cluster remains resilient and always up-to-date.
Read More
K8s Pod Scheduling: Node & Pod Affinity Demystified
August 17, 2023
Efficient pod scheduling is essential to achieving high performance and resource utilization in a Kubernetes cluster. Understanding the intricacies of pod scheduling, particularly node affinity, pod affinity, and anti-affinity rules, empowers you to distribute workloads effectively. In this comprehensive blog post, we will explore the art of pod scheduling in Kubernetes , shedding light on the power of node affinity, enhancing resource allocation with pod affinity, and ensuring fault tolerance through anti-affinity.
Read More
Securing Kubernetes: Guarding Against Container Threats
August 16, 2023
Kubernetes has become the de facto platform for deploying containerized applications , revolutionizing software development. However, with great power comes great responsibility, and security is paramount in a Kubernetes environment. In this comprehensive blog post, we will delve into the critical security concerns in Kubernetes, covering the protection of the API server, implementing Role-Based Access Control (RBAC), fortifying with Network Policies, and mitigating container vulnerabilities. By the end, you’ll have actionable tips to build a robust Kubernetes fortress, protecting your applications and data from potential security risks.
Read More
K8s Cluster Performance: Resource Optimization Guide
August 15, 2023
Efficiently managing resources in a Kubernetes cluster is crucial to achieving peak performance and cost-effectiveness. Resource allocation, utilization, and handling resource-intensive applications demand careful consideration. In this comprehensive blog post, we will delve into best practices for resource management, exploring resource allocation techniques, monitoring, and optimizing resource-hungry applications. By the end, you’ll be armed with the knowledge to optimize your Kubernetes cluster for maximum productivity and resource efficiency. Understanding Resource Management in Kubernetes Resource management involves allocating CPU, memory, and other resources to applications running in a Kubernetes cluster.
Read More
K8s Scaling Mastery: Manual, HPA & Metrics APIs
August 14, 2023
Kubernetes has revolutionized application deployment by providing a scalable and efficient container orchestration platform. However, as your applications grow, you’ll encounter the challenge of efficiently scaling them to meet varying demands. In this in-depth blog post, we will explore the intricacies of scaling applications in Kubernetes , discussing manual scaling, Horizontal Pod Autoscalers (HPA), and harnessing the power of Kubernetes Metrics APIs. By the end, you’ll be equipped with the knowledge to elegantly scale your applications, ensuring they thrive under any workload.
Read More
K8s Storage Demystified: Persistent Volumes & Classes
August 13, 2023
Kubernetes has become the go-to platform for deploying scalable, containerized applications. However, managing persistent data in a dynamic container environment presents unique challenges. In this comprehensive blog post, we’ll delve into the world of Kubernetes persistent storage, exploring the various approaches like Persistent Volumes (PVs) and Storage Classes (SCs). We’ll also shed light on common issues such as data loss and performance bottlenecks, equipping you with the knowledge to ensure data integrity and optimal storage performance within your Kubernetes clusters.
Read More
K8s Networking: Pod Communication and Ingress Demystified
August 12, 2023
Kubernetes has revolutionized the way we deploy and manage containerized applications . However, with the increasing complexity of distributed systems, networking and communication between pods within a Kubernetes cluster can become a daunting challenge. In this blog post, we will delve into the common networking issues that arise in Kubernetes and explore effective solutions using Service Discovery and Ingress controllers. By the end, you’ll have a clearer understanding of how to ensure seamless communication between your pods, enabling your applications to thrive in the Kubernetes ecosystem.
Read More
React State Balancing: A Guide to State Management
August 11, 2023
As React apps grow, managing shared and app-wide state can become challenging. Dedicated state management libraries help tackle these complexities. Let’s compare popular options: Redux Redux uses a centralized store for state: // Store with root reducer const store = createStore(rootReducer); // Dispatch actions store.dispatch(addTodo(text)); // Selectors const todos = useSelector(state => state.todos); Redux enforces unidirectional data flow inspired by functional programming. MobX MobX uses observable variables that update reactively:
Read More
React + Node: Beginner's Guide to Full Stack Dev
August 10, 2023
React excels at building fast, dynamic frontends. Node.js shines for server-side APIs and microservices. Together, they make a powerful stack for full stack apps. Let’s walk through integrating React with Node.js: Serving React Builds Use Node.js middleware like Express to serve the React app: // server.js app.use(express.static(path.join(__dirname, 'client/build'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html)); }); This serves the React build from the /build folder. Proxying API Requests Proxy frontend requests to the backend API:
Read More
Optimal React Patterns: Beginner's Guide
August 9, 2023
As with any framework, React comes with its own set of best practices and optimal patterns. Let’s explore some tips for writing robust React code: Modular Components Break components into reusable, composable units: // Bad function App() { return ( <header> <nav> <logo> <links> </nav> <h1>Welcome!</h1> <footer> <copyright> </footer> </header> ); } // Good function Nav() { return ( <nav> <Logo /> <Links /> </nav> ); } function Header() { return ( <header> <Nav /> <h1>Welcome!
Read More
Debugging React Apps: Beginner's Guide
August 8, 2023
Bugs are inevitable in complex React applications. Thankfully, React provides great tools to squash bugs quickly. Let’s look at some key techniques for debugging React apps: React Developer Tools The React DevTools Chrome extension lets you inspect React component hierarchies, props, state and more in Chrome: DevTools: <App> <Navbar /> <Profile name="Jane" imageUrl="https://..." /> </App> This provides invaluable visibility into React apps. Error Boundaries Error boundaries catch errors and display fallbacks:
Read More
Advanced React Patterns: Compound Components & More
August 7, 2023
As React apps scale, you’ll want to structure components for greater reusability and composability. Here are some powerful React patterns: Compound Components The compound components pattern creates component APIs with shared context: // Parent exposes context through 'Box' component function Layout({children}) { return <Box>{children}</Box> } // Children access shared context via Box function Profile() { return ( <Layout> <Box p={2}> <h1>Jane Doe</h1> </Box> </Layout> ); } This provides more flexible APIs than just props.
Read More
React Animation Guide: Libraries and Techniques
August 6, 2023
Animation brings interfaces to life. Thankfully, React has great open source libraries for animation. Let’s compare some popular options: Framer Motion Framer Motion uses declarative props for animation: import { motion } from 'framer-motion'; const boxVariants = { hidden: { opacity: 0 }, visible: { opacity: 1 }, } function MyComponent() { return ( <motion.div initial="hidden" animate="visible" variants={boxVariants} /> ); } Framer Motion allows CSS, SVG, gesture, and physics animations.
Read More
Testing React Apps: Beginner's Guide to TDD
August 5, 2023
Testing is crucial for ensuring React apps are stable and bug-free. Popular tools like Jest and React Testing Library make testing React components simple. Let’s look at how to write great tests for React: render Component Render the component into a test environment using render from React Testing Library: import { render } from '@testing-library/react'; import Button from './Button'; test('displays button text', () => { const { getByText } = render(<Button>Click</Button>); expect(getByText('Click')).
Read More
Data Fetched Fast - A Beginner's Guide to React Query
August 4, 2023
Fetching data in React often means using stale state and complex caching logic. React Query simplifies data fetching with powerful features like automatic caching, deduplication, and background updates. Let’s explore some key features of React Query: Declarative Data Fetching Fetch data with the useQuery hook: import { useQuery } from 'react-query'; function MyComponent() { const { data, error, isLoading } = useQuery('posts', fetchPosts); // use data } useQuery handles declaring cache keys, performing fetches, and more.
Read More
Forms Simplified, A Beginner's Guide to Managing React Forms
August 3, 2023
Forms are a common need for many React apps. However, managing form state and validation can be tricky. Thankfully, React provides great libraries to simplify complex forms. Let’s explore some helpful tools: Formik for Form State Formik handles common form tasks: import { Formik } from 'formik'; const MyForm = () => ( <Formik initialValues={{ email: '' }} onSubmit={values => console.log(values)} > {formik => ( <form onSubmit={formik.handleSubmit}> <input name="email" onChange={formik.handleChange} value={formik.
Read More
Optimizing React Performance: Beginner's Guide
August 2, 2023
As React apps grow, you may notice performance starting to lag - sluggish interactions, choppy animations, janky scrolling. Luckily, there are many great techniques to optimize React app performance. Let’s look at some top tips: Use React.memo for Component Memoization The React.memo API can memoize component outputs: const MyComponent = React.memo(function MyComponent(props) { /* only rerenders if props change */ }); This prevents unnecessary re-renders if props stay the same.
Read More
State Management 101 - A Beginner's Guide to React State
August 1, 2023
State management is a crucial concept in React. State allows components to dynamically update UI based on data changes. However, managing state properly takes some practice. Let’s walk through the basics of handling state in React: Creating State The useState hook defines state variables: import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); } useState accepts the initial state value and returns: The current state A function to update it Reading State To display state in UI, simply reference the variable:
Read More
Accessible React Apps: Beginner's Guide to Accessibility
July 31, 2023
Accessibility is an important consideration when building modern web apps. React provides useful tools to make accessible, inclusive products. Let’s look at some best practices for web accessibility with React: Semantic HTML Use proper HTML semantics. For example: // Good <button>Save</button> // Avoid <div onclick="save">Save</div> Semantic HTML is parsed correctly by screen readers. alt Text Images should have alt text describing content/purpose: <img src="logo.png" alt="Company logo" /> Screen readers can’t interpret images.
Read More
Mystery Boxes - A Beginner's Guide to React Fragments
July 30, 2023
When returning multiple elements from a component’s render method, they must be wrapped in a single parent DOM node: // Needs a <div> wrapper return ( <div> <ChildA /> <ChildB /> </div> ); This extra wrapper <div> in the DOM is often unwanted. Enter React fragments - a way to group elements without adding extra nodes. Short Syntax The simplest fragment syntax is: return ( <> <ChildA /> <ChildB /> </> ); The <></> syntax declares a React fragment.
Read More
Unidirectional Data Flow in React: Beginner's Guide
July 29, 2023
A key advantage of React is its unidirectional data flow. This makes the flow of data predictable, and helps avoid unexpected side effects from data changing unexpectedly. But what exactly does “unidirectional data flow” mean in React? Let’s break it down: The Data Flows Down In React, parent components pass data to children via props: // Parent function Parent() { const [value, setValue] = useState('Hello'); return <Child value={value} />; } // Child function Child({value}) { return <h1>{value}</h1>; } The parent’s value state is passed down into the Child via a prop.
Read More
Event Handling in React: Beginner's Guide
July 28, 2023
Responding to user events is a crucial part of building interactive UIs. In React, you can pass event handlers as props to components to run code when events occur. Let’s look at how to listen and react to common events in React: Binding to Events Pass an event handler function to a component to subscribe to events: function Button({ onClick }) { return ( <button onClick={onClick}> Click Me </button> ); } function App() { const handleClick = () => { console.
Read More
Hooked on React - A Beginner's Guide to React Hooks
July 27, 2023
When React was first released, class components were the standard way to build complex UIs. However, classes can be cumbersome for some use cases. Enter React hooks - a way to use React features like state and lifecycle methods without classes. Hooks provide a more direct API for React concepts you already know. Let’s dive into some commonly used hooks: Managing State with useState The useState hook lets components use state without a class:
Read More
Lifting State in React: Beginner's Guide
July 26, 2023
As React apps grow in complexity, managing shared state between components can become tricky. Oftentimes, several child components may need to reflect the same data in the UI. The React solution is to lift the state up to a common ancestor component. The parent component can manage the state, and pass it down to the children via props. Let’s look at how to lift state for easier data sharing: The Problem with Local State Imagine we have a <Toolbox> component that contains some <Tool> components:
Read More
Looping in JSX with React Keys: Beginner's Guide
July 25, 2023
Looping over arrays to render lists of elements is a common need in React apps. However, there are some special considerations when rendering lists in JSX. One important aspect is the key prop. React uses keys to uniquely identify list elements and optimize performance. Let’s look at how to loop through arrays in JSX, and why keys are important: Rendering Arrays in JSX JSX makes looping straightforward - you can use JavaScript’s map() function directly:
Read More
Conditional Rendering in React
July 24, 2023
In React apps, you’ll often need to render different UI components conditionally based on certain state. For example, showing a login form if a user is not authenticated, or displaying different content based on configurable settings. Here are useful patterns for conditional rendering in React: If/Else Statements The standard JS if/else statement works in JSX too: function App() { const loggedIn = false; if (loggedIn) { return <WelcomeMessage />; } else { return <LoginForm />; } } This will render either the WelcomeMessage or LoginForm component based on the value of loggedIn.
Read More
Passing Data Between React Components with Props
July 23, 2023
One of React’s core concepts is reusability through composable components. Components allow splitting complex UI into separate, reusable pieces. However, for components to communicate, they need a way to pass data to each other. Enter props. Props allow passing data from a parent component to a child component. They are like function parameters, but for React components. Let’s look at a simple example: // Parent component const Parent = () => { return ( <Child color="blue" onClick={handleClick} /> ); } // Child component const Child = (props) => { return <div>{props.
Read More
Fostering DevOps Learning Culture: Lifelong Learning
July 22, 2023
Introduction In the fast-evolving world of technology, where advancements and innovations are a constant, staying ahead of the curve is paramount for any DevOps team. One of the most effective ways to achieve this is by fostering a continuous learning culture. Embracing a mindset of lifelong learning not only empowers individuals to enhance their skills and knowledge but also drives collective growth and innovation within the organization. In this blog post, we will explore the significance of building a continuous learning culture in DevOps, its impact on team performance, and practical strategies to implement and sustain such a culture.
Read More
DevOps' Role in AI: Enhancing Intelligent Systems
July 21, 2023
Introduction The world of technology is witnessing a remarkable fusion of two transformative disciplines: DevOps and Artificial Intelligence (AI). DevOps has revolutionized software development, emphasizing collaboration, automation, and continuous delivery, while AI has pushed the boundaries of what machines can achieve, enabling intelligent decision-making and automation. In this blog post, we will explore the symbiotic relationship between DevOps and AI, the challenges and opportunities it presents, and how organizations can leverage this powerful combination to unlock the full potential of intelligent systems.
Read More
DevOps and Microservices: Scalable, Agile Software Delivery
July 20, 2023
Introduction In the fast-paced world of software development, two crucial methodologies have emerged as game-changers for modern development teams: DevOps and Microservices. DevOps is a cultural and technical movement that emphasizes collaboration, automation, and continuous delivery, while Microservices is an architectural style that structures applications as a collection of loosely coupled, independently deployable services. Combining these methodologies can empower organizations to achieve scalable, agile, and efficient software delivery. In this blog post, we will explore the intersection of DevOps and Microservices, their synergies, and how they complement each other.
Read More
Nature-Inspired Problem Solving: Genetic Algorithms
July 19, 2023
Introduction Genetic Algorithms (GAs) and Evolutionary Computation (EC) are powerful optimization techniques inspired by the process of natural selection and evolution. These algorithms mimic the principles of genetics and survival of the fittest to find high-quality solutions to complex problems. In this blog post, we will dive into the world of Genetic Algorithms and Evolutionary Computation, exploring their underlying concepts and demonstrating how they can be implemented in Python to tackle a variety of real-world challenges.
Read More
Python Dynamic Programming: Mastering Optimization
July 18, 2023
Introduction Dynamic programming is a powerful algorithmic technique that allows developers to tackle complex problems efficiently. By breaking down these problems into smaller overlapping subproblems and storing their solutions, dynamic programming enables the creation of more adaptive and resource-efficient solutions. In this comprehensive guide, we will explore dynamic programming in-depth and learn how to apply it in Python to solve a variety of problems. 1. Understanding Dynamic Programming Dynamic programming is a method of solving problems by breaking them down into smaller, simpler subproblems and solving each subproblem only once.
Read More
Python Reflection & Metaprogramming: Advanced Power
July 17, 2023
Introduction Python is a versatile programming language that offers powerful features and capabilities. For advanced users, understanding and harnessing the potential of reflection and metaprogramming can open up a whole new world of possibilities. In this blog post, we’ll dive deep into the concepts of reflection and metaprogramming in Python, exploring their definitions, use cases, and implementation techniques. By mastering reflection and metaprogramming, you can build resilient, scalable, and highly adaptable applications.
Read More
Kubernetes ReplicaSets: Scalability & Fault Tolerance
July 16, 2023
Introduction In Kubernetes, ReplicaSets are a vital resource that enables scalable and fault-tolerant deployments of pods. They provide the ability to ensure a desired number of pod replicas are running at all times, allowing applications to handle increased traffic and recover from failures. In this blog post, we will delve into the world of ReplicaSets, exploring their functionalities, use cases, and best practices. By mastering ReplicaSets, you can build resilient and scalable deployments in Kubernetes.
Read More
Kubernetes Namespaces: Isolation & Resource Management
July 15, 2023
Introduction In Kubernetes, namespaces provide a powerful abstraction that allows you to partition and isolate resources within a cluster. In this blog post, we’ll explore Kubernetes namespaces in detail and discuss their importance in achieving effective resource management and isolation. By understanding namespaces and leveraging their capabilities, you can enhance the security, scalability, and manageability of your Kubernetes deployments . Let’s dive into the world of namespaces and unlock their potential!
Read More
K8s Cluster Resiliency: Advanced High Availability
July 14, 2023
Introduction In today’s technology landscape, ensuring the resiliency and high availability of Kubernetes clusters is crucial for maintaining the availability of applications and business continuity. In this blog post, we will explore advanced techniques and best practices for building cluster resiliency in Kubernetes. By implementing these strategies, you can ensure that your applications remain highly available, even in the face of failures or disruptions. Let’s dive into the world of cluster resiliency and learn how to build rock-solid, resilient clusters!
Read More
K8s Networking Mastery: Advanced Cluster Communication
July 13, 2023
Introduction Kubernetes has revolutionized container orchestration, enabling the efficient management of complex applications. As an advanced user, you’re likely already familiar with the basics of Kubernetes networking. In this blog post, we’ll dive deeper into advanced networking concepts, exploring techniques and best practices to optimize cluster communication, enhance security, and troubleshoot network-related issues. Get ready to level up your networking skills in Kubernetes! Network Models in Kubernetes In Kubernetes, network models play a crucial role in facilitating communication between pods.
Read More
Blue-Green Deployments in Kubernetes: Production & DR
July 12, 2023
Introduction In today’s fast-paced and highly competitive digital landscape, organizations strive to deliver seamless and uninterrupted services to their customers. To achieve this, a robust production strategy combined with a solid disaster recovery (DR) plan is crucial. In the realm of Kubernetes, one powerful technique for achieving these goals is the implementation of blue-green deployments. This blog post will explore the concept of blue-green deployments, their benefits, and how they can be effectively leveraged in Kubernetes environments to streamline production and disaster recovery strategies.
Read More
AWS Production-DR Failover: Advanced Strategies
July 11, 2023
Introduction Implementing failover between a production (Prod) account and a disaster recovery (DR) account is a critical aspect of ensuring high availability and business continuity in AWS. While DNS-based failover is a common approach, advanced users can explore additional strategies that provide enhanced control, automation, and scalability for failover scenarios. In this comprehensive guide, we will delve into advanced techniques that go beyond DNS, enabling advanced users to build robust failover architectures in AWS.
Read More
Python Context Managers Mastery: Resource Management
July 10, 2023
Introduction Python context managers provide a convenient and reliable way to manage resources and ensure proper setup and teardown actions. Whether dealing with file operations, database connections, or any resource that needs to be acquired and released, context managers offer a clean and concise approach. This comprehensive blog post will explore the concept of context managers in Python, starting from the fundamentals and gradually progressing to more advanced techniques. Understanding Context Managers The Context Management Protocol The Context Management Protocol defines the interface that objects must implement to be used as context managers.
Read More
Python Decorators Mastery: Advanced Usage Guide
July 9, 2023
Introduction Python decorators are a powerful feature that allows you to modify the behavior of functions or classes dynamically. Decorators provide a way to add functionality to existing code without modifying the original source. This blog post will delve into the concept of decorators in Python, starting from the basics and gradually progressing to more advanced techniques. Understanding Decorators Function Decorators Function decorators are a way to modify the behavior of a function by wrapping it inside another function.
Read More
Python's Yield Mastery: Advanced Usage Guide
July 8, 2023
Introduction Python’s yield statement is a powerful feature that allows you to create generator functions. Generators provide an efficient way to generate a sequence of values without storing them all in memory at once. This blog post will delve into the concept of yield in Python, starting from the basics and gradually progressing to more advanced techniques. Understanding the Basics Yield vs. Return In Python, the yield statement is used within a function to create a generator.
Read More
Python: Unleashing the Power of Simplicity and Versatility
July 7, 2023
Getting Started with Python Python is a versatile and popular programming language known for its simplicity and readability. It is widely used in various fields, including web development, data analysis, artificial intelligence, and automation. If you’re new to Python, this guide will help you get started with the basics and provide some code examples to illustrate key concepts. Installing Python To begin, you need to install Python on your computer. Python is available for multiple platforms, including Windows, macOS, and Linux.
Read More
Python's Advanced Features: Empowering Programmers
July 6, 2023
Introduction: In the vast realm of programming, Python stands tall as a language that caters to developers of all levels. Beyond its beginner-friendly syntax, Python harbors a treasure trove of advanced features that can elevate your coding prowess to new heights. In this blog post, we embark on an exhilarating journey to explore the depths of Python’s advanced features, unleashing their full potential. Brace yourself as we delve into the world of decorators, context managers, metaclasses, multiple inheritance, generators, coroutines, dynamic typing, duck typing, and functional programming tools.
Read More
Python's Yield: Unleashing Generator Magic
July 5, 2023
Introduction Python, being a versatile language, offers numerous tools and features to streamline our coding experience. One such powerful feature is the yield keyword. In this blog post, we will embark on an exciting journey to explore the hidden potential of Python’s yield statement and dive into the realm of generators. Buckle up and get ready to witness the magic unfold! Section 1: Understanding the Basics of Yield At its core, yield is used in Python to create generator functions.
Read More
GitOps Rising: Transforming DevOps for Streamlined Delivery
July 4, 2023
Introduction In today’s fast-paced digital landscape, where businesses strive to deliver high-quality software products with agility and efficiency, DevOps practices have become indispensable. DevOps aims to bridge the gap between software development and operations, enabling seamless collaboration, faster deployments, and improved overall software delivery. One of the most prominent trends revolutionizing the DevOps world is GitOps. In this blog post, we will explore the concept of GitOps, its benefits, and why it has gained significant traction in the industry.
Read More
Enhancing Security: How DevOps Mitigates Cyber Threats
July 3, 2023
Introduction In today’s digital landscape, where cyber threats are prevalent and evolving, organizations must adopt robust security measures to safeguard their sensitive data and systems. In this pursuit, DevOps practices have emerged as a powerful ally, enabling organizations to build secure and resilient software solutions. By integrating security into every stage of the software development lifecycle, DevOps plays a crucial role in preventing, detecting, and responding to cyber attacks. In this blog post, we will explore how DevOps helps organizations fend off hackers and enhance their overall security posture.
Read More
Site Reliability Engineering (SRE) in Modern Organizations
July 2, 2023
Introduction In today’s fast-paced and technology-driven world, organizations heavily rely on digital services to deliver their products and serve their customers. With the increasing complexity of modern infrastructure and the need for high availability and reliability, Site Reliability Engineering (SRE) has emerged as a critical discipline. SRE combines software engineering principles with operations expertise to ensure the smooth functioning of complex systems. In this blog post, we will explore the importance of SRE in organizations and how it contributes to their success.
Read More
DevOps & DevSecOps: Bridging Dev-Security Gap
July 1, 2023
Introduction In today’s fast-paced digital landscape, where software development cycles are becoming increasingly rapid and security threats are ever-present, organizations are seeking effective ways to align development and security practices. Two prominent approaches that have gained significant attention are DevOps and DevSecOps . While these terms may sound similar, there are crucial distinctions between them. In this blog post, we will explore the differences between DevOps and DevSecOps , their goals, and how they contribute to efficient and secure software delivery.
Read More
Unleashing the Power: Lambda - A Killer Feature in AWS
June 30, 2023
In the world of cloud computing, Amazon Web Services (AWS) has long been a dominant player, providing a comprehensive suite of services to meet the diverse needs of businesses. Among its vast array of offerings, one particular service stands out as a true game-changer: AWS Lambda. Lambda is a serverless computing platform that has revolutionized the way developers build and deploy applications. In this blog post, we’ll explore why Lambda is rightly hailed as a killer feature in AWS.
Read More
Python vs Java Performance: Programming Powerhouses
June 29, 2023
In the vast landscape of programming languages, Python and Java have emerged as titans, offering robust solutions for a wide range of applications. When it comes to performance, developers often find themselves pondering which language reigns supreme. In this blog post, we will delve into the world of Python and Java, exploring their performance characteristics, strengths, and weaknesses, and ultimately helping you make an informed choice for your next project.
Read More
Teach me the Basics of Data Science in Python
June 28, 2023
An overview of Data Science in Python This is an overview of the basics of data science in Python. Data science involves extracting knowledge and insights from data using various techniques such as data cleaning, visualization, statistical analysis, and machine learning . Python is a popular programming language in the data science community due to its rich ecosystem of libraries and tools. Let’s go through the key components of data science in Python.
Read More
How to Share a VPC from one AWS Account to Another
June 27, 2023
To share a Virtual Private Cloud (VPC) from one AWS account to another, you can use the AWS Resource Access Manager (RAM) service. RAM allows you to securely share your AWS resources with other AWS accounts while maintaining control over the resource permissions. Here’s a step-by-step guide on how to share a VPC from one AWS account to another: 1. Set up the necessary permissions In the account that owns the VPC (the sharing account), ensure that you have the required permissions to share the VPC.
Read More
[Solved] Set CloudWatch Logs role ARN in account settings
June 26, 2023
The error message you mentioned, “CloudWatch Logs role ARN must be set in account settings to enable logging,” typically occurs when you’re trying to enable logging for an AWS service that requires a CloudWatch Logs role, but the necessary role hasn’t been set up or configured correctly in your account settings. To resolve this issue, you can follow these steps: Sign in to the AWS Management Console. Open the AWS CloudTrail console at https://console.
Read More
How to Create CloudFormation with Multiple Files
June 25, 2023
To create a CloudFormation (CFN) stack with multiple files, you can follow these general steps: Organize your resources: Divide your resources into logical groups or services. For example, you might have separate files for networking, storage, compute, and so on. Create YAML or JSON templates: Create individual YAML or JSON templates for each group or service. Each template will define the resources specific to that group. For example, networking.yaml, storage.yaml, and compute.
Read More
Teach me Hashicorp Vault
June 24, 2023
Introduction to Hashicorp Vault HashiCorp Vault is a popular open-source tool designed for securely storing and managing secrets, such as API keys, passwords, certificates, and other sensitive information. It provides a centralized place to store secrets, access control mechanisms, and auditing capabilities. Vault ensures that only authorized applications and users can access the secrets they need, thus improving security in an organization. Concepts Here’s a high-level overview of the key concepts and components of HashiCorp Vault:
Read More
How to Generate Terraform using a Bash Shell script
June 23, 2023
To generate Terraform code using a Bash shell script, you can utilize Python within the script. Here’s an example of how you can achieve this: 1. Create a new Bash script file Open a text editor and create a new file, for example, generate_terraform.sh. 2. Add the shebang line Start the script with the shebang line to specify that it should be interpreted using Bash: #!/bin/bash 3. Install Required Libraries Since you’ll be using Python within the script, ensure that Python and pip are installed on your system.
Read More
How to Generate Terraform using Python
June 22, 2023
To generate Terraform code using Python, you can utilize the power of the language and various libraries to dynamically create and manipulate the Terraform configuration files. Here’s a step-by-step guide on how to get started: 1. Install Required Libraries Make sure you have Python installed on your system. Additionally, install the hclwriter library, which simplifies the process of generating HCL (HashiCorp Configuration Language) code, the language used by Terraform. You can install it using pip:
Read More
Make EKS cluster private with NodeGroup access
June 21, 2023
The Theory To make an Amazon Elastic Kubernetes Service (EKS) cluster private and allow nodes to join through a node group, you need to follow a few steps. By default, EKS creates a public cluster, but you can configure it to make it private for enhanced security. Here’s an overview of the process: Create a VPC: Start by creating a Virtual Private Cloud (VPC) in your AWS account if you haven’t already.
Read More
Which is the best language to use in DevOps
June 20, 2023
In DevOps, there isn’t a single “best” language that universally applies to all situations. The choice of programming language depends on various factors, including the specific requirements of your project, existing infrastructure, team’s expertise, and the ecosystem surrounding the tools and technologies you plan to use. However, here are some commonly used languages in different areas of DevOps: Automation and Configuration Management Ansible: Ansible uses a declarative YAML syntax for defining configurations and automation tasks.
Read More
How is Ansible different from Chef or Puppet
June 19, 2023
Ansible, Chef, and Puppet are all popular configuration management and automation tools, but they differ in their approach and architecture. Here’s a comparison of Ansible with Chef and Puppet: Architecture Ansible: Ansible follows a simple agentless architecture. It uses SSH or WinRM to connect to managed nodes and executes tasks remotely without the need for installing any agent software on the nodes. Chef: Chef uses a client-server architecture. It requires a Chef client agent to be installed on each managed node, which communicates with a central Chef server.
Read More
Teach me the basics of Ansible
June 18, 2023
Ansible is an open-source automation tool that allows you to manage and configure computer systems. It uses a declarative language called YAML (Yet Another Markup Language) for defining configurations and tasks. Ansible follows a client-server architecture, where the controlling machine (the Ansible server) manages and communicates with the target machines (managed nodes) over SSH. The basics of Ansible Inventory An inventory file in Ansible contains a list of target hosts (managed nodes) on which Ansible performs operations.
Read More
How do you create an EKS cluster using CloudFormation
June 17, 2023
The steps to achieve this To create an Amazon Elastic Kubernetes Service (EKS) cluster using CloudFormation, you can follow these steps: Create a CloudFormation template: Start by creating a CloudFormation template in YAML or JSON format. This template will define the resources required for your EKS cluster, including the cluster itself, worker nodes, and other necessary components. Define the EKS cluster resource: Within your CloudFormation template, define an AWS::EKS::Cluster resource. Specify the desired configuration for your EKS cluster, such as the version, name, and role-based access control (RBAC) configuration.
Read More
How to connect an API Gateway to Inline Lambda in Terraform
June 16, 2023
To connect an API Gateway to an inline Lambda function using Terraform, you can follow these steps: Define your API Gateway and Lambda function resources in your Terraform configuration. Here’s an example: resource "aws_api_gateway_rest_api" "my_api_gateway" { name = "MyApiGateway" } resource "aws_api_gateway_resource" "my_api_gateway_resource" { rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id parent_id = aws_api_gateway_rest_api.my_api_gateway.root_resource_id path_part = "myresource" } resource "aws_api_gateway_method" "my_api_gateway_method" { rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id resource_id = aws_api_gateway_resource.my_api_gateway_resource.id http_method = "GET" authorization = "NONE" integration { type = "AWS_PROXY" http_method = "POST" uri = "arn:aws:apigateway:${var.
Read More
API Gateway to Inline Lambda in CloudFormation
June 15, 2023
To connect an API Gateway to an inline Lambda function using CloudFormation, you can follow these steps: Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example: Resources: MyApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: MyApiGateway MyApiGatewayResource: Type: AWS::ApiGateway::Resource Properties: RestApiId: !Ref MyApiGateway ParentId: !GetAtt MyApiGateway.RootResourceId PathPart: myresource MyApiGatewayMethod: Type: AWS::ApiGateway::Method Properties: RestApiId: !Ref MyApiGateway ResourceId: !Ref MyApiGatewayResource HttpMethod: GET AuthorizationType: NONE Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !
Read More
How to connect an API Gateway to Lambda in CloudFormation
June 14, 2023
To connect an API Gateway to a Lambda function using CloudFormation, you can follow these steps: Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example: Resources: MyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: MyLambdaFunction Runtime: python3.8 Handler: index.handler Code: S3Bucket: my-lambda-code-bucket S3Key: lambda-code.zip MyApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: MyApiGateway Create a resource of type AWS::ApiGateway::Resource to define the resource path for your API Gateway: MyApiGatewayResource: Type: AWS::ApiGateway::Resource Properties: RestApiId: !
Read More
Create DynamoDB Table & Add Items using Python 3 from Lambda
June 13, 2023
To create a DynamoDB table and add items to it using Python 3 from AWS Lambda, you can use the AWS SDK for Python, also known as Boto3. Here’s a step-by-step guide: Set up your AWS environment: Install Boto3 by running pip install boto3 in your local development environment. Set up your AWS credentials and configure your AWS CLI or environment variables. You can find detailed instructions in the AWS documentation.
Read More
How to create a Site-to-Site VPN in Boto3 Python
June 12, 2023
To create a site-to-site VPN using the Boto3 library in Python, you can utilize the boto3.client('ec2') client to interact with the AWS EC2 service. Here’s an example code snippet to create a site-to-site VPN: import boto3 ec2_client = boto3.client('ec2') # Create VPN Gateway vpn_gateway_response = ec2_client.create_vpn_gateway(Type='ipsec.1', TagSpecifications=[{ 'ResourceType': 'vpn-gateway', 'Tags': [{'Key': 'Name', 'Value': 'SiteToSiteVPN'}] }]) vpn_gateway_id = vpn_gateway_response['VpnGateway']['VpnGatewayId'] # Create VPN Connection vpn_connection_response = ec2_client.create_vpn_connection( Type='ipsec.1', CustomerGatewayId='<CUSTOMER_GATEWAY_ID>', VpnGatewayId=vpn_gateway_id, Options={ 'StaticRoutesOnly': True }, TagSpecifications=[{ 'ResourceType': 'vpn-connection', 'Tags': [{'Key': 'Name', 'Value': 'SiteToSiteVPNConnection'}] }] ) vpn_connection_id = vpn_connection_response['VpnConnection']['VpnConnectionId'] # Create VPN Connection Route ec2_client.
Read More
How to create a Site-to-Site VPN in Terraform
June 11, 2023
To create a site-to-site VPN using Terraform, you can use the aws_vpn_gateway and aws_vpn_connection resources from the AWS provider. Here’s an example Terraform configuration to create a site-to-site VPN: resource "aws_vpn_gateway" "vpn_gateway" { vpc_id = "<VPC_ID>" tags = { Name = "SiteToSiteVPN" } } resource "aws_vpn_connection" "vpn_connection" { customer_gateway_id = "<CUSTOMER_GATEWAY_ID>" vpn_gateway_id = aws_vpn_gateway.vpn_gateway.id type = "ipsec.1" static_routes_only = true tags = { Name = "SiteToSiteVPNConnection" } } resource "aws_vpn_connection_route" "vpn_connection_route" { destination_cidr_block = "<DESTINATION_CIDR_BLOCK>" vpn_connection_id = aws_vpn_connection.
Read More
How to create a Site-to-Site VPN in CloudFormation
June 10, 2023
To create a site-to-site VPN (Virtual Private Network) using AWS CloudFormation, you can use the AWS::EC2::VPNGateway and AWS::EC2::VPNConnection resources. Here’s an example CloudFormation template to create a site-to-site VPN: AWSTemplateFormatVersion: '2010-09-09' Resources: VpnGateway: Type: AWS::EC2::VPNGateway Properties: Type: ipsec.1 Tags: - Key: Name Value: SiteToSiteVPN VpnConnection: Type: AWS::EC2::VPNConnection Properties: Type: ipsec.1 CustomerGatewayId: <CUSTOMER_GATEWAY_ID> VpnGatewayId: !Ref VpnGateway StaticRoutesOnly: true Tags: - Key: Name Value: SiteToSiteVPNConnection VpnConnectionRoute: Type: AWS::EC2::VPNConnectionRoute Properties: DestinationCidrBlock: <DESTINATION_CIDR_BLOCK> VpnConnectionId: !
Read More
How to AWS sts assume role in one command - without jq
June 9, 2023
The issue - what it takes to assume a role To assume an AWS role in the CLI, you will have to do something like this: aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test --region eu-central-1 This will give you the following output: { "Credentials": { "AccessKeyId": "someAccessKeyId", "SecretAccessKey": "someSecretAccessKey", "SessionToken": "someSessionToken", "Expiration": "20203-01-02T06:52:13+00:00" }, "AssumedRoleUser": { "AssumedRoleId": "idOfTheAssummedRole", "Arn": "theARNOfTheRoleIWantToAssume" } } But then you will have to manually copy and paste the values of AccessKeyId, SecretAccessKey and SessionToken in a bunch of exports like this:
Read More
How to create a Lambda in CloudFormation
June 7, 2023
You can create a Lambda in CloudFormation as follows: Option 1 - Inline code Resources: MyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: MyLambdaFunction Runtime: python3.8 Handler: index.lambda_handler Code: ZipFile: | import json def lambda_handler(event, context): # Your Lambda function code here return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } Role: !GetAtt MyLambdaExecutionRole.Arn In this example, instead of specifying the S3Bucket and S3Key properties under the Code section, you use the ZipFile property to provide the actual code as a multiline string.
Read More
How to create a Lambda in Terraform
June 7, 2023
To create an AWS Lambda function using Terraform, you need to define the necessary resources in a Terraform configuration file. Here’s an example of how you can create a Lambda function using Terraform: Option 1 - Seperate Lambda Source Create a new directory for your Terraform configuration and navigate to it in your terminal. Create a new file with a .tf extension, such as lambda.tf, and open it in a text editor.
Read More
How to create a Bastion server in Terraform
June 6, 2023
To create a Bastion server using Terraform, you need to define the necessary resources in a Terraform configuration file. Here’s an example of how you can create a Bastion server using Terraform: # Define the security group resource "aws_security_group" "bastion_sg" { name = "bastion-security-group" description = "Bastion Security Group" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } vpc_id = "your-vpc-id" } # Define the Bastion instance resource "aws_instance" "bastion_instance" { ami = "your-ami-id" instance_type = "t2.
Read More
How to create a Bastion server in CloudFormation
June 5, 2023
To create a Bastion server using AWS CloudFormation, you need to define the necessary resources in a CloudFormation template. Here’s an example of how you can create a Bastion server using CloudFormation: AWSTemplateFormatVersion: "2010-09-09" Resources: BastionSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Bastion Security Group SecurityGroupIngress: - IpProtocol: tcp FromPort: 22 ToPort: 22 CidrIp: 0.0.0.0/0 VpcId: "your-vpc-id" BastionInstance: Type: AWS::EC2::Instance Properties: ImageId: "your-ami-id" InstanceType: "t2.micro" # Update with the desired instance type SecurityGroupIds: - !
Read More
How to you create a Cross Account Role in Terraform
June 4, 2023
To create a cross-account role in Terraform, you need to perform the following steps: 1. Define the IAM role Define the IAM role in the Terraform configuration resource "aws_iam_role" "cross_account_role" { name = "CrossAccountRole" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::<ACCOUNT_ID>:root" }, "Action": "sts:AssumeRole" } ] } EOF } In the assume_role_policy section, replace <ACCOUNT_ID> with the AWS account ID of the target account that will assume this role.
Read More
How to you create a Cross Account Role in CloudFormation
June 3, 2023
To create a cross-account role in CloudFormation, you can follow these steps: 1. Create a CloudFormation template Create a new CloudFormation template in YAML or JSON format. This template will define the resources, including the cross-account role, that you want to create. 2. Define the cross-account role Within your CloudFormation template, define the cross-account role using the AWS::IAM::Role resource type. Specify the necessary properties such as RoleName, AssumeRolePolicyDocument, and ManagedPolicyArns.
Read More
How to create Public and Private Subnets in CloudFormation
June 2, 2023
To create public and private subnets in AWS CloudFormation, you can use the AWS CloudFormation Template Language (CFT) to define your network configuration. Here’s an example CloudFormation template that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS: Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 Tags: - Key: Name Value: my-vpc PublicSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.0.0/24 AvailabilityZone: us-west-2a Tags: - Key: Name Value: public-subnet PrivateSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !
Read More
How to create Public and Private Subnets in Terraform
June 1, 2023
To create public and private subnets in Terraform, you can use the AWS provider to define your network configuration. Here’s an example configuration that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS: # Define your AWS provider configuration provider "aws" { region = "us-west-2" # Update with your desired region } # Create the VPC resource "aws_vpc" "my_vpc" { cidr_block = "10.0.0.0/16" # Update with your desired VPC CIDR block tags = { Name = "my-vpc" } } # Create the public subnet resource "aws_subnet" "public_subnet" { vpc_id = aws_vpc.
Read More
Create Internet Gateway & Assign to EC2 in CloudFormation
May 31, 2023
To create an Internet Gateway and associate it with an EC2 instance using AWS CloudFormation, you can follow these steps: Step 1: Create a CloudFormation template Create a new YAML or JSON file with a .yaml or .json extension (e.g., template.yaml), and add the following contents: AWSTemplateFormatVersion: "2010-09-09" Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 # Replace with your desired VPC CIDR block MyInternetGateway: Type: AWS::EC2::InternetGateway MyVPCGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !
Read More
Create Internet Gateway & Assign to EC2 in Terraform
May 30, 2023
To create an Internet gateway and assign it to an EC2 instance using Terraform, you can follow these steps: Step 1: Set up your Terraform environment Install Terraform: Download and install Terraform from the official website (https://www.terraform.io/downloads.html ) based on your operating system. Configure AWS credentials: Set up your AWS access key and secret access key as environment variables or use an AWS profile configured on your system. Step 2: Create a Terraform configuration file Create a new file with a .
Read More
How to configure Terraform to use Local Providers from Nexus
May 29, 2023
If your organization has blocked registry.terraform.io and has instead downloaded the provider binaries to Nexus, then you can do the following to still make your Terraform execute correctly. Step 1 - Download the Required Providers In our example, we need the following providers: AWS Archive These commands below are running directly from the pipeline that executes the Terraform: # Download the providers from the Nexus repository - curl -u ${Nexus_REPO_USER}:${Nexus_REPO_PASS} -o terraform-provider-aws4.
Read More
[Solved] Fargate Can't Read Secrets from Secret Manager
May 28, 2023
If you’re running a Fargate task and it’s not able to read secrets from AWS Secret Manager, there are a few things you can check: Verify that the Fargate task has the correct IAM permissions to access the secret. You need to grant the task the secretsmanager:GetSecretValue permission for the specific secret that it needs to access. You can do this by adding the necessary permission to the task execution role, or by creating a separate IAM role and attaching it to the task.
Read More
Golang vs Python: The Ultimate Battle in DevOps
May 27, 2023
In the world of DevOps, two programming languages are often pitted against each other: Golang and Python. Both languages have their own strengths and weaknesses, and choosing the right one for your DevOps needs can be a tough decision. In this blog post, we will take a closer look at Golang and Python, and compare their capabilities in the DevOps landscape. Golang Golang is a language that has gained immense popularity in recent years, especially in the field of DevOps.
Read More
Why DevOps and Python are Amazing Together
May 26, 2023
In today’s software development world, DevOps and Python are two of the most essential elements for building high-quality software. DevOps has transformed the way software is developed, tested, and deployed, while Python has become a popular programming language for automation and scripting. The combination of DevOps and Python is particularly powerful because it provides developers with the necessary tools to automate, test, and deploy software efficiently. Here are some of the reasons why DevOps and Python are such a great match:
Read More
Python & DevOps: Transforming Software Development
May 25, 2023
Introduction: In recent years, the software industry has witnessed a remarkable shift towards DevOps and Python. DevOps has become a vital part of software development, and Python is now one of the most popular programming languages used by developers. In this blog post, we’ll explore why DevOps and Python are so amazing together, and how they can help revolutionize software development. DevOps: A Game Changer in Software Development DevOps is a software development methodology that aims to bridge the gap between development and operations teams.
Read More
DevOps: The Ultimate Secret Weapon for High-Tech Success
May 24, 2023
DevOps has been a buzzword in the tech industry for some time now. While some companies have embraced the DevOps methodology, others are still lagging behind. If you’re wondering what all the hype is about and why DevOps is so amazing, then read on! Here are ten reasons why DevOps is the ultimate secret weapon for high-tech success. 1. Improved Collaboration and Communication Improved collaboration and communication are critical benefits of DevOps that can have a significant impact on the success of software development projects.
Read More
How to Deploy a Java Application in AWS ECS using Terraform
May 23, 2023
In order to deploy a Java application into AWS ECS (Elastic Container Service) using Terraform, we need to consider a few different things. Step 1 - Java Application Create a file called HelloWorld.java and add the following code to it: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } We now need to build our class as follows: javac HelloWorld.java Once this is done, we can package our application into a jar file:
Read More
How to set the Hostname on a Linux server with Terraform
May 22, 2023
If you need to set the hostname on a linux server, and you are using Terraform, then you can do the following: Include the provisioner block and set it to remote-exec: provisioner "remote-exec" { inline = ["sudo hostnamectl set-hostname friendly.example.com"] }
Read More
What are the different types of AWS API Gateway Protocols?
May 21, 2023
Amazon API Gateway supports various protocols for exposing APIs, including: 1. RESTful API This is the most common and widely used protocol for web APIs. Amazon API Gateway allows you to create and manage RESTful APIs, where you define API resources, methods (such as GET, POST, PUT, DELETE, etc.), and HTTP request and response mappings using API Gateway’s REST API model. Primary use-cases include Building traditional web APIs with standard HTTP methods (GET, POST, PUT, DELETE, etc.
Read More
IaC: A Guide to Modern Software Development
May 20, 2023
In the world of software development, efficiency, scalability, and repeatability are paramount. Enter Infrastructure as Code (IaC), a revolutionary approach to managing infrastructure in the cloud era. In this definitive guide, we will dive deep into the concept of IaC, explore its benefits, best practices, and how it is reshaping the way modern software is built and deployed. Join us on this journey as we unlock the power of IaC and uncover its secrets to successful software development.
Read More
DevOps and Microservices: How They Complement Each Other
May 19, 2023
In today’s fast-paced world of software development, DevOps and microservices have emerged as two powerful methodologies that enable organizations to build and deploy applications with speed, agility, and reliability. While DevOps and microservices are distinct concepts, they often go hand in hand, complementing each other to create a seamless and efficient software development and deployment process. In this blog post, we will explore how DevOps and microservices fit together and how organizations can leverage them to accelerate their software delivery pipelines and achieve business success.
Read More
IaC Unlock: Maximize Potential with Ansible
May 18, 2023
In today’s fast-paced world of software development and IT operations, the need for efficient and scalable infrastructure management has become more critical than ever. Enter Infrastructure as Code (IaC), a game-changing approach that allows organizations to automate their infrastructure provisioning and management, making it more agile, scalable, and reliable. And when it comes to IaC, Ansible stands out as a top choice for many IT teams due to its simplicity, versatility, and robustness.
Read More
GitOps: Managing Infrastructure as Code with Git
May 17, 2023
Introduction In today’s fast-paced world of software development and operations, managing infrastructure efficiently and securely is crucial for organizations to deliver reliable and scalable applications. Traditional methods of managing infrastructure can be time-consuming, error-prone, and lack visibility, making it challenging to keep up with the demands of modern software development practices. However, with the emergence of GitOps, organizations now have a powerful and efficient way to manage infrastructure as code, leveraging the familiar and widely adopted Git version control system.
Read More
DevOps Synergy: Boosting Cybersecurity
May 16, 2023
As organizations increasingly rely on technology to power their operations, the need for robust cybersecurity measures becomes more critical than ever. Cyber threats are constantly evolving, and traditional security approaches are no longer sufficient to protect against sophisticated attacks. This is where DevOps, a collaborative approach to software development and operations, can play a significant role in enhancing cybersecurity defenses. In this blog post, we will explore the powerful synergy between DevOps and cybersecurity, and how organizations can leverage this approach to strengthen their security posture.
Read More
The Role of DevOps in Blockchain
May 15, 2023
Blockchain technology is gaining traction across various industries for its ability to provide transparency, security, and immutability. However, implementing blockchain solutions requires a robust and efficient software development process, which is where DevOps comes in. In this blog post, we will explore the role of DevOps in blockchain development and how it can help organizations deploy blockchain solutions seamlessly. What is DevOps? DevOps is a software development methodology that emphasizes collaboration, automation, and continuous delivery to ensure faster and more reliable software delivery.
Read More
The Importance of Testing in DevOps: Strategies and Tools
May 14, 2023
Introduction In today’s fast-paced digital world, software development has become an essential part of business operations. With the adoption of DevOps practices, organizations can build and deploy software applications more efficiently and effectively. However, with faster release cycles, it becomes increasingly important to ensure that software is thoroughly tested before release. In this blog post, we will explore the importance of testing in DevOps, strategies for successful testing, and tools that can help streamline the testing process.
Read More
DevOps Impact on Customer Experience
May 13, 2023
DevOps has revolutionized the way organizations develop, deploy, and manage software applications. It has brought about a cultural shift that emphasizes collaboration, automation, and continuous improvement. While DevOps has many benefits for software development teams, it also has a significant impact on customer experience and business success. In this blog post, we will explore how DevOps can improve customer experience and lead to business success. Key Points Faster Time-to-Market One of the key benefits of DevOps is that it enables teams to release software faster and more frequently.
Read More
Building a DevOps Culture from the Ground Up
May 12, 2023
DevOps has become a crucial aspect of software development, enabling teams to deliver software more efficiently and with higher quality. However, implementing DevOps is not just a matter of adopting tools and processes; it requires a cultural shift in the organization. In this blog post, we will explore the steps organizations can take to build a DevOps culture from the ground up. 1. Define the vision and goals The first step in building a DevOps culture is to establish a clear vision and goals.
Read More
Scaling DevOps for Enterprise Organizations
May 11, 2023
Introduction DevOps has become a popular approach for software development in recent years, enabling teams to collaborate more effectively, increase efficiency, and deliver high-quality software faster. However, scaling DevOps for enterprise organizations can be challenging due to the size and complexity of their operations. In this blog post, we will explore the key considerations for scaling DevOps in an enterprise context and provide practical tips for success. 1. Establish a Clear Vision and Strategy Before scaling DevOps, it’s crucial to establish a clear vision and strategy that aligns with the organization’s business objectives.
Read More
The Benefits of Infrastructure as Code in DevOps
May 10, 2023
Introduction The increasing complexity of software systems requires a flexible, scalable, and reliable infrastructure. This is where infrastructure as code (IaC) comes in, providing a way to automate the management of infrastructure through code. In DevOps, IaC is a critical component that helps teams achieve continuous delivery and deployment, reduce errors, improve collaboration and communication, and ensure consistency and repeatability. In this blog post, we will explore the benefits of infrastructure as code in DevOps.
Read More
DevOps for Legacy Systems: Challenges and Solutions
May 9, 2023
As organizations continue to evolve and embrace digital transformation, they often encounter legacy systems that are critical to their business operations. These systems may be outdated and require modernization, but they still need to be maintained and supported in the meantime. This is where DevOps for legacy systems comes in, offering new opportunities for agility, innovation, and efficiency. In this blog post, we will explore the challenges and solutions for implementing DevOps practices for legacy systems.
Read More
DevOps Risk Management: Security & Compliance
May 8, 2023
DevOps has transformed software development, enabling teams to build, test, and deploy applications faster and more efficiently. However, the speed and agility of DevOps also bring new risks, particularly in the areas of security and compliance. To mitigate these risks, DevOps teams need to adopt strategies that incorporate security and compliance into the development process from the start. In this blog post, we will discuss some of the key strategies for managing risk in DevOps.
Read More
Why DevOps is Critical for Digital Transformation
May 7, 2023
Digital transformation is the process of adopting and implementing digital technologies to improve business operations, increase efficiency, and enhance customer experience. The adoption of digital technologies has become essential for businesses to remain competitive in today’s fast-paced environment. However, implementing digital transformation is not just about technology, it requires a significant cultural shift in the organization. One of the key elements of digital transformation is the implementation of DevOps. In this blog post, we will explore why DevOps is critical for digital transformation.
Read More
The Role of Microservices in DevOps
May 6, 2023
In recent years, microservices have become a popular architectural style for building software applications. Microservices are small, independent services that work together to form a larger application. Each microservice is responsible for a specific task, and they communicate with each other through well-defined APIs. This approach offers many benefits, including scalability, resilience, and flexibility. In this blog post, we’ll explore the role of microservices in DevOps and how they contribute to a successful software development process.
Read More
Achieving Continuous Delivery with DevOps and Automation
May 5, 2023
Continuous delivery is a DevOps practice that aims to automate the entire software delivery process, from code commit to production deployment. With continuous delivery, teams can deliver software faster and with greater reliability. By automating many of the manual steps involved in software delivery, teams can reduce the risk of errors and increase the speed of deployment. To achieve continuous delivery, DevOps teams must prioritize automation. Here are some best practices for achieving continuous delivery with DevOps and automation:
Read More
The Importance of Collaboration in DevOps Culture
May 4, 2023
Collaboration is a key aspect of DevOps culture, and it plays a crucial role in driving success and delivering value to customers. In today’s fast-paced business environment, DevOps teams need to work together seamlessly to ensure that applications are developed and deployed quickly and efficiently, while maintaining high quality and security standards. In this blog post, we will discuss the importance of collaboration in DevOps culture and how it can lead to better outcomes for organizations.
Read More
Cloud-Native: Key to DevOps Success
May 3, 2023
In recent years, cloud-native architecture has become a buzzword in the world of DevOps. But what exactly does it mean, and why is it so important for DevOps success? In this blog post, we’ll explore the concept of cloud-native architecture and why it’s essential for DevOps teams to embrace it. What is Cloud-Native Architecture? Cloud-native architecture is an approach to building and running applications that takes advantage of the scalability and flexibility of cloud computing.
Read More
10 Best Practices for Continuous Integration in DevOps
May 2, 2023
Continuous Integration (CI) is an essential part of modern software development and is integral to the DevOps methodology. CI ensures that every code change made by developers is integrated and tested with the existing codebase, allowing teams to catch and fix issues early in the development cycle. In this blog post, we’ll explore the best practices for implementing Continuous Integration in DevOps. 1. Automate the build process Automating the build process in CI involves using tools and scripts to build, package, and deploy software artifacts.
Read More
DevOps vs. Agile: What's the Difference and Why it Matters
May 1, 2023
Introduction In the world of software development, there are two methodologies that are often mentioned: Agile and DevOps. While they share some similarities, they are distinct and have different goals. In this blog post, we’ll explore the differences between Agile and DevOps, why they matter, and how they can work together. What is Agile? Agile is a software development methodology that emphasizes collaboration, flexibility, and responsiveness. It was first introduced in 2001 with the publication of the Agile Manifesto, which outlined a set of guiding principles for software development.
Read More
The Future of DevOps: Emerging Trends and Technologies
April 30, 2023
In recent years, DevOps has emerged as a key practice for modern software development, helping organizations to achieve faster delivery of high-quality applications. However, as the technology landscape continues to evolve, DevOps itself is undergoing significant changes to keep pace with emerging trends and technologies. In this blog post, we will explore the future of DevOps and the emerging trends and technologies that are shaping its evolution. Serverless computing Serverless computing is an approach to cloud computing that allows developers to write and run code without having to manage the underlying infrastructure.
Read More
Building Resilient Microservices with Istio and Envoy
April 29, 2023
As microservices architecture continues to grow in popularity, it’s becoming increasingly important to ensure that these distributed systems are reliable and resilient. Istio and Envoy are two tools that have emerged to help with this challenge. In this blog post, we’ll explore how Istio and Envoy can be used to build resilient microservices. Introduction to Istio and Envoy Istio is an open-source service mesh that provides a unified way to connect, manage, and secure microservices.
Read More
5 Key Metrics to Measure DevOps Success
April 27, 2023
As DevOps continues to gain popularity and adoption, it is important for organizations to measure the success of their DevOps initiatives. While DevOps is about culture and collaboration, it is also about delivering value to customers quickly and reliably. In this blog post, we will discuss five key metrics that organizations can use to measure the success of their DevOps initiatives. 1. Lead Time for Changes Lead time for changes is the amount of time it takes for a change to be implemented, from the moment it is requested to the moment it is deployed.
Read More
The Importance of Infrastructure as Code in DevOps
April 26, 2023
Infrastructure as Code (IaC) is a methodology that involves managing and provisioning infrastructure through code rather than manually configuring hardware and software components. This approach is essential in DevOps because it enables teams to manage infrastructure at scale, improve collaboration, and reduce errors. In this blog post, we will explore the importance of IaC in DevOps and why it is critical for modern software development. 1. Consistency and Reproducibility Manual infrastructure configuration is prone to errors and can be challenging to reproduce consistently.
Read More
How to Build a Successful DevOps Toolchain
April 24, 2023
DevOps toolchains are essential for streamlining software delivery and ensuring that teams can work efficiently and collaboratively. However, building a successful DevOps toolchain requires careful planning, coordination, and evaluation. In this blog post, we will explore some strategies for building a successful DevOps toolchain that can help teams deliver software faster and more reliably. 1. Define the requirements The first step in building a successful DevOps toolchain is defining the requirements.
Read More
Scaling DevOps: Strategies for Managing Large Teams
April 24, 2023
DevOps has revolutionized software development and delivery, enabling teams to work collaboratively, automate processes, and deliver software faster and more reliably. However, as organizations grow and teams become larger, managing DevOps at scale becomes more challenging. In this blog post, we will explore some strategies for managing large DevOps teams and ensuring successful software delivery. 1. Embrace modular architecture Modular architecture is a critical aspect of scaling DevOps. By breaking down applications into smaller, more manageable components, teams can work independently, reducing dependencies and improving agility.
Read More
Why DevOps Culture is Critical for Business Success
April 23, 2023
The DevOps movement has been gaining momentum in recent years as organizations realize the benefits of breaking down silos between development and operations teams. DevOps is not just a set of tools and practices; it’s a culture that emphasizes collaboration, communication, and continuous improvement. In this blog post, we will explore why DevOps culture is critical for business success. 1. Speed and agility In today’s fast-paced business environment, organizations need to deliver software quickly and adapt to changing customer demands.
Read More
The Ultimate Guide to Kubernetes Deployment Strategies
April 22, 2023
Kubernetes has become a popular choice for container orchestration, providing developers with a powerful platform for deploying, scaling, and managing containerized applications. However, with great power comes great responsibility, and choosing the right deployment strategy is essential for ensuring application availability, scalability, and performance. In this post, we will cover the ultimate guide to Kubernetes deployment strategies, including their benefits, drawbacks, and best practices. 1. Rolling updates Rolling updates are the most common deployment strategy in Kubernetes, allowing you to update a running application without downtime.
Read More
10 Best Practices for Container Security in DevOps
April 21, 2023
Containers have become a critical component of modern software development practices. They provide a lightweight, portable, and scalable way to package and deploy software applications. However, containers also introduce new security challenges, such as vulnerabilities in container images, insecure configurations, and compromised host environments. In this post, we will outline 10 best practices for container security in DevOps to help you mitigate these risks. 1. Use trusted base images When building container images, it’s essential to use trusted base images from reputable sources.
Read More
How to Implement CI/CD Pipelines with Jenkins
April 20, 2023
Continuous Integration and Continuous Deployment (CI/CD) pipelines are critical components of modern software development practices. They enable development teams to deliver high-quality software quickly and reliably by automating the build, test, and deployment process. Jenkins is a popular open-source automation tool that can help you implement CI/CD pipelines easily. In this post, we will guide you through the process of setting up a basic CI/CD pipeline with Jenkins. Step 1: Install Jenkins The first step is to install Jenkins on your system.
Read More
[Solved] AWS Error: TooManyBuckets - Bucket Limit Exceeded
April 19, 2023
If you get the following error: │ Error: creating Amazon S3 (Simple Storage) Bucket (<your-bucket-name): TooManyBuckets: You have attempted to create more buckets than allowed │ status code: 400, request id: 0P1TV2VCEDKGFQNY, host id: gc9di71ONabECoBYkkzc7Lmqs0DOo2DVhV2kqCgNruNO6Okm5K3EXzosdf5MCxP8uI= │ The reason for the problem There is a soft limit of 100 S3 buckets per AWS account. Find out more https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html The solution to the problem Option 1 - Quick fix Remove unused S3 buckets.
Read More
How to check if a program exists from a Bash/Shell script
April 18, 2023
You can look to use: command -v <the_command> There are also 2 other ways, that we will run through a little further down, but for now.. How to use the command if a conditional if ! command -v <the_command> &> /dev/null then echo "<the_command> could not be found" exit fi To summarize, there are 3 ways you can do this Option 1 - Using command command -v foo >/dev/null 2>&1 || { echo >&2 "foo is not installed.
Read More
The DevOps Culture
April 17, 2023
DevOps is a software development approach that emphasizes collaboration and communication between development and operations teams. DevOps culture refers to the values, principles, and practices that foster this collaboration and enable teams to work together effectively. Here are some key elements of DevOps culture: Collaboration DevOps culture emphasizes collaboration between development, operations, and other stakeholders involved in the software development process. This collaboration ensures that all team members are working towards the same goal and have a shared understanding of the project.
Read More
Teach me Kubernetes - Part 7 - Sidecar Containers
April 16, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a sidecar container is a secondary container that runs in the same Pod as the primary container. The sidecar container runs alongside the primary container and shares the same network namespace, IPC namespace, and mount namespace. Here are some key features of sidecar containers in Kubernetes: Sidecar containers are used to enhance the functionality of the primary container: The sidecar container runs alongside the primary container and provides additional functionality that the primary container needs to function properly.
Read More
Teach me Kubernetes - Part 6 - Deployments
April 15, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a Deployment is a higher-level abstraction that manages the deployment and scaling of a set of Pods. Deployments provide a declarative way to manage the desired state of your application, making it easy to roll out updates and scale your application over time. Here are some key features of Deployments in Kubernetes : Deployments manage the desired state of your application: You can specify the desired state of your application (e.
Read More
Teach me Kubernetes - Part 5 - Services
April 14, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a Service is an abstraction that provides a stable, IP address and DNS name for a set of Pods. Services allow you to decouple the logical representation of your application from the underlying infrastructure, making it easier to manage and scale your application over time. Here are some key features of Services in Kubernetes: Services provide a stable IP address and DNS name: A Service is assigned a static IP address and DNS name that remains the same even if the underlying Pods are recreated or rescheduled.
Read More
Teach me Kubernetes - Part 4 - Replication Controllers
April 13, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a ReplicationController (also known as a “ReplicaSet” in newer versions of Kubernetes) is a controller that ensures that a specified number of replicas of a Pod are running at any given time. The ReplicationController is responsible for monitoring the state of the Pods it manages and taking corrective action if the desired state does not match the actual state.
Read More
Teach me Kubernetes - Part 3 - Pods
April 12, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a Pod is the smallest and simplest unit in the cluster. A Pod represents a single instance of a running process in a container, and it encapsulates one or more container images, storage resources, and network configurations. Pods are used to run and manage containerized applications in Kubernetes, and they provide a mechanism for managing and scaling containers.
Read More
Teach me Kubernetes - Part 2 - Nodes
April 11, 2023
Looking for the entire 7 part guide? Start at the Overview In Kubernetes, a Node is a worker machine that runs containerized applications. Nodes are responsible for running Pods, which are the smallest deployable units in Kubernetes. Nodes in a Kubernetes cluster can be physical or virtual machines, and they typically have multiple CPUs and large amounts of memory and storage. Each Node runs a container runtime, such as Docker or containerd, which is responsible for managing the containers that run on the Node.
Read More
Teach me Kubernetes - Part 1 - Overview
April 10, 2023
Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. With Kubernetes, you can manage containerized applications across multiple hosts, scale them up or down as needed, and even roll out updates without downtime. Here are some key concepts you need to understand to get started with Kubernetes: Nodes: A node is a physical or virtual machine that runs your containerized applications. It can be a virtual machine running in a cloud provider or a physical server in your data center.
Read More
How to Create a Simple Chatbot in Python
April 9, 2023
This is a simple chatbot in Python using the NLTK library. See the below example Python code: # Import necessary libraries from nltk.chat.util import Chat, reflections # Define your chatbot's responses responses = { "hello": "Hello, how can I assist you?", "hi": "Hi there! How can I help you today?", "how are you": "I'm doing well, thank you for asking.", "what can you do": "I can help you with tasks such as finding information, setting reminders, and more!
Read More
Create Transit Gateway with Attachments in Terraform
April 8, 2023
The following example Terraform code snippet creates a Transit Gateway with VPC and VPN attachments: provider "aws" { region = "us-west-2" } # Create a transit gateway resource "aws_ec2_transit_gateway" "example" { description = "Example transit gateway" } # Create a VPC attachment resource "aws_ec2_transit_gateway_vpc_attachment" "example_vpc_attachment" { subnet_ids = ["subnet-abc123", "subnet-def456"] # IDs of the subnets in the VPC to attach transit_gateway_id = aws_ec2_transit_gateway.example.id vpc_id = "vpc-xyz789" # ID of the VPC to attach } # Create a VPN attachment resource "aws_ec2_transit_gateway_vpn_attachment" "example_vpn_attachment" { transit_gateway_id = aws_ec2_transit_gateway.
Read More
How to Create an AWS EC2 Instance in Terraform
April 7, 2023
The following Terraform code snippet creates an EC2 instance for you. provider "aws" { region = "us-west-2" } resource "aws_instance" "example" { ami = "ami-0c94855ba95c71c99" # Amazon Linux 2 AMI instance_type = "t2.micro" key_name = "example-keypair" tags = { Name = "example-instance" } } In this example, we’re using the aws_instance resource type to create an EC2 instance in the us-west-2 region. We’re using the ami parameter to specify the Amazon Linux 2 AMI ID, and the instance_type parameter to specify a t2.
Read More
A Primer on Terraform Concepts
April 6, 2023
Terraform is an open-source tool for building, changing, and versioning infrastructure safely and efficiently. It allows you to describe your infrastructure as code and manage it in a version-controlled way, just like you would with application code. Here are the basic steps of how Terraform works: Write your infrastructure code: You write infrastructure code in the Terraform configuration language (HCL) to describe the resources you want to create. You can define resources like servers, load balancers, databases, and more, as well as their configurations and relationships.
Read More
How to Learn Recursion by Example in Python
April 5, 2023
Here’s an example code in Python that demonstrates recursion: def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(5)) # Output: 120 This code defines a function factorial that calculates the factorial of a given number n. The factorial of a number is the product of all positive integers up to and including that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
Read More
Understanding Site Reliability Engineering (SRE)
April 4, 2023
Site Reliability Engineering (SRE) can also help organizations to be more proactive in identifying and addressing potential issues before they become major problems. By monitoring system performance and using data-driven insights, SRE teams can detect and respond to issues more quickly, reducing the impact on customers and the business. This can help to increase uptime and reduce the cost of downtime, which can have a direct impact on revenue and profitability.
Read More
What is DevOps?
April 3, 2023
DevOps is a term that combines “development” and “operations.” It is a methodology that aims to bridge the gap between the software development and IT operations teams. DevOps is a set of practices that focuses on automating the software development process, reducing the time between writing code and deploying it to production, and ensuring a high level of quality in the delivered software. Introduction to DevOps DevOps is a set of practices that combines software development and IT operations.
Read More
How to Create a Password Generator in Golang
April 2, 2023
Introduction In today’s digital age, password security is more important than ever before. Hackers can easily guess weak passwords, leading to identity theft and other cybersecurity breaches. To ensure our online safety, we need to use strong and secure passwords that are difficult to guess. A good password generator can help us create random and strong passwords. In this blog post, we’ll discuss how to create a password generator in Golang.
Read More
How does Disaster Recovery work in the Cloud?
April 1, 2023
Disaster Recovery (DR) in the cloud refers to the process of recovering IT infrastructure and data in the event of a disaster, such as a natural disaster or a cyber attack, in a cloud environment. Cloud-based Disaster Recovery (DR) is different from traditional DR because it utilizes cloud services and technologies to protect data and applications and minimize downtime. Some key elements involved in implementing a Disaster Recovery plan in the cloud covers topics such as the following.
Read More
What is DevOps and why is it important?
March 31, 2023
DevOps is a software development methodology that emphasizes collaboration and communication between software developers and IT operations teams. It is a set of practices that seeks to streamline the software development lifecycle, from planning and coding to testing and deployment, through the use of automation, monitoring, and iterative development processes. The primary goal of DevOps is to deliver software more quickly, reliably, and efficiently by breaking down silos between development and operations teams and encouraging continuous feedback and improvement.
Read More
What is the Zen of Python?
March 30, 2023
The Zen of Python is an Easter Egg that long time Pythoneer (Tim Peters) channeled the guiding principals for the language’s design principals into 20 aphorisms, of which only 19 of them are written down. How to access this Zen of Python Easter Egg By importing this into your Python application, it will immediately print as follows: import this What is the Zen of Python? Beautiful is better than ugly. Explicit is better than implicit.
Read More
Bash: Convert HTML to Markdown Recursively with Pandoc
March 29, 2023
You can recursively convert all your HTML files to Mardown format in Bash, by using Pandoc. find . \-name "*.ht*" | while read i; do pandoc -f html -t markdown "$i" -o "${i%.*}.md"; done
Read More
How to Create a Password Generator in C++
March 27, 2023
You can easily create a password generator in C++ with the following simple method. How to create the Password Generator in C++ #include <iostream> #include <string> #include <algorithm> #include <random> std::string generate_password(int length = 16) { std::string seed = string("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + string("0123456789") + string("!@#$%^&*()_+=-{}[]\\|:;<>,.?/"); std::string password_string = seed; std::shuffle(password_string.begin(), password_string.end(), std::mt19937{std::random_device{}()}); return password_string.substr(0, length); } int main() { std::cout << generate_password() << std::endl; std::cout << generate_password(28) << std::endl; return 0; }
Read More
How do you architect Disaster Recovery in AWS?
March 26, 2023
Disaster recovery (DR) in AWS involves creating a plan and set of procedures to help your organization recover from a catastrophic event, such as a natural disaster, power outage, or cyber attack, that could impact your business operations. AWS provides a range of tools and services to help you architect an effective DR solution in the cloud. Here are the high-level steps to architect a Disaster Recovery solution in AWS:
Read More
What options exist for Infrastructure as Code (IaC)
March 25, 2023
There are several options for Infrastructure as Code (IaC) tools that can help automate the provisioning and management of infrastructure resources, such as servers, networks, and storage, in a reliable and reproducible way. Here are some of the most popular IaC options: Terraform: An open-source tool by HashiCorp that supports a wide range of infrastructure providers, including AWS, Azure, Google Cloud, and more. Terraform uses a declarative language to describe infrastructure as code and can manage both low-level and high-level resources.
Read More
How to learn Java in 1 day
March 24, 2023
Learning Java in one day is not a realistic goal, as Java is a complex programming language that requires time and practice to master. However, here are some tips to get you started: Start with the basics: Before diving into complex topics, learn the basics of Java, such as variables, data types, control structures, and object-oriented programming principles. Watch tutorials and read documentation: There are many resources available online that can help you learn Java quickly.
Read More
How to read user input as numbers in Python
March 23, 2023
In Python 3 onwards, the input function returns a string type.. int value You can explicitly convert this into an int type. val = int(input("Enter a number: ")) float value If you need to accept fractional components, then simply swap this out with a float type: val = float(input("Enter a number:")) map multiple values If you have multiple integers in a single line, then you can use map to extract them into a list:
Read More
Capitalize First Letter of Each Word in Python
March 22, 2023
If you have a sentence containing multiple words, and you want each of the words to start with a capital letter, then you can do one of the following: Option 1 - using string.capwords() import string string.capwords('this is a test!') Output: 'This Is A Test!' Option 2 - using title() 'this is a test!'.title() Output: 'This Is A Test!' Option 3 - using join(), split() and list comprehensions " ".join(w.capitalize() for w in 'this is a test!
Read More
How to Create a Password Generator in Python
March 16, 2023
You can easily create a password generator in Python with the following simple method. How to create the Password Generator in Python import string import random def generate_password(length=16): seed = f"{string.ascii_letters}{string.ascii_lowercase}{string.ascii_uppercase}{string.punctuation}" password_string = [x for x in seed] random.shuffle(password_string) return ''.join(password_string[:length]) How to use the Password Generator in Python With this function, you can either call the generate_password() function without any arguments, and it will generate a 16 digit long password, unless you need a longer one, then pass in an integer to specify the lengh of the password you would like.
Read More
How to Convert Bytes to a String in Python
March 14, 2023
If you need to convert bytes to a string in Python, then you can do the following: your_string = b'This works \xE2\x9C\x85'.decode("utf-8") print(your_string) Output: This works ✅ Note that in the above example, we have converted a utf-8 string to.
Read More
How to measure the elapsed time in Python
March 13, 2023
Option 1 - using the time module import time start = time.time() print(23*2.3) end = time.time() print(end - start) Output: 52.9 3.600120544433594e-05 Option 2 - using the timeit module from timeit import default_timer as timer start = timer() print(23*2.3) end = timer() print(end - start) Output: 52.9 6.355400000000039e-05
Read More
How to Change a MariaDB/MySQL Data Directory to a New Location on Linux
March 7, 2023
Step 1 — Moving the MariaDB Data Directory mysql -u root -p select @@datadir; Output: +-----------------+ | @@datadir | +-----------------+ | /var/lib/mysql/ | +-----------------+ 1 row in set (0.00 sec) exit sudo systemctl stop mariadb sudo systemctl status mariadb Output: mysql systemd[1]: Stopped MariaDB database server. sudo rsync -av /var/lib/mysql /mnt/my-volume-01 sudo mv /var/lib/mysql /var/lib/mysql.bak Step 2 — Pointing to the New Data Location sudo vi /etc/my.cnf [mysqld] . . .
Read More
[Solved] Docker Daemon Connection Error: Daemon Running?
March 4, 2023
If you get the following error when trying to run a Docker container: Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Then you can resolve it by running the following: systemctl start docker If this doesn’t work because of a root user issue, then you can do the following first: gpasswd -a $USER docker Additional issues? Issue 1 If you have tried the above, and get this error:
Read More
[Solved] M1 Docker Image Platform Mismatch with Host (ARM64)
March 3, 2023
If you get the following error when trying to run a Docker container that was built on an M1 mac: M1 docker preview and keycloak 'image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)' Issue The solution Then you can do simply add the following argument to your docker build command. --platform linux/amd64 Where this goes docker build --platform linux/amd64 -t your_docker_item .
Read More
How to get the SHA512 sum of a string using Python
March 2, 2023
If you need to get the SHA512 sum of a string using Python, then you can do the following. Step 1 Firstly, we need to use the hashlib module: import hashlib Step 2 Now make sure that the input string is encoded correctly. your_input = "this is your input string".encode('utf-8') Step 3 Finally use the sha512 function of the hashlib module, and get the hexdigest() value from it: hashlib.sha512(your_input).hexdigest() Putting it all together import hashlib your_input = "this is your input string".
Read More
How to get the SHA256 sum of a string using Python
March 1, 2023
If you need to get the SHA256 sum of a string using Python, then you can do the following. Step 1 Firstly, we need to use the hashlib module: import hashlib Step 2 Now make sure that the input string is encoded correctly. your_input = "this is your input string".encode('utf-8') Step 3 Finally use the sha256 function of the hashlib module, and get the hexdigest() value from it: hashlib.sha256(your_input).hexdigest() Putting it all together import hashlib your_input = "this is your input string".
Read More
How to get the MD5 sum of a string using Python
February 28, 2023
If you need to get the MD5 sum of a string using Python, then you can do the following. Step 1 Firstly, we need to use the hashlib module: import hashlib Step 2 Now make sure that the input string is encoded correctly. your_input = "this is your input string".encode('utf-8') Step 3 Finally use the md5 function of the hashlib module, and get the hexdigest() value from it: hashlib.md5(your_input).hexdigest() Putting it all together import hashlib your_input = "this is your input string".
Read More
[Solved] TypeError: datetime Not JSON Serializable
February 27, 2023
If you get the following error: TypeError: Object of type datetime is not JSON serializable ..then you can solve it by using this trick: json.dumps(your_dict, indent=4, sort_keys=True, default=str)
Read More
How to Return a List of All AWS Lambda Function Names in CLI
February 24, 2023
If you would like to list all AWS Lambda Function Names in your CLI using the AWS CLI, then you can do this: Get a List of all Lambda Functions aws lambda list-functions However, note that this will return a potentially large JSON payload back to your CLI. So what if you only want a list of the function names themselves? You can couple the AWS command above, with the jq command as follows:
Read More
How much faster is Python code?
February 23, 2023
The speed of Python code compared to other programming languages depends on a variety of factors, such as the specific task being performed, the libraries and frameworks used, the quality of the code implementation, and the hardware on which the code is executed. In general, Python is an interpreted language, which means that code is executed line-by-line by an interpreter, rather than being compiled into machine code beforehand. This can make Python code slower than compiled languages like C or C++ for some tasks.
Read More
Zip & Encode Dict to String & Back in Python
February 22, 2023
If you have a Python dictionary, and want to encode it as a string and zip it to save space, perhaps for passing a dictionary through as an environment variable or similar, then you can do the following Zip then Encode / Decode then Unzip Functions import json, gzip, base64 from io import BytesIO def _zip_then_encode(data: dict) -> str: """Gzip and base64 encode a dictionary""" if type(data) != dict: raise TypeError("data must be a dictionary") compressed = BytesIO() with gzip.
Read More
What Categories of Websites are there?
February 17, 2023
There are many different categories of websites, but here are some of the most common: E-commerce websites: These websites sell products or services online. Examples include Amazon, eBay, and Etsy. News websites: These websites provide up-to-date news and information on a variety of topics. Examples include CNN, BBC, and The New York Times. Blogging websites: These websites are used for personal or business blogs. Examples include WordPress, Blogger, and Medium.
Read More
How to Generate a Random Number between 2 numbers in Python
February 16, 2023
If you need to generate a random number between two (2) numbers in Python, then you can make use of the random module. First, import the module: import random Then you can use it like this: random.randint(0, 255) Another option is to use randrange and uniform as follows: from random import randrange, uniform # randrange gives you an integral value irand = randrange(0, 10) # uniform gives you a floating-point value frand = uniform(0, 10)
Read More
How to Install AWS SAM CLI on Mac
February 15, 2023
If you need to install AWS SAM CLI on a Mac, then the easiest option is to use Homebrew with the following commands: brew tap aws/tap brew install aws-sam-cli Now you can validate the installation as follows: sam --version
Read More
How to count the amount of rows in MariaDB fast
February 11, 2023
If you need to find the fastest way to count the number of rows in a massive MariaDB, or MySQL table, then you can do the following instead of performing a select count() query: show table status like '<TABLE_NAME>' This will provide you with a table of information about the table statistics, including the amount of rows.
Read More
How to find the Product of Consecutive Fib Numbers in Python
February 10, 2023
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, … This is the Van Eck’s Sequence. Let’s go through it step by step. Term 1: The first term is 0. Term 2: Since we haven’t seen 0 before, the second term is 0. Term 3: Since we had seen a 0 before, one step back, the third term is 1 Term 4: Since we haven’t seen a 1 before, the fourth term is 0 Term 5: Since we had seen a 0 before, two steps back, the fifth term is 2.
Read More
How to Solve Van Eck's Sequence in Python
February 9, 2023
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, … This is the Van Eck’s Sequence. Let’s go through it step by step. Term 1: The first term is 0. Term 2: Since we haven’t seen 0 before, the second term is 0. Term 3: Since we had seen a 0 before, one step back, the third term is 1 Term 4: Since we haven’t seen a 1 before, the fourth term is 0 Term 5: Since we had seen a 0 before, two steps back, the fifth term is 2.
Read More
How to Solve: Help the Bookseller Challenge in Python
February 8, 2023
A bookseller has lots of books classified in 26 categories labeled A, B, … Z. Each book has a code c of 3, 4, 5 or more characters. The 1st character of a code is a capital letter which defines the book category. In the bookseller’s stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.
Read More
How to solve AWS MediaPackage PackagingGroup Quota Limit
January 31, 2023
If you are using AWS Elemental MediaPackage and hit the following error, then you need to either do one of the following: Error: error waiting for CloudFormation Stack (arn:aws:cloudformation:eu-west-1:800417762774:stack/dev-MediaPackage-Vod-1/511fc7a0-a092-11ed-b853-068baf6ac251) create: failed to create CloudFormation stack, delete requested (DELETE_COMPLETE): ["The following resource(s) failed to create: [PackagingGroup]. Delete requested by user." "Resource handler returned message: \"Limit exceeded for resource of type 'AWS::MediaPackage::PackagingGroup'. Reason: You reached the quota for resource=PackagingGroup. Delete the resources that you don?
Read More
How to Run Cdk Bootstrap
January 30, 2023
To bootstrap an AWS CDK environment, you simply need to do the following: npx aws-cdk bootstrap …for each environment that you would like the CD to operate within. This will deploy all the required prerequisites to the AWS account, such as the: An Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments. The required resources are defined in an AWS CloudFormation stack, called the bootstrap stack, which is usually named CDKToolkit.
Read More
How to Get Account Number from AWS Lambda
January 24, 2023
If you need to get the current Account Number, or Account ID from within a Lambda execution, then you can access invoked_function_arn from the context and return the associated value as follows: aws_account_id = context.invoked_function_arn.split(":")[4]
Read More
Summary of the Frequently Used AWS STS API calls
January 19, 2023
AssumeRole – is useful for allowing existing IAM users to access AWS resources that they don’t already have access to. For example, the user might need access to resources in another AWS account. It is also useful as a means to temporarily gain privileged access—for example, to provide multi-factor authentication (MFA). You must call this API using existing IAM user credentials. AssumeRoleWithWebIdentity – returns a set of temporary security credentials for federated users who are authenticated through a public identity provider.
Read More
Understanding Locking and Conditional Writes in AWS DynamoDB
January 18, 2023
Optimistic locking is a strategy to ensure that the client-side item that you are updating (or deleting) is the same as the item in DynamoDB. Optimistic concurrency depends on checking a value upon save to ensure that it has not changed. If you use this strategy, then your database writes are protected from being overwritten by the writes of others — and vice-versa. By default, the DynamoDB write operations (PutItem, UpdateItem, DeleteItem) are unconditional: each of these operations will overwrite an existing item that has the specified primary key.
Read More
AWS CodeDeploy Deployment Type Options
January 17, 2023
CodeDeploy provides two (2) deployment type options: Option 1 – In-place Deployment In-place deployment: The application on each instance in the deployment group is stopped, the latest application revision is installed, and the new version of the application is started and validated. You can use a load balancer so that each instance is deregistered during its deployment and then restored to service after the deployment is complete. Only deployments that use the EC2/On-Premises compute platform can use in-place deployments.
Read More
Defining Amazon ECS Task Placement Strategies
January 16, 2023
Amazon ECS supports the following task placement strategies: binpack – Place tasks based on the least available amount of CPU or memory. This minimizes the number of instances in use. random – Place tasks randomly. spread – Place tasks evenly based on the specified value. Accepted values are attribute key-value pairs, instanceId, or host.
Read More
Deployment methods in AWS Elastic Beanstalk
January 15, 2023
– All at once – Deploy the new version to all instances simultaneously. All instances in your environment are out of service for a short time while the deployment occurs. – Rolling – Deploy the new version in batches. Each batch is taken out of service during the deployment phase, reducing your environment’s capacity by the number of instances in a batch. – Rolling with additional batch – Deploy the new version in batches, but first launch a new batch of instances to ensure full capacity during the deployment process.
Read More
How to update NTP to sync clock on Linux
January 4, 2023
If you need to sync the clock on Linux using the central NTP clock service, you can do the following: sudo service ntp stop sudo ntpd -gq sudo service ntp start The -gg flags do the following: Tell g flag tells the NTP Daemon to correct the time regardless of the offset The q flag tells it to exit immediately after setting the time
Read More
How to Find IP Address Ranges used by Amazon S3
December 13, 2022
You can query the ip-ranges Amazon AWS URL, and parse the results through jq as follows: Generic S3 IP Ranges Query: curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.service=="S3")' Response: { "ip_prefix": "3.5.140.0/22", "region": "ap-northeast-2", "service": "S3", "network_border_group": "ap-northeast-2" } { "ip_prefix": "52.219.170.0/23", "region": "eu-central-1", "service": "S3", <truncated> Region Specific S3 IP Ranges Query: curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="eu-west-1") | select(.service=="S3") | .ip_prefix' Response: 18.34.32.0/20 3.
Read More
How to Find the nth Reverse Number in Java
December 12, 2022
The challenge Reverse Number is a number which is the same when reversed. For example, the first 20 Reverse Numbers are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 Task You need to return the nth reverse number. (Assume that reverse numbers start from 0 as shown in the example.) Notes 1 < n <= 100000000000 The solution in Java Option 1:
Read More
How to Find the Sum of Intervals in Java
December 11, 2022
The challenge Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.
Read More
How to Find the Stray Number in Python
December 10, 2022
The challenge You are given an odd-length array of integers, in which all of them are the same, except for one single number. Complete the method which accepts such an array, and returns that single different number. The input array will always be valid! (odd-length >= 3) Examples [1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3 The solution in Python Option 1: def stray(arr): for x in arr: if arr.
Read More
How to Find the EDID UUID of External Mac Monitors
December 9, 2022
You can issue the following command on an Apple Mac’s terminal to show the EDID UUID (unique serial number) of all attached external monitors: ioreg -l | grep EDID
Read More
[Solved] jsii.errors.JSIIError: docker exited with status 1
December 8, 2022
If you get the following error while running AWS CDK: raise JSIIError(resp.error) from JavaScriptError(resp.stack) jsii.errors.JSIIError: docker exited with status 1 Then you can resolve it as follows: How to solve docker exited with status 1 error Make sure that your local Docker client is running. Start docker on the local machine and CDK will be able to make the Docker connections required.
Read More
How to Filter a Number in C
December 7, 2022
The challenge The number has been mixed up with the text. Your goal is to retrieve the number from the text, can you return the number back to its original state? Task Your task is to return a number from a string. Details You will be given a string of numbers and letters mixed up, you have to return all the numbers in that string in the order they occur.
Read More
How to Take a Ten Minute Walk in C
December 6, 2022
The challenge You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones — everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg.
Read More
How to Count Stats of a String in C
December 5, 2022
The challenge You will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows. Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters. The solution in C Option 1: void count_char_types (const char *string, unsigned counts[4]) { char c; counts[0] = counts[1] = counts[2] = counts[3] = 0; while((c = *string++)) if(c >= 'A' && c <= 'Z') counts[0]++; else if(c >= 'a' && c <= 'z') counts[1]++; else if(c >= '0' && c <= '9') counts[2]++; else counts[3]++; } Option 2:
Read More
How to Convert a String to the NATO Phonetic Alphabet in C
December 4, 2022
The challenge You’ll have to translate a string to Pilot’s alphabet (NATO phonetic alphabet). Input: If, you can read? Output: India Foxtrot , Yankee Oscar Uniform Charlie Alfa November Romeo Echo Alfa Delta ? Note: There are preloaded dictionary you can use, named NATO The set of used punctuation is ,.!?. Punctuation should be kept in your return string, but spaces should not. Xray should not have a dash within. Every word and punctuation mark should be seperated by a space ‘ ‘.
Read More
How to Add 1 to the Value of each Array in C
December 3, 2022
The challenge Given an array of integers of any length, return an array that has 1 added to the value represented by the array. the array can’t be empty only non-negative, single digit integers are allowed Return nil (or your language’s equivalent) for invalid inputs. Examples: Valid arrays [4, 3, 2, 5] would return [4, 3, 2, 6] [1, 2, 3, 9] would return [1, 2, 4, 0] [9, 9, 9, 9] would return [1, 0, 0, 0, 0]
Read More
How to Calculate the Sum of a Sequence in C
December 2, 2022
The challenge Your task is to make function, which returns the sum of a sequence of integers. The sequence is defined by 3 non-negative values: begin, end, step (inclusive). If begin value is greater than the end, function should returns **** Examples 2,2,2 --> 2 2,6,2 --> 12 (2 + 4 + 6) 1,5,1 --> 15 (1 + 2 + 3 + 4 + 5) 1,5,3 --> 5 (1 + 4) The solution in C Option 1:
Read More
How to Solve the Sum of Triangular Numbers in C
December 1, 2022
The challenge Your task is to return the sum of Triangular Numbers up-to-and-including the nth Triangular Number. Triangular Number: “any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc.” [01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18 19 20 [21] e.g. If 4 is given: 1 + 3 + 6 + 10 = 20.
Read More
How to Determine if a String Only Contains Unique Characters in C
November 30, 2022
The challenge Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise. The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. ‘a’ and ‘A’ are considered different characters. The solution in C Option 1: int has_unique_chars(const char *str) { int mask[128]={0}; while (*str) if (++mask[*str++]>1) return 0; return 1; } Option 2: #include <limits.h> _Bool has_unique_chars(const char *str) { char hit[CHAR_MAX + 1] = {0}; while (*str) { if (*str < 0) { str++; continue; } if (hit[*str]) return 0; hit[*str++] = 1; } return 1; } Option 3:
Read More
How to Find the Maximum Multiple in C
November 29, 2022
The challenge Given a Divisor and a Bound , Find the largest integer N , Such That , Conditions : N is divisible by divisor N is less than or equal to bound N is greater than 0. Notes The parameters (divisor, bound) passed to the function are only positive values . It’s guaranteed that a divisor is Found .Input » Output Examples maxMultiple (2,7) ==> return (6) Explanation: (6) is divisible by (2) , (6) is less than or equal to bound (7) , and (6) is > 0 .
Read More
How to Assign a Digital Cypher in C
November 28, 2022
The challenge Digital Cypher assigns to each letter of the alphabet unique number. For example: a b c d e f g h i j k l m 1 2 3 4 5 6 7 8 9 10 11 12 13 n o p q r s t u v w x y z 14 15 16 17 18 19 20 21 22 23 24 25 26 Instead of letters in encrypted word we write the corresponding number, eg.
Read More
How to Check for All Inclusive in C
November 27, 2022
The challenge Input: a string strng an array of strings arr Output of function contain_all_rots(strng, arr) (or containAllRots or contain-all-rots): a boolean true if all rotations of strng are included in arr false otherwise Examples: contain_all_rots( "bsjq", ["bsjq", "qbsj", "sjqb", "twZNsslC", "jqbs"]) -> true contain_all_rots( "Ajylvpy", ["Ajylvpy", "ylvpyAj", "jylvpyA", "lvpyAjy", "pyAjylv", "vpyAjyl", "ipywee"]) -> false) Note: Though not correct in a mathematical sense we will consider that there are no rotations of strng == "" and for any array arr: contain_all_rots("", arr) --> true The solution in C Option 1:
Read More
How to Solve for Factorial in C
November 26, 2022
The challenge In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1. Write a function to calculate factorial for a given input. If input is below 0 or above 12 return -1 (C).
Read More
How to Create an Incrementer in C
November 25, 2022
The challenge Given an input of an array of digits, return the array with each digit incremented by its position in the array: the first digit will be incremented by 1, the second digit by 2, etc. Make sure to start counting your positions from 1 ( and not 0 ). Your result can only contain single digit numbers, so if adding a digit with its position gives you a multiple-digit number, only the last digit of the number should be returned.
Read More
How to Return the Closest Number Multiple of 10 in C
November 24, 2022
The challenge Given a number return the closest number to it that is divisible by 10. Example input: 22 25 37 Expected output: 20 30 40 The solution in C Option 1: #include <math.h> int round_to_10 (int n) { return round(n / 10.0) * 10; } Option 2: int round_to_10(int n) { return (n + 5) / 10 * 10; } Option 3: int round_to_10 (int n) { int r = n % 10; if (r > 0) return r < 5 ?
Read More
How to Reverse Every Other Word in a String in C
November 23, 2022
The challenge Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this challenge. The solution in C Option 1: #include <stddef.h> #include <stdbool.h> void reverse_alternate(const char *string, char *result) { bool is_word = false, is_second = false, not_first = false; for (const char *s = string; *s; ++s) { if (*s == ' ' && is_word) { is_word = false; is_second = !
Read More
How to Solve Simple Beads Count in C
November 22, 2022
The challenge Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads. @ @@ @ @@ @ @@ @ @@ @ @@ @ Implement count_red_beads(n) (countRedBeads(n)) so that it returns the number of red beads. If there are less than 2 blue beads return 0. The solution in C Option 1: int countRedBeads(n) { if(n<=1) return 0; return 2*(n-1); } Option 2:
Read More
How to Solve the Maze Runner in C
November 21, 2022
The challenge Introduction Welcome Adventurer. Your aim is to navigate the maze and reach the finish point without touching any walls. Doing so will kill you instantly! Task You will be given a 2D array of the maze and an array of directions. Your task is to follow the directions given. If you reach the end point before all your moves have gone, you should return Finish. If you hit any walls or go outside the maze border, you should return Dead.
Read More
How to Take a Number and Sum It’s Digits Raied to the Consecutive Powers in C
November 20, 2022
The challenge The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this challenge. What’s the use of saying “Eureka”? Because this sum gives the same number. In effect: 89 = 8^1 + 9^2 The next number in having this property is 135. See this property again: 135 = 1^1 + 3^2 + 5^3 We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.
Read More
How to Find the Middle Element in C
November 19, 2022
The challenge You need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements. The input to the function will be an array of three distinct numbers (Haskell: a tuple). For example: gimme([2, 3, 1]) => 0 2 is the number that fits between 1 and 3 and the index of 2 in the input array is __.
Read More
How to Invite More Women in C
November 18, 2022
The challenge Task King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel. To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year’s party. He gave you a list of integers of all the party goers.
Read More
How to Build a Tower in C
November 17, 2022
The challenge Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors. A tower block is represented with "*" character. For example, a tower with 3 floors looks like this: [ " * ", " *** ", "*****" ] And a tower with 6 floors looks like this: [ " * ", " *** ", " ***** ", " ******* ", " ********* ", "***********" ] The solution in C Option 1:
Read More
How to Calculate A Rule of Divisibility by 7 in C
November 16, 2022
The challenge A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a number known to be divisible by 7 is obtained; you can stop when this number has at most 2 digits because you are supposed to know if a number of at most 2 digits is divisible by 7 or not.
Read More
How to Categorize a New Member in C
November 15, 2022
The challenge The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed. To be a senior, a member must be at least 55 years old and have a handicap greater than 7. In this croquet club, handicaps range from -2 to +26; the better the player the lower the handicap.
Read More
How to Solve Deodorant Evaporator in C
November 14, 2022
The challenge This program tests the life of an evaporator containing a gas. We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive. The program reports the nth day (as an integer) on which the evaporator will be out of use.
Read More
How to Find the Divisors in C
November 13, 2022
The challenge Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer’s divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string ‘(integer) is prime’ (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust). Example: divisors(12); // results in {2, 3, 4, 6} divisors(25); // results in {5} divisors(13); // results in NULL The solution in C Option 1:
Read More
Solving Love vs Friendship in C
November 12, 2022
The challenge If a = 1, b = 2, c = 3 ... z = 26 Then l + o + v + e = 54 and f + r + i + e + n + d + s + h + i + p = 108 So friendship is twice as strong as love 🙂 Your task is to write a function which calculates the value of a word based off the sum of the alphabet positions of its characters.
Read More
How to Bounce Balls in C
November 11, 2022
The challenge A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a window 1.5 meters from the ground. How many times will the mother see the ball pass in front of her window (including when it’s falling and bouncing?
Read More
How to Find the Capitals in C
November 10, 2022
The challenge Instructions Write a function that takes a single string (word) as argument. The function must return an ordered list containing the indexes of all capital letters in the string. Example Test.assertSimilar( capitals('CodEStAr'), [0,3,4,6] ); The solution in C Option 1: #include <stddef.h> #include <string.h> #include <stdlib.h> size_t *find_capitals(const char *word, size_t *nb_uppercase) { size_t n = strlen(word); size_t *arr = (size_t *) calloc(n, sizeof(size_t)); size_t j = 0; for(size_t i=0; i<n; i++) { if(word[i] >='A' && word[i] <='Z') { arr[j++] = i; } } *nb_uppercase = j; return realloc(arr, j * sizeof(size_t)); } Option 2:
Read More
How to Empty and Delete an S3 Bucket using the AWS CLI
November 9, 2022
Option 1 – Using AWS CLI Step 1 export bucketname='your-bucket-here' Step 2 aws s3api delete-objects --bucket $bucketname --delete "$(aws s3api list-object-versions --bucket $bucketname --output=json --query='{Objects: *[].{Key:Key,VersionId:VersionId}}')"; Step 3 aws s3 rb s3://$bucketname Option 2 – Using Python #!/usr/bin/env python BUCKET = 'your-bucket-here' import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET) bucket.object_versions.delete() bucket.delete()
Read More
What ports to open for FSx connection to AWS Managed Active Directory
November 8, 2022
If you are creating a FSx file system, and want to connect it to AWS Managed Active Directory, then you will need to create a VPC Security Group with the following ports: Inbound ports Rules Ports UDP 53, 88, 123, 389, 464 TCP 53, 88, 123, 389, 445, 464, 636, 3268, 3269, 9389, 49152-65535 Outbound ports All traffic, 0.0.0.0/0
Read More
How to Calculate Variance in Python
November 7, 2022
If you need to calculate variance in Python, then you can do the following. Option 1 – Using variance() from Statistics module import statistics list = [12,14,10,6,23,31] print("List : " + str(list)) var = statistics.variance(list) print("Variance: " + str(var)) Option 2 – Using var() from numpy module import numpy as np arr = [12,43,24,17,32] print("Array : ", arr) print("Variance: ", np.var(arr)) Option 3 – Using sum() and List Comprehensions list = [12,43,24,17,32] average = sum(list) / len(list) var = sum((x-average)**2 for x in list) / len(list) print(var)
Read More
How to Calculate the Sum of a List in Python
November 6, 2022
If you need to calculate and get the sum of a list in Python, then you can do the following. Option 1 – Using sum() myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] listSum = sum(myList) print(f"Sum of list -> {listSum}") If you get a TypeError then you can do the following: myList = ["1", "3", "5", "7", "9"] myNewList = [int(string) for string in myList] sum1 = sum(myNewList) sum2 = sum(number for number in myNewList) print(f"Sum of list -> {sum1}") print(f"Sum of list -> {sum2}") Option 2 – Using for myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] length = len(myList) listSum = 0 for i in range(length): listSum += myList[i] print(f"Sum of list -> {listSum}")
Read More
How to add a List to a Set in Python
November 5, 2022
If you need to add a list to a set in Python, then you can do the following: Option 1 – Using Tuple myset = set((1,2,3,4)) mylist = list(1,2,3]) myset.add(tuple(mylist)) print(myset) Output: {1, 2, 3, 4, (1, 2, 3)} Option 2 – Using set.update() myset = set((1,2,3,4)) mylist = list(8,9,12]) myset.update(tuple(mylist)) print(myset) Output: {1, 2, 3, 4, 8, 9, 12}
Read More
How to Remove Punctuation from a List in Python
November 4, 2022
If you have a Python list, and want to remove all punctuation, then you can do the following: First get all punctuation by using string.punctuation import string print(string.punctuation) Output: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ Option 1 – Using for import string words = ["hell'o", "Hi,", "bye bye", "good bye", ""] new_words = [] for word in words: if word == "": words.remove(word) else: for letter in word: if letter in string.punctuation: word = word.replace(letter,"") new_words.
Read More
How to Normalize a List of Numbers in Python
November 3, 2022
If you need to normalize a list of numbers in Python, then you can do the following: Option 1 – Using Native Python list = [6,1,0,2,7,3,8,1,5] print('Original List:',list) xmin = min(list) xmax=max(list) for i, x in enumerate(list): list[i] = (x-xmin) / (xmax-xmin) print('Normalized List:',list) Option 2 – Using MinMaxScaler from sklearn import numpy as np from sklearn import preprocessing list = np.array([6,1,0,2,7,3,8,1,5]).reshape(-1,1) print('Original List:',list) scaler = preprocessing.MinMaxScaler() normalizedlist=scaler.fit_transform(list) print('Normalized List:',normalizedlist) You can also specify the range of the MinMaxScaler().
Read More
How to Multiply a List by a Scalar in Python
November 2, 2022
If you need to multiply a list by a scalar in Python, then you can do one of the following: Option 1 – Using List Comprehensions li = [1,2,3,4] multiple = 2.5 li = [x*multiple for x in li] print(li) Output: [2.5, 5.0, 7.5, 10.0] Option 2 – Using map() li = [1,2,3,4] multiple = 2.5 def multiply(le): return le*multiple li = list(map(multiply,li)) print(li) Output: [2.5, 5.0, 7.5, 10.0] Option 3 – Using Lambda Functions li = [1,2,3,4] multiple = 2.
Read More
How to Find the Index of the Minimum Element in a List in Python
November 1, 2022
If you need to find the index of the minimum element in a list, you can do one of the following: Option 1 – Using min() and index() lst = [8,6,9,-1,2,0] m = min(lst) print(lst.index(m)) Output: 3 Option 2 – Using min() and for lst = [8,6,9,-1,2,0] m = min(lst) for i in range(len(lst)): if(lst[i]==m): print(i) break Output: 3 Option 3 – Using min() and enumerate() lst = [8,6,9,-1,2,0] a,i = min((a,i) for (i,a) in enumerate(lst)) print(i) Output: 3
Read More
How to Convert a Set to a String in Python
October 31, 2022
If you need to convert a set to a string in Python, then you can do one of the following: Option 1 – Using map() and join() str_new = ', '.join(list(map(str, se))) You can confirm this worked as follows: print(str_new) print(type(str_new)) # '1, 2, 3' # <class 'str'> Option 2 – Using repr() r_str = repr(se) You can confirm this worked as follows: print(r_str) print(type(r_str)) # {1, 2, 3} # <class 'str'>
Read More
How to Decrement a Loop in Python
October 30, 2022
If you need to decrement a loop in Python, then you can do the following: How to Decrement a loop in Python using -1 The optional third argument you can pass to the range function is the order. The default order is to count up / increment, while the -1 value, is to count down / decrement. for i in range(3, 0, -1): print(i) Output: 3 2 1 How to Decrement a loop in Python using while You can also use a while loop and set the value to the upper bound, and then decrement while in the loop itself.
Read More
How to Create Zip Archive of Directory in Python
October 29, 2022
If you need to create a zip of a directory using Python, then you can do the following: Create a Zip using shutil in Python import os import shutil filename = "compressed_archive" format = "zip" directory = os.getcwd() shutil.make_archive(filename, format, directory)
Read More
How to Remove the Last Character of a String in PHP
October 28, 2022
If you need to remove the last character of a string in PHP, then you can do the following: Option 1 – Using rtrim() Syntax: rtrim($string, $character) $mystring = "This is a PHP program!"; echo("Before Removal: $mystring\n"); # Before Removal: This is a PHP program! $newstring = rtrim($mystring, ". "); echo("After Removal: $newstring"); # After Removal: This is a PHP program Option 2 – Using substr() Syntax: substr($string, $start, $length)
Read More
How to Create Function with Multiple Returns in PHP
October 27, 2022
If you need to create a PHP function that returns multiple values, then you can do one of the following. Option 1 – Returning an array function returnArray() { return array("one", "two"); } // call the function and print the response var_dump(returnArray()); Option 2 – Returning a conditional function returnConditional($x = true) { if ($x) return "one"; else return "two"; } // call the function with a value and print the response var_dump(returnConditional(false)); Option 3 – Using generator to yield values function multipleValues() { yield "one"; yield "two"; } $res = multipleValues(); foreach($res as $r) { echo $r; // first val=="one", second val=="two" }
Read More
How to Download a File in NodeJS without any Third Party Libraries
October 26, 2022
If you need to download a file in NodeJS without using any third party libraries, then you can do the following. The NodeJS ecosystem comes with a fs module, this is to denote the FileSystem built in library. First declare your imports: const http = require('https'); const fs = require('fs'); Now you can use the https module to download a file, and write it to a stream using fs. const https = require("https"); const fs = require("fs"); const endpoint = "https://example/files/some_csv_file"; https.
Read More
How to Execute a Shell Script in NodeJS
October 25, 2022
If you need to execute a shell script in NodeJS, then you can use the exec keyword. Syntax: exec(command [, options] [, callback] const shell = require('shelljs') shell.exec("npm --version")
Read More
How to Print Multiple Arguments in Python
October 24, 2022
If you need to print out multiple arguments using Python, then you can do one of the following: Option 1 – Using print print("Something", "Else", "Please") Output: Something Else Please Option 2 – Using String Formatting print("Something {} {}".format("Else", "Please")) Output: Something Else Please Or with explicit ordering: print("Something {1} {0}".format("Else", "Please")) Output: Something Please Else Option 3 – Using F-String Formatting one = "Something" two = "Else" three = "Please" print(f"{one} {two} {three}") Output: Something Else Please
Read More
How to Delete all Resources Except One in Terraform
October 23, 2022
If you need to delete all resources created by Terraform, except for a single, specific one, then you can do the following: Step 1 – Get the current state list terraform state list Step 2 – Remove the exception resource Remove the specific resource that you don’t want Terraform to track anymore. terraform state rm <resource_to_be_removed> Step 3 – Destroy the resources terraform destroy
Read More
How to Copy Files between Two Nodes using Ansible
October 22, 2022
If you need to copy files between two (2) nodes, using Ansible, then you can do the following: This solution uses the synchronize module, specifically using the delegate_to:source-server keywords. - hosts: serverB tasks: - name: Copy Remote-To-Remote (from serverA to serverB) synchronize: src=/copy/from_serverA dest=/copy/to_serverB delegate_to: serverA
Read More
How to Delete Files and Folders in a Directory using Ansible
October 21, 2022
If you need to delete files and folders in a directory using Ansible, then you can do the following: - name: Delete content & entire directory file: state: absent path: /some/directory/path/
Read More
How to Copy Multiple Files with Ansible
October 20, 2022
If you need to copy multiple files using Ansible, then you can do the following: How to Copy Multiple Files with Ansible Look into using the with_fileglob loop as follows: - copy: src: "{{ item }}" dest: /etc/fooapp/ owner: root mode: 600 with_fileglob: - /playbooks/files/fooapp/* If you would like to do it as a task, then this could help: - name: Your copy task copy: src={{ item.src }} dest={{ item.dest }} with_items: - { src: 'another_file', dest: '/etc/somewhere' } - { src: 'dynamic', dest: '{{ var_path }}' } # repeat for additional files
Read More
How to Write Multiline Shell Scripts in Ansible
October 19, 2022
If you need to write a shell script in Ansible, you probably have something like this: - name: iterate user groups shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} with_items: "{{ users }}" But how do you write multiline shell scripts with this format? How to write Multiline shell scripts - name: iterate user groups shell: | groupmod -o -g {{ item['guid'] }} {{ item['username'] }} do_some_stuff_here and_some_other_stuff with_items: "{{ users }}" Just note that Ansible can do some strange things with manipulations of arguments, so you may want to follow something like this:
Read More
How to Pass Variables to Ansible Playbook CLI
October 18, 2022
If you need to pass a variable to Ansible playbook, using the command line, then you can do the following: Option 1 – Specifying command line arguments ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo" N.B. --extra-vars specified variables will override any variables with the same name defined inside the playbook. You can also read up on Passing Variables On The Command Line (Wayback Machine link to maintain versioning) Option 2 – Specify a YML file You can also specify a .
Read More
How to Create a Directory using Ansible
October 17, 2022
If you need to create a directory using Ansible, then you can do the following: Create a Directory in Ansible You will need the file module, then to create a directory you simply specify the option state=directory: - name: Creates a directory file: path: /src/www state: directory Note that with state=directory, all the immediate subdirectories will be created if they don’t already exist. Extending the file module - name: Creates a directory file: path: /src/www state: directory owner: www-data group: www-data mode: 0775 Create the Directories Recursively - name: Creates directory file: path: /src/www state: directory owner: www-data group: www-data mode: 0775 recurse: yes This is similar to the recursive argument used with mkdir -p
Read More
How to Disable Screensaver on Mac using the CLI
October 16, 2022
If you want to disable the Screensaver on your Mac, by using the Command Line Interface (CLI), then you can do the following: Step 1 – See what is currently set defaults read com.apple.screensaver Step 2 – Set the idleTime defaults -currentHost write com.apple.screensaver idleTime 0 Step 3 – (Optional) – Undo the change defaults -currentHost delete com.apple.screensaver idleTime
Read More
How to Remove Old and Unused Docker Images
October 15, 2022
If you need to remove any old and unused Docker images, then you can do the following: How to Remove Old and Unused Docker Images Firstly you need to see all the images: docker images You can also use ls to see the Docker Images: docker image ls How to Remove a Single Docker Image The docker rmi command will remove a single Docker image as follows: docker rmi <image_id> You can also use the Docker image names as follows:
Read More
How to Convert Milliseconds to Date in Javascript
October 14, 2022
If you need to convert Milliseconds to Date in Javascript, then you can do the following: How to Convert Milliseconds to Date in Javascript let date = new Date(milliseconds); date.toString(); Common Date Conversions From Milliseconds in Javascript let originalDate = new Date(milliseconds); // output: "D/MM/YYYY, H:MM:SS PM/AM" originalDate.toLocaleString(); //output: "D/MM/YYYY" originalDate.toLocaleDateString(); // output: "Day Month DD YYYY" originalDate.toDateString(); // output: "HH:MM:SS GMT+0530" originalDate.toTimeString(); // output: "Day Month DD YYYY HH:MM:SS GMT+0500" originalDate.
Read More
How to Convert String to Title Case in Javascript
October 13, 2022
If you need to convert a String to Title Case in Javascript, then you can do one of the following: Option 1 – Using a for loop function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); return str.join(' '); } console.log(titleCase("this is an example of some text!")); Output: This Is An Example Of Some Text! Option 2 – Using map() function titleCase(str) { return str.
Read More
How to Compile Multiple Java Files from a Single Command in Java
October 12, 2022
If you need to compile multiple Java files using a single command, then you can do the following. First, it’s good to learn how to compile a Java file. How to Compile a Java File Let’s take the following Java code: class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } To compile this, we simply do the following: javac HelloWorld.java Then when we need to run it, we do:
Read More
How to Convert JSON to a Java Object
October 11, 2022
If you need to convert JSON to a Java Object, then you can do one of the following: Option 1 – Using Gson import com.google.gson.Gson; public class SimpleTesting { public static void main(String[] args) throws InterruptedException { String json = """ { "firstName" : "Jane", "lastName" : "Doe", "dateOfBirth" : "1973-04-29", "address" : "81 Hype", "city" : "New York", "contact" : "0123456789" } """; Student data = new Gson().fromJson(json, Student.class); System.
Read More
How to Calculate Powers of Integers in Java
October 10, 2022
If you need to calculate the powers of Integers in Java, then you can do one of the following: Option 1 – Using for loops public class Power { public static void main(String args[]){ int number = 5; int power = 3; int result = calculatePower(number,power); System.out.println(number+"^"+power+"="+result); } static int calculatePower(int num, int power){ int answer = 1; if (num > 0 && power==0){ return answer; } else if(num == 0 && power>=1){ return 0; } else{ for(int i = 1; i<= power; i++) answer = answer*num; return answer; } } } Option 2 – Using Recursion public class Power { public static void main(String args[]){ int number = 3; int power = 3; int result = CalculatePower(number,power); System.
Read More
How to Get Today’s Date in Java
October 9, 2022
If you need to get today’s date in Java, then you can do one of the following: Option 1 – Using LocalDate import java.time.LocalDate; public class GetTodayDate { public static void main(String[] args) { LocalDate todaysDate = LocalDate.now(); System.out.println(todaysDate); } } Option 2 – Using Calendar and SimpleDateFormat import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class GetTodayDate { public static void main(String[] args) { SimpleDateFormat dtf = new SimpleDateFormat("yyyy/MM/dd"); Calendar calendar = Calendar.
Read More
How to Copy Files from Docker Container to Host
October 8, 2022
If you need to copy files from a Docker Container to the Host, then you can do one of the following: Option 1 – Using docker cp Syntax: docker cp [OPTIONS] CONTAINER: SRC_PATH DEST_PATH Setup the container: # pull the ubuntu image docker pull ubuntu # run the container locally docker run -it -d ubuntu # connect to the container docker exec -it abcde123456 /bin/bash Create a file from the container:
Read More
How to Get the IP Address of a Docker Container
October 7, 2022
If you need to get the IP Address of a Docker Container, then you can do the following: Option 1 – Connect to the Bridge Network Find out the network setup: docker network ls Create a docker container and assign it to the bridge network: docker run -dt <nginx> Get the information about the container: docker ps Inspect the network: docker network inspect bridge Now you can see the container IP Address.
Read More
How to Convert Time to String in Golang
October 6, 2022
If you need to convert Time to a String in Go, then you can do one of the following: Option 1 – Using time.Now package main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Time: ", currentTime.String()) } Option 2 – Using time.Time.String() package main import ( "fmt" "time" ) func main() { Time := time.Date(2022, 03, 28, 03, 50, 16, 0, time.UTC) t := Time.String() fmt.Printf("Time without the nano seconds: %v\n", t) }
Read More
How to Perform a Deep Copy in Golang
October 5, 2022
To perform a Deep Copy in Go, you can use a struct type as follows: Deep Copying using a struct in Go package main import ( "fmt" ) type Dog struct { age int name string friends []string } func main() { john := Dog{1, "Harry", []string{"Steve", "Matt", "Sarah"}} jack := john jack.friends = make([]string, len(john.friends)) copy(jack.friends, harry.friends) jack.friends = append(jay.friends, "Fred") fmt.Println(john) fmt.Println(jack) }
Read More
How to Return Lambda Functions in Golang
October 4, 2022
Go doesn’t typically have Lambda Expressions, but synonymous to Lambdas, or Closures if Anonymous Functions for Go. How to return a value from an Anonymous Function in Go package main import "fmt" func main() { var sum = func(n1, n2 int) int { sum := n1 + n2 return sum } result := sum(5, 3) fmt.Println("Sum is:", result) } How to return an Area from an Anonymous Function in Go package main import "fmt" var ( area = func(l int, b int) int { return l * b } ) func main() { fmt.
Read More
How to Create an Empty Slice in Golang
October 3, 2022
If you would like to create an empty slice in Go, then you can do the following: Option 1 – Initialize an Empty Slice in Go package main import "fmt" func main() { b := []string{} fmt.Println(b == nil) } Option 2 – Using make() package main import "fmt" func main() { c := make([]string, 0) fmt.Println(c == nil) }
Read More
How to Parallelize a for Loop in Python
October 2, 2022
If you need to run a for loop in parallel, then you can do one of the following: Option 1 – Using multiprocessing import multiprocessing def sumall(value): return sum(range(1, value + 1)) pool_obj = multiprocessing.Pool() answer = pool_obj.map(sumall,range(0,5)) print(answer) Option 2 – Using joblib module from joblib import Parallel, delayed import math def sqrt_func(i, j): time.sleep(1) return math.sqrt(i**j) Parallel(n_jobs=2)(delayed(sqrt_func)(i, j) for i in range(5) for j in range(2)) Option 3 – Using asyncio import asyncio import time def background(f): def wrapped(*args, **kwargs): return asyncio.
Read More
How to Reverse an Integer in Python
October 1, 2022
If you need to reverse an integer using Python, then you can do the following: Option 1 – Mathematical Palindrome Check original_number = 123454321 copy_number = original_number reversed_number = 0 while original_number > 0: remainder = original_number % 10 reversed_number = reversed_number * 10 + remainder original_number = original_number // 10 if copy_number == reversed_number: print(copy_number, 'is a palindrome number') else: print(copy_number, 'is not a palindrome number') Option 2 – String Reversal Number Palindrome number = 123454321 if number == int(str(number)[::-1]): print(number, 'is palindrome.
Read More
How to Save a Python Dictionary to a File in Python
September 30, 2022
If you need to save a Python Dictionary object type to a file using Python, then you can do one of the following: Option 1 – Using pickle module import pickle my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23} with open("dictionaryFile.pkl", "wb") as tf: pickle.dump(my_dict,tf) Then you can load the pickle file back as follows: import pickle with open("dictionaryFile.pkl", "wb") as tf: new_dict = pickle.load(tf) print(new_dict) Option 2 – Using numpy import numpy as np my_dict = { 'Bob': 31, 'Jane': 50, 'Harry': 13, 'Steve': 23} np.
Read More
How to Move Files From One Directory to Another Using Python
September 29, 2022
If you need to move files from one directory to another directory, using Python, then you can do one of the following: Option 1 – Using shutil.move() import shutil import os file_source = 'source/directory' file_destination = 'destination/directory' get_files = os.listdir(file_source) for file in get_files: shutil.move(file_source + file, file_destination) Option 2 – Using os.replace() import os file_source = 'source/directory' file_destination = 'destination/directory' get_files = os.listdir(file_source) for file in get_files: os.replace(file_source + file, file_destination + file) Option 3 – Using pathlib from pathlib import Path import shutil import os file_source ='source/directory' file_destination ='destination/directory' for file in Path(file_source).
Read More
How to Get the Number of Lines in a File in Python
September 28, 2022
If you need to get the number of lines in a file, or the line count total from a file, using Python, then you can use one of the following options: Option 1 – Using open() and sum() with open('directory/file.txt') as myfile: total_lines = sum(1 for line in myfile) print(total_lines) Option 2 – Using mmap import mmap with open('directory/file.txt', "r+") as myfile: mm = mmap.mmap(myfile.fileno(), 0) total_lines = 0 while mm.
Read More
How to Read Specific Lines From a File in Python
September 27, 2022
If you need to read a specific line from a file using Python, then you can use one of the following options: Option 1 – Using fileobject.readlines() If you need to read line 10: with open("file.txt") as f: data = f.readlines()[10] print(data) If you need to read lines 10, to 20: with open("file.txt") as f: data = f.readlines()[10:20] print(data) Option 2 – Using for in fileobject lines =[10, 20] data = [] i = 0 with open("file.
Read More
How to Get All Files in a Directory in Python
September 26, 2022
If you need to get all the files in a directory using Python, then you can do the following: Option 1 – Using os.listdir() import os dirPath = r"/your/directory/path/" result = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f))] print(result) Option 2 – Using os.walk() import os dirPath = r"/your/directory/path/" result = next(os.walk(dirPath))[2] print(result) Option 3 – Using glob.glob() import glob dirPathPattern = r"/your/directory/path/*.*" result = glog.glob(dirPathPattern) print(result)
Read More
[Solved] dial tcp: lookup proxy.golang.org: i/o timeout
September 25, 2022
If you get a timeout when trying to install go dependencies, the error may look something like this: $ go get github.com/aws/aws-sdk-go/aws go: module github.com/aws/aws-sdk-go/aws: Get "https://proxy.golang.org/github.com/aws/aws-sdk-go/aws/@v/list": dial tcp: lookup proxy.golang.org: i/o timeout How to Solve the Timeout Issue when installing Go Deps export GOPROXY=direct Then re-run your go get command.
Read More
How to Check Operating System in Python
September 24, 2022
If you need to check the Operating System information from Python, then you can do one of the following: Option 1 – Using the platform module import platform my_os = platform.system() print("Operating System is: ",my_os) Option 2 – Using the sys module import sys my_os=sys.platform print("Operating System is: ",my_os)
Read More
How to Convert Hex to Byte in Python
September 23, 2022
If you need to convert Hex to Byte in Python, then you can do one of the following: Option 1 – Using binascii import binascii str_val = 'This is a test'.encode('utf-8') hex_val = binascii.hexlify(str_val).decode('utf-8') print(hex_val) Option 2 – Using bytes.fromhex() hex_val = 'This is a test' print(bytes.fromhex(hex_val)) Option 3 – Using unhexlify import binascii from binascii import unhexlify str_val = 'This is a test'.encode('utf-8') hex_val = binascii.hexlify(str_val).decode('utf-8') print('String value: ', str_val.
Read More
[Solved] fatal: Could not read from remote repository with Git
September 22, 2022
If you receive the following error when trying to clone a Git repository: fatal: Could not read from remote repository. The full message may look something like this: $ git clone git@ssh.abc.xyz:org/repo.git Cloning into 'repo'... Bad owner or permissions on /Users/ao/.ssh/config fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. How to solve this error ssh-add ~/.ssh/id_rsa where id_rsa is a ssh key associated with the repo.
Read More
How to Install Homebrew on a Mac
September 21, 2022
Prerequisites You should have some familiarity with the Mac Terminal application since you’ll need to use it to install Homebrew. The Terminal application is located in the Utilities folder in the Applications folder. Dependencies. You need to install one other piece of software before you can install Homebew: Xcode. Install Apple’s Xcode development software: Xcode in the Apple App Store. Installation Overview Installing Homebrew is straightforward as long as you understand the Mac Terminal.
Read More
How to create an AWS EC2 instance in CloudFormation
September 20, 2022
Create an EC2 Instance in CloudFormation If you need to create an EC2 instance in CloudFormation, then you can do the following: AWSTemplateFormatVersion: "2010-09-09" Resources: WebInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.nano ImageId: ami-80861296 KeyName: my-key SecurityGroupIds: - sg-abc01234 SubnetId: subnet-abc01234 You can set the Instance Name as follows: AWSTemplateFormatVersion: "2010-09-09" Resources: WebInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.nano ImageId: ami-80861296 KeyName: my-key SecurityGroupIds: - sg-abc01234 SubnetId: subnet-abc01234 Tags: - Key: Name Value: webserver You can Enable Monitoring as follows:
Read More
How to Run Commands on an AWS ECS Cluster Task or Container
September 19, 2022
If you need to run a command, or set of commands on an AWS ECS cluster container, then you can do the following: aws ecs execute-command --cluster ${ClusterName} --task ${TASK_ARN} --container nginx --command "/bin/sh" --interactive
Read More
Understanding the Network Modes in AWS ECS
September 18, 2022
If using the EC2 launch type, the allowable network mode depends on the underlying EC2 instance’s operating system. If Linux, awsvpc, bridge, host and none mode can be used. If Windows, only the NAT mode is allowed. If using the Fargate launch type, the ‘awsvpc’ is the only network mode supported. Amazon ECS task networking The networking behavior of Amazon ECS tasks hosted on Amazon EC2 instances is dependent on the network mode defined in the task definition.
Read More
How to Enable ContainerInsights on AWS ECS from the AWS CLI
September 17, 2022
If you need to enable Container Insights for an ECS cluster, by using the AWS CLI, then you can do the following: aws ecs update-cluster-settings --cluster <cluster-name> --settings name=containerInsights,value=enabled --region <aws_region>
Read More
AppMesh and ECS with Imported ACM certificates on Envoy Sidecar through EFS
September 16, 2022
Summary This guide showcases the ability to use imported certificates from a third party provider (e.g. Venafi) in ACM, mount them in EFS and use them as trusted sources on Envoy sidecars with applications running in ECS. AppMesh is used as a passthrough with TLS termination occurring on the application container layer. Prerequisites and limitations Prerequisites A certificate that contains the chain of domains required for the fronted service and micro-services needed.
Read More
How to Increase the disk size on a Cloud9 instance
September 15, 2022
If you need to increase the disk size of a Cloud9 instance, you can run the following script directly from the terminal in Cloud9: pip3 install --user --upgrade boto3 export instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) python3 -c "import boto3 import os from botocore.exceptions import ClientError ec2 = boto3.client('ec2') volume_info = ec2.describe_volumes( Filters=[ { 'Name': 'attachment.instance-id', 'Values': [ os.getenv('instance_id') ] } ] ) volume_id = volume_info['Volumes'][0]['VolumeId'] try: resize = ec2.modify_volume( VolumeId=volume_id, Size=30 ) print(resize) except ClientError as e: if e.
Read More
How to Get the Instance Profile attached to an AWS EC2
September 14, 2022
If you need to get the IAM Role information from the attached EC2 role directly, you can do the following: IAM_ROLE=$(curl -s 169.254.169.254/latest/meta-data/iam/info | \ jq -r '.InstanceProfileArn' | cut -d'/' -f2)
Read More
How to Create an AWS ECR Repository in AWS CLI
September 13, 2022
If you need to create an Elastic Container Registry (ECR) Repository from the AWS CLI, you can do the following: aws ecr create-repository \ --repository-name <repo-name> \ --image-scanning-configuration scanOnPush=true \ --region ${AWS_REGION}
Read More
How to Scale Out an AWS ECS Service
September 12, 2022
When you create the Amazon ECS service, it includes three Amazon ECS task replicas. You can see this by using the describe-services command, which returns three. Use the update-service command to scale the service to five tasks. Re-run the describe-services command to see the updated five. Step 1 – Query the desired count aws ecs describe-services \ --cluster fargate-getting-started \ --services nginx-service \ --query 'services[0].desiredCount' Output: 3 Step 2 – Set the new desired count aws ecs update-service \ --cluster fargate-getting-started \ --service nginx-service \ --desired-count 5 This will now update the service to have a desired count of 5.
Read More
How to Retrieve AWS ECS Cluster Information
September 11, 2022
For more information about the Amazon ECS cluster, run the following command. You will find the number of running tasks, capacity providers, and more. aws ecs describe-clusters --cluster <your-fargate-cluster> Sample output: { "clusters": [ { "clusterArn": "arn:aws:ecs:us-east-2:123456789012:cluster/<your-fargate-cluster>", "clusterName": "fargate-getting-started", "status": "ACTIVE", "registeredContainerInstancesCount": 0, "runningTasksCount": 3, "pendingTasksCount": 0, "activeServicesCount": 1, "statistics": [], "tags": [], "settings": [], "capacityProviders": [ "FARGATE", "FARGATE_SPOT" ], "defaultCapacityProviderStrategy": [] } ], "failures": [] }
Read More
Types of communication in Amazon EKS
September 10, 2022
There are multiple types of communication in Amazon EKS environments. Lines of communication include the following: Interpod communication between containers Communication between pods on the same node or pods on different nodes Ingress connections from outside the cluster In some cases, the default Kubernetes methods are used. In other cases, specifically inter-node communication and ingress methods specific to Amazon EKS are used. Intrapod communication Containers in a pod share a Linux namespace and can communicate with each other using localhost.
Read More
[Solved] Read timeout on endpoint URL: “https://lambda.[region].amazonaws.com/2015-03-31/functions/[function-name]/invocations”
September 9, 2022
If you get the following error: Read timeout on endpoint URL: "https://lambda.<region>.amazonaws.com/2015-03-31/functions/<function-name>/invocations" Then you are probably trying to use the aws cli to invoke an AWS Lambda function and it is timing out. Other than making sure to set the Lambda execution time to something much higher than it is, you also need to make sure to specify the aws cli --cli-read-timeout argument to something that will cover the execution time.
Read More
How to Remove a Passphrase from Certificate Key
September 8, 2022
If you have a Certificate Key that includes a Passphrase and you need to remove it, potentially to use it with AWS App Mesh, then you can do the following: How to Remove a Passphrase using OpenSSL Locate the Private Key Run the following command: open ssl rsa -in <original.key> -out <new.key> Enter the original passphrase for the existing key The output file <new.key> will now be unencrypted How to Verify if the Passphrase has been removed Open the file in a text editor and check the headers.
Read More
How to get Python logger to Print to std out
September 7, 2022
If you use Python’s logger as follows: import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # or logging.INFO Perhaps you want to get it to print to Standard Output (stdout), then you can do the following: Setup Logger to print to Standard Output import logging logger = logging.getLogger() # logger.setLevel(logging.INFO) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) This way you can now log straight to the console as well:
Read More
How to Convert a String to an Integer in C
September 6, 2022
If you need to convert a String to an Integer in C, then you can do one of the following: Option 1 – Use atoi() int atoi(const char *str); You can do something like this: #include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { int value; char str[20]; strcpy(str,"123"); value = atoi(str); printf("String value = %s, Int value = %d\n", str, value); return(0); } Option 2 – Use strtol() long int strtol(const char *string, char **laststr,int basenumber);
Read More
How to Convert an Integer to a String in C
September 5, 2022
If you need to convert an Integer to a String in C, then you can do one of the following: Option 1 – Use sprintf() int sprintf(char *str, const char *format, [arg1, arg2, ... ]); You can do something like this: #include <stdio.h> int main(void) { int number; char text[20]; printf("Enter a number: "); scanf("%d", &number); sprintf(text, "%d", number); printf("\nYou have entered: %s", text); return 0; } Option 2 – Use itoa() char* itoa(int num, char * buffer, int base)
Read More
How to append to an Array in Elasticsearch using elasticsearch-py
September 4, 2022
If you are using the Official ElasticSearch Python library (Docs), and you want to create an index: doc = { "something": "123a", "somethingelse": "456b", "timestamp": datetime.now(), "history": [] } es.index(index="someindex", doc_type="somedoctype", id="someid", body=doc) You can append items to the history each time, instead of overriding them, like this: es.update(index="someindex", doc_type="somedoctype", id="someid", body={ "script" : { "source": "ctx._source.history.addAll(params.history)", "lang": "painless", "params" : { "history" : ["item1","item2"] } } }) This uses scripted updates in Elasticsearch, for appending to an array.
Read More
How to Copy Text to the Clipboard in Python
September 3, 2022
If you need to Copy Text to the Clipboard using your Python application code, then you can do the following: Option 1 – Using pyperclip First install the pyperclip package, using pip: pip install pyperclip Now you can run the following code: import pyperclip as pc a1 = "This text will now be in your clipboard" pc.copy(a1) a2 = pc.paste() print(a2) print(type(a2)) Option 2 – Using pyperclip3 This version is similar to the first option above, except it copies all the data into bytes.
Read More
How to Read a PDF file in Python
September 2, 2022
If you need to read a PDF (Portable Document Format) file in your Python code, then you can do the following: Option 1 – Using PyPDF2 from PyPDF2 import PDFFileReader temp = open('your_document.pdf', 'rb') PDF_read = PDFFileReader(temp) first_page = PDF_read.getPage(0) print(first_page.extractText()) Option 2 – Using PDFplumber import PDFplumber with PDFplumber.open("your_document.PDF") as temp: first_page = temp.pages[0] print(first_page.extract_text()) Option 3 – Using textract import textract PDF_read = textract.process('document_path.PDF', method='PDFminer')
Read More
How to Convert HEX to RBG in Python
September 1, 2022
If you need to convert HEX (Hexadecimal) to RGB (Red-Green-Blue) in your Python code, then you can do the following: Option 1 – Using the PIL library from PIL import ImageColor hex = input('Enter HEX value: ') ImageColor.getcolor(hex, "RGB") Option 2 – Using a custom solution hex = input('Enter HEX value: ').lstrip('#') print('RGB value =', tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)))
Read More
How to Refer to a Null Object in Python
August 31, 2022
If you need to refer to a Null Object in your Python code, then you can do the following. It is important to note that Python does not have a Null type, instead Python refers to not set objects or variables as None. We can use the is keyword to check if an object or variable has the type of None. object_name = None print(object_name is None) object_name = ' some_value' print(object_name is None)
Read More
How to Convert Bytearray to String in Python
August 30, 2022
If you need to convert a Bytearray to a String in Python, then you can do the following: Option 1 – Using bytes() b = bytearray("test", encoding="utf-8") str1 = bytes(b) print(str1) Option 2 – Using bytearray.decode() b = bytearray("test", encoding="utf-8") str1 = b.decode() print(str1)
Read More
How to get the Hostname in Python
August 29, 2022
If you need to get the Hostname in your Python application, then you can do the following: Option 1 – Using gethostname() import socket print(socket.gethostname()) Option 2 – Using the platform module import platform print (platform.node()) Option 3 – Using os.uname() import os hname = os.uname() print(hname)
Read More
How to get the IP Address in Python
August 28, 2022
If you need to get the IP Address in your Python application, then you can do the following: Option 1 – Using socket.gethostname() import socket print(socket.gethostbyname(socket.gethostname())) Option 2 – Using socket.getsockname() import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0]) Option 3 – Using the netifaces module from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] print(' '.join(addresses))
Read More
How to use SSH in your Python application
August 27, 2022
If you need to make an SSH connection and issues commands over SSH using your Python application, then you can do the following: Option 1 – Using the paramiko library ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute) Option 2 – Using the subprocess module subprocess.check_output(['ssh', 'my_server', 'echo /*/']) Option 3 – Using the subprocess module subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
Read More
How to Pause a Program in Python
August 26, 2022
If you need to pause the execution of your Python program, then you can do the following: Option 1 – Using time.sleep() import time time_duration = 3.5 time.sleep(time_duration) Option 2 – Using input() name = input("Please enter your name: ") print("Name:", name) Option 3 – Using os.system("pause") import os os.system("pause")
Read More
How to Convert String to Double in Python
August 25, 2022
If you need to convert a String to a Double in your Python code: Option 1 – Convert String to Double using float() string = '1234.5678' myfloat = float(string) print(myfloat) Option 2 – Convert String to Double using decimal.Decimal() from decimal import Decimal string = '1234.5678' myfloat = Decimal(string) print(myfloat)
Read More
How to a Run Bash Command in Python
August 24, 2022
If you need to run a bash command in your Python code, then you can do the following: Option 1 – Using run() from subprocess Module from subprocess import PIPE comp_process = subprocess.run("ls",stdout=PIPE, stderr=PIPE) print(comp_process.stdout) Option 2 – Using Popen() from subprocess Module from subprocess import PIPE process = subprocess.Popen("ls",stdout=PIPE, stderr=PIPE) output, error = process.communicate() print(output) process.kill
Read More
How to Force Redeployment of AWS API Gateway using AWS CloudFormation
August 23, 2022
If you have an AWS API Gateway resource, and need it to force a redeployment using CloudFormation, then you can use the TIMESTAMP trick. Example AWS CloudFormation Extract template.yaml extract: APIGatewayStage: Type: AWS::ApiGateway::Stage Properties: StageName: !Sub ${EnvironmentTagName} RestApiId: !Ref APIGateway DeploymentId: !Ref APIGatewayDeployment__TIMESTAMP__ TracingEnabled: true MethodSettings: - DataTraceEnabled: true HttpMethod: "*" LoggingLevel: INFO ResourcePath: "/*" MetricsEnabled: true APIGatewayDeployment__TIMESTAMP__: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !Ref APIGateway Description: !Sub ${EnvironmentTagName} Deployment __TIMESTAMP__ APIGateway: Type: AWS::ApiGateway::RestApi Properties: Name: !
Read More
How to Deploy React App to S3 and CloudFront
August 22, 2022
If you would like to deploy a React App to AWS S3 and AWS CloudFront, then you can follow this guide. The following solution creates a React App and deploys it to S3 and CloudFront using the client’s CLI. It also chains commands so that a React build, S3 sync and CloudFront invalidation can occur with a single command. Code available at GitHub https://github.com/ao/deploy-react-to-s3-cloudfront Target Architecture Guided Deployment Solution Create a directory for the application:
Read More
[Solved] export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’
August 21, 2022
In react-router-dom v6, Switch is replaced by routes Routes. You need to update the import from: import { Switch, Route } from "react-router-dom"; to: import { Routes, Route } from 'react-router-dom'; You also need to update the Route declaration from: <Route path="/" component={Home} /> to: <Route path='/welcome' element={<Home/>} />
Read More
How to List all Files/Folders/Directories in Python
August 20, 2022
If you need to list all Files, Folders, or Directories in Python code, then you can use the listdirs method from the os package. import os print(os.listdir("/path/to/directory/")
Read More
How to Read a File in Python
August 19, 2022
If you need to read a file in Python, then you can use the open() built-in function to help you. Let’s say that you have a file called somefile.txt with the following contents: Hello, this is a test file With some contents How to Open a File and Read it in Python We can read the contents of this file as follows: f = open("somefile.txt", "r") print(f.read()) This will print out the contents of the file.
Read More
How to Drop Columns in Pandas Only If Exists
August 18, 2022
If you have a Pandas DataFrame, and want to only drop columns if they exist, then you can do the following: Add parameter errors to DataFrame.drop: errors : {‘ignore', ‘raise'}, default ‘raise' If ‘ignore', suppress error and only existing labels are dropped. df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore') An example of how to Ignore Errors with .drop() df = pd.DataFrame({'row_num':[1,2], 'w':[3,4]}) df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore') print (df) w 0 3 1 4
Read More
[Solved] An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult:
August 17, 2022
If you are running a GlueJob in AWS and get the following error: An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult: Then you need to view the CloudWatch logs to help you pinpoint where the problem is occuring. How to solve the Exception thrown in awaitResult It’s highly likely that the issue is in an expired IAM Role. When a Role is created in IAM, the default maximum session duration is set to 1 hour.
Read More
AWS CDK Commands
August 16, 2022
The AWS Cloud Development Kit (CDK) comes with a list of commands that you need to know: cdk list (ls) Lists the stacks in the app cdk synthesize (synth) Synthesizes and prints the CloudFormation template for the specified stack(s) cdk bootstrap Deploys the CDK Toolkit staging stack; see Bootstrapping cdk deploy Deploys the specified stack(s) cdk destroy Destroys the specified stack(s) cdk diff Compares the specified stack with the deployed stack or a local CloudFormation template cdk metadata Displays metadata about the specified stack cdk init Creates a new CDK project in the current directory from a specified template cdk context Manages cached context values cdk docs (doc) Opens the CDK API reference in your browser cdk doctor Checks your CDK project for potential problems You can learn more about the CDK here: https://docs.
Read More
How to Make a Java Jar File Executable
August 15, 2022
Let’s say you have a Java project as follows: package ms.ao.something; public class MyProject { public static void main(String...args) throws Exception { System.out.println("Hello world!"); } } Now you want to build this and make it a self contained executable Jar. If you do a mvn clean install or mvn clean package, and try and run it as follows: java -jar target/my-java-1.0-SNAPSHOT.jar You will get the following error: no main manifest attribute, in target/my-java-1.
Read More
How to List All Resources in an AWS Account
August 14, 2022
If you need to see a list of all the resources in your AWS Account, then you need to look into the Tag Editor. Step 1 – Tag Editor Search for Tag Editor in the navigation search at the top of the AWS Console. Select the Resource Groups & Tag Editor. Step 2 – Find Resources From the left hand menu, select Tag Editor Step 3 – Filter your Search Requirements From the Regions drop down, select All regions and then select All supported resource types from the Resource types drop down.
Read More
Fixed size left column and fluid right column both with 100% height in CSS
August 13, 2022
If you need two (2) columns and want the left column to be a fixed size, but the right column to automatically take the remaining size of the window, then you can use the following solution. Follow the steps below, which include some CSS and some HTML. The CSS for our solution html, body { height: 100%; width: 100%; padding: 0; margin: 0; } .page-wrapper { height: 100%; position: relative; } .
Read More
How to Check if a Volume is Mounted in Bash
August 12, 2022
If you need to check if a volume is mounted in a Bash script, then you can do the following. How to Check Mounted Volumes First we need to determine the command that will be able to check. This can be done with the /proc/mounts path. How to Check if a Volume is Mounted in Bash if grep -qs '/mnt/foo ' /proc/mounts; then echo "It's mounted." else echo "It's not mounted.
Read More
How to Determine if a Bash Variable is Empty
August 11, 2022
If you need to check if a bash variable is empty, or unset, then you can use the following code: if [ -z "${VAR}" ]; The above code will check if a variable called VAR is set, or empty. What does this mean? Unset means that the variable has not been set. Empty means that the variable is set with an empty value of "". What is the inverse of -z?
Read More
How to Order by File Size using the du command in Linux
August 10, 2022
If you use the du command to list all the file sizes on Linux: du # or du -h # Human readable Then you would have noticed that they are not ordered by file size. Instead you can pass that result to the sort command as follows: du -h | sort -h
Read More
How to Join Multiple MySQL Tables in Python
August 9, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . Presenting the data let’s take two (2) tables as a demonstration for the code below. Users – Table 1 { id: 1, name: 'Carl', fav: 254}, { id: 2, name: 'Emma', fav: 254}, { id: 3, name: 'John', fav: 255}, { id: 4, name: 'Hayley', fav:}, { id: 5, name: 'Andrew', fav:} Products – Table 2
Read More
How to Limit a MySQL Query in Python
August 8, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Limit the Result Returned from MySQL in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers LIMIT 10") myresult = mycursor.fetchall() for x in myresult: print(x) How to Start From Another Position in MySQL from Python import mysql.
Read More
How to Update a MySQL Table in Python
August 7, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Update a MySQL Table in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = 'Stoneleigh Place' WHERE address = 'Abbey Road'" mycursor.execute(sql) mydb.
Read More
How to Drop a MySQL Table in Python
August 6, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Delete/Drop a MySQL Table in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "DROP TABLE customers" mycursor.execute(sql) How to Delete/Drop Only if MySQL Table Exists in Python import mysql.
Read More
How to Delete MySQL Records in Python
August 5, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Delete MySQL Records in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "DELETE FROM customers WHERE address = 'The Rockies'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted") Prevent SQL Injection in MySQL queries through Python Specify the injected variable as the second argument to the execute command as below.
Read More
How to ORDER BY a MySQL Query in Python
August 4, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Sort the Result of a MySQL Query in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers ORDER BY name" mycursor.execute(sql) myresult = mycursor.
Read More
How to Filter WHERE MySQL Queries in Python
August 3, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Select from MySQL with a Filter in Python You simply specify the WHERE clause in your SQL statement as follows: import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address ='London Road'" mycursor.
Read More
How to Select From MySQL in Python
August 2, 2022
First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python . How to Select From a MySQL Table in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x) How to Select Columns From a MySQL Table in Python import mysql.
Read More
How to Insert into a MySQL Table in Python
August 1, 2022
If you need to insert data into a MySQL table using Python, then look no further. If you need to first learn about the mysql.connector and how to get this up and running, first take a look at the How to Install MySQL Driver in Python post before continuing. How do Insert into a MySQL Table in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.
Read More
How to Create a Primary Key for a MySQL Database in Python
July 31, 2022
You can create a Primary Key for your MySQL database in Python as follows. First, you need to know if the Primary Key already exists. Option 1 – The Primary Key does not Exist import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))") Option 2 – The Primary Key already Exists import mysql.
Read More
How to Create a MySQL Table in Python
July 30, 2022
If you need to create a table in a MySQL database using Python, then you can do the following. How to Create a MySQL Table in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE people (name VARCHAR(255), address VARCHAR(255))") How to Check if a MySQL Table Exists in Python import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.
Read More
How to Create a MySQL Database in Python
July 29, 2022
In order to create a MySQL database in Python, you first need to initiate a connection using the mysql.connector. You can learn about how to create a connection to MySQL here . How to Create a Database in Python Creating a database is simple. First, make sure you have an active connection to your database, and then set a cursor. Once you have this, issue the execute command to create your database.
Read More
How to Install MySQL Driver in Python
July 28, 2022
To begin using MySQL in Python, you need to do the following: Step 1 – Install the MySQL Connector Using pip, we can install the MySQL Connector package: python -m pip install mysql-connector-python Step 2 – Test the MySQL Connector Create a Python file and import the new package: import mysql.connector Step 3 – Create a Connection to the MySQL Database Now you can create a connection to your MySQL database.
Read More
How to Resize an AWS EBS Volume in Bash
July 27, 2022
If you need to resize an EBS volume in AWS, you can do so using bash. Step 1 – Create a bash file Create a bash file called resize.sh: #!/bin/bash SIZE=${1:-20} INSTANCEID=$(curl http://169.254.169.254/latest/meta-data/instance-id) REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/\(.*\)[a-z]/\1/') VOLUMEID=$(aws ec2 describe-instances \ --instance-id $INSTANCEID \ --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" \ --output text \ --region $REGION) aws ec2 modify-volume --volume-id $VOLUMEID --size $SIZE while [ \ "$(aws ec2 describe-volumes-modifications \ --volume-id $VOLUMEID \ --filters Name=modification-state,Values="optimizing","completed" \ --query "length(VolumesModifications)"\ --output text)" !
Read More
How to get all checked checkboxes in Javascript
July 26, 2022
If you need to get all the checked checkboxes using Javascript, then you can do the following: Option 1 – In a single line const checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked'); Option 2 – Another one liner const data = [...document.querySelectorAll('.mycheckboxes:checked')].map(e => e.value); Option 3 – Create a helper function function getCheckedBoxes(checkboxName) { var checkboxes = document.getElementsByName(checkboxName); var checkboxesChecked = []; for (var i=0; i<checkboxes.length; i++) { if (checkboxes[i].checked) checkboxesChecked.push(checkboxes[i]); } } return checkboxesChecked.
Read More
How to Setup Credential Helper for AWS CodeCommit
July 25, 2022
AWS CodeCommit is a git code repository service by Amazon Web Services. You will want to clone your repository and setup your remotes using credential helper. Step 1 – Setup Credential Helper git config --global credential.helper '!aws codecommit credential-helper $@' git config --global credential.UseHttpPath true This will write to your local user’s ~/.gitconfig, and the file will look something like: [credential] helper = !aws --profile CodeCommitProfile codecommit credential-helper $@ UseHttpPath = true You can edit this file by running the following git command:
Read More
How to Flex Grid 2 Columns using CSS
July 24, 2022
If you would like to flex grid 2 columns in CSS then you need three (3) divs. Step 1 – Set your HTML template Create some HTML with this layout. <div class="Parent"> <div class="child1"> <h1>Left</h1> </div> <div class="child2"> <h1>RIGHT</h1> </div> </div> Step 2 – Container Div Create a Parent div that uses the Flexbox display model. .Parent { display: flex; flex-direction: row; } Step 3 – Child Divs Create two (2) divs that are both 50% of the parent container.
Read More
How to Create a Hashtag Generator in Javascript
July 23, 2022
If you want to create a hashtag generator in Javascript, then you can do the following: function generateHashtag(string) { if (string.trim() === '') return false; const stringWithCamelCase = string .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(''); const stringWithHashtag = `#${stringWithCamelCase.trim()}`; return stringWithHashtag.length > 140 ? false : stringWithHashtag; } How to use the Hashtag Generator const hashtag = generateHashtag("My New Hashtag !") console.log(hashtag); // #MyNewHashtag!
Read More
How to Confirm before Leaving Page in Javascript
July 22, 2022
You can implement a function to be called before the user leaves a page with Javascript as follows: window.onbeforeunload = function(e) { return "Do you want to exit this page?"; }; This is a typically solution for when you want the user to confirm their changes are saved before allowing them to close the current page in editing tools.
Read More
What are the multiples of 3 from 1 to 1000
July 21, 2022
If you need to calculate the multiples of 3, starting from 1 up until 1000, then you can use the following code: n = 1 v = [] while n <= 1000: v.append(n) n = n + 3 This will generate the list of numbers which are the multiples of 3 from 1 to 1000: 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 154, 157, 160, 163, 166, 169, 172, 175, 178, 181, 184, 187, 190, 193, 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388, 391, 394, 397, 400, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 439, 442, 445, 448, 451, 454, 457, 460, 463, 466, 469, 472, 475, 478, 481, 484, 487, 490, 493, 496, 499, 502, 505, 508, 511, 514, 517, 520, 523, 526, 529, 532, 535, 538, 541, 544, 547, 550, 553, 556, 559, 562, 565, 568, 571, 574, 577, 580, 583, 586, 589, 592, 595, 598, 601, 604, 607, 610, 613, 616, 619, 622, 625, 628, 631, 634, 637, 640, 643, 646, 649, 652, 655, 658, 661, 664, 667, 670, 673, 676, 679, 682, 685, 688, 691, 694, 697, 700, 703, 706, 709, 712, 715, 718, 721, 724, 727, 730, 733, 736, 739, 742, 745, 748, 751, 754, 757, 760, 763, 766, 769, 772, 775, 778, 781, 784, 787, 790, 793, 796, 799, 802, 805, 808, 811, 814, 817, 820, 823, 826, 829, 832, 835, 838, 841, 844, 847, 850, 853, 856, 859, 862, 865, 868, 871, 874, 877, 880, 883, 886, 889, 892, 895, 898, 901, 904, 907, 910, 913, 916, 919, 922, 925, 928, 931, 934, 937, 940, 943, 946, 949, 952, 955, 958, 961, 964, 967, 970, 973, 976, 979, 982, 985, 988, 991, 994, 997, 1000
Read More
How to Count Files in Directory on Linux
July 20, 2022
If you need to count how many files are in a directory on Linux, then you can use a combination of the ls command to list all the files, and the wc command to count how many lines are printed: Option 1 – Using wc ls | wc -l You can specify a directory as follows: ls <directory> | wc -l Option 2 – Using find You can count files recursively by using the find command:
Read More
How to Read a File Line by Line in Java
July 19, 2022
If you need to read a file line by line in Java, then you can use one of the following three (3) options. Option 1 You can use the FileReader and BufferedReader packages as follows: File file = new File("./your/file.txt"); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } Option 2 You can also read the lines using Files and Paths as follows:
Read More
How can I clear or empty a StringBuilder
July 18, 2022
You can use Java’s StringBuilder to create and manipulate Strings as follows: StringBuilder sb = new StringBuilder(); sb.append("Some").append(" ").append("String"); System.out.println(sb.toString()); // "Some String" The following three (3) options allow you to clear or empty a StringBuilder. Option 1 – using setLength sb.setLength(0); Option 2 – reinstantiating sb = new StringBuilder(); Option 3 – using delete sb.delete(0, sb.length());
Read More
How to Approve a SageMaker model in AWS CLI
July 17, 2022
Sometimes you will need to manually approve a SageMaker model package from the AWS CLI. Step 1 – Get a list of the available packages aws sagemaker list-model-packages --model-package-group-name "the-model-package-group" This will produce the following output: { "ModelPackageSummaryList": [ { "ModelPackageGroupName": "...", "ModelPackageVersion": "...", "ModelPackageArn": "the-arn-we-will-use-below", "ModelPackageDescription": "...", "CreationTime": "...", "ModelPackageStatus": "Completed", "ModelApprovalStatus": "PendingManualApproval" }, ... ] } Step 2 – Approve the model aws sagemaker update-model-package --model-package-arn <ARN-FROM-ABOVE> --model-approval-status Approved
Read More
How to Assume Role across Accounts in AWS
July 16, 2022
If you need to assume role between AWS accounts, or allow an account to assume a role and use resources in another AWS account, then you need to create a role and attach the following policy. The following two (2) steps creates a Trust Relationship between the accounts. Step 1 – In the Source Account { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": [ "arn:aws:iam::DESTINATION-ACCOUNT-ID:role/DESTINATION-ROLENAME" ] }] } Step 2 – In the Destination Account { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::SOURCE-ACCOUNT-ID:role/SOURCE-USERNAME" }, "Action": "sts:AssumeRole" }] }
Read More
How to Style an Element using Javascript
July 15, 2022
If you need to style an element using Javascript then you can use the style object to support all your CSS needs. <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").style.color = "red"; </script> <p>The paragraph above was changed by a script.</p> </body> </html> If you need to do this purely in a Javascript file itself, then: // Get a reference to the element var myElement = document.querySelector("#p1"); // Now you can update the CSS attributes myElement.
Read More
How to Wait 1 Second in Javascript
July 14, 2022
If you need your Javascript code to wait one (1) second (or more) while executing, then there are a couple of ways to achieve this. Option 1 – Creating a delay Promise function delay(time) { return new Promise(resolve => setTimeout(resolve, time)); } delay(1000).then(() => console.log('ran after 1 second elapsed')); Option 2 – Using setTimeout setTimeout(function(){ console.log("Ready") }, 1000); Option 3 – Using an async Promise async function test() { console.log('start timer'); await new Promise(resolve => setTimeout(resolve, 1000)); console.
Read More
How to use forEach method in Javascript
July 13, 2022
Arrays come with a useful forEach function that allows you to loop through the array. var colors = ['red', 'blue', 'green']; colors.forEach(function(color) { console.log(color); }); // red // blue // green You can also get the index in each loop as follows: const colors = ['red', 'blue', 'green']; colors.forEach((item, index)=>{ console.log(index, item) }); // 0 'red' // 1 'blue' // 2 'green'
Read More
How to Remove an Element from an Array in Javascript
July 12, 2022
If you need to remove an element from an array in Javascript, then you can use one of the following five (5) options: Option 1 – Use splice to remove an element Example 1 using splice: var colors = ["red","blue","car","green"]; var carIndex = colors.indexOf("car"); colors.splice(carIndex, 1); // colors = ["red","blue","green"] Example 2 using splice: var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // Remove Sunday -- index 0 and Monday -- index 1 myArray.
Read More
How to get the Alphabet as Array in Javascript
July 11, 2022
If you need to get an array of alphabetical letters in Javascript then you can use one of the following: Option 1 – Explicitly define the array first const alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; Option 2 – Split a string of alphabetical characters const alphabetArray = "abcdefghijklmnopqrstuvwxyz".split(""); Option 3 – Split a string and UpperCase characters const alphabetArrayUp = toUpperCase("abcdefghijklmnopqrstuvwxyz").split("");
Read More
The Power of Two (2) Table
July 10, 2022
With the Power of Two, you can ask the following: How do you find the powers of 2? What does the power of 2 stand for? How much is the power of 2? The Power of Two (2) Table (Powers of Two) Power Value 1 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1,024 11 2,048 12 4,096 13 8,192 14 16,384 15 32,768 16 65,536 17 131,072 18 262,144 19 524,288 20 1,048,576 21 2,097,152 22 4,194,304 23 8,388,608 24 16,777,216 25 33,554,432 26 67,108,864 27 134,217,728 28 268,435,456 29 536,870,912 30 1,073,741,824 31 2,147,483,648 32 4,294,967,296 33 8,589,934,592 34 17,179,869,184 35 34,359,738,368 36 68,719,476,736 37 137,438,953,472 38 274,877,906,944 39 549,755,813,888 40 1,099,511,627,776 41 2,199,023,255,552 42 4,398,046,511,104 43 8,796,093,022,208 44 17,592,186,044,416 45 35,184,372,088,832 46 70,368,744,177,664 47 140,737,488,355,328 48 281,474,976,710,656 49 562,949,953,421,312 50 1,125,899,906,842,624 51 2,251,799,813,685,248 52 4,503,599,627,370,496 53 9,007,199,254,740,992 54 18,014,398,509,481,984 55 36,028,797,018,963,968 56 72,057,594,037,927,936 57 144,115,188,075,855,872 58 288,230,376,151,711,744 59 576,460,752,303,423,488 60 1,152,921,504,606,846,976 61 2,305,843,009,213,693,952 62 4,611,686,018,427,387,904 63 9,223,372,036,854,775,808 64 18,446,744,073,709,551,616 65 36,893,488,147,419,103,232 66 73,786,976,294,838,206,464 67 147,573,952,589,676,412,928 68 295,147,905,179,352,825,856 69 590,295,810,358,705,651,712 70 1,180,591,620,717,411,303,424 71 2,361,183,241,434,822,606,848 72 4,722,366,482,869,645,213,696 73 9,444,732,965,739,290,427,392 74 18,889,465,931,478,580,854,784 75 37,778,931,862,957,161,709,568 76 75,557,863,725,914,323,419,136 77 151,115,727,451,828,646,838,272 78 302,231,454,903,657,293,676,544 79 604,462,909,807,314,587,353,088 80 1,208,925,819,614,629,174,706,176 81 2,417,851,639,229,258,349,412,352 82 4,835,703,278,458,516,698,824,704 83 9,671,406,556,917,033,397,649,408 84 19,342,813,113,834,066,795,298,816 85 38,685,626,227,668,133,590,597,632 86 77,371,252,455,336,267,181,195,264 87 154,742,504,910,672,534,362,390,528 88 309,485,009,821,345,068,724,781,056 89 618,970,019,642,690,137,449,562,112 90 1,237,940,039,285,380,274,899,124,224 91 2,475,880,078,570,760,549,798,248,448 92 4,951,760,157,141,521,099,596,496,896 93 9,903,520,314,283,042,199,192,993,792 94 19,807,040,628,566,084,398,385,987,584 95 39,614,081,257,132,168,796,771,975,168 96 79,228,162,514,264,337,593,543,950,336 97 158,456,325,028,528,675,187,087,900,672 98 316,912,650,057,057,350,374,175,801,344 99 633,825,300,114,114,700,748,351,602,688 100 1,267,650,600,228,229,401,496,703,205,376 The Power of Two (2) Tables from 1 to 100 Below you will find the Power of Two (2) tables from 1 to 100.
Read More
How to get the Screen Width in Javascript
July 9, 2022
Javascript gives a few options to determine the screen width. When we say screen, we mean the browser window’s width itself. Option 1 – Using Native Javascript Using native Javascript objects, we can find the innerWidth and innerHeight: var w = window.innerWidth; var h = window.innerHeight; The window object also allows for: window.screen.width // or simply screen.width We can write some code to tell us the width and height with fallbacks:
Read More
How to Read a File in Rust
July 8, 2022
If you need to read a file in Rust, then you can use the fs package from the standard library: use std::fs; fn main() { let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); println!("With text:\n{}", contents); }
Read More
How to Convert Array to String in Java
July 7, 2022
If you need to convert an array to a string in Java, then you could look at a solution like this: String stringArray[] = {"Hello ", " world", " this", " is", " a", " test"}; StringBuffer sb = new StringBuffer(); for(int i = 0; i < stringArray.length; i++) { sb.append(stringArray[i]); } String str = sb.toString(); System.out.println(str); Or you could do something simple like this: String str = String.join(",", arr);
Read More
How to Join Two Strings Together in Golang
July 6, 2022
If you need to join two (2) strings together in Golang, you can do the following, using the + concatenation operator: package main import ( "fmt") func main() { message1 := "Join Strings" message2 := "Together" result := message1 + " " + message2 fmt.Println(result) }
Read More
How to Recursively Delete all Files in an AWS S3 Bucket
July 5, 2022
If you need to recursively delete all files in an AWS S3 bucket, then you can do the following: aws s3 rm --recursive s3://your-bucket-name/foo/bar/ If you only want to delete an specific object from AWS S3: aws s3 rm s3://your-bucket-name/foo/bar/item.txt
Read More
How to Execute Linux Commands in Golang
July 4, 2022
If you want to execute linux commands in Golang, then you can use exec.Command: cmd := exec.Command("echo", "hello world") res, _ := cmd.CombinedOutput() fmt.Println(string(res))
Read More
How to Check for Prime Numbers using Golang
July 3, 2022
If you need to check for Prime Numbers in Golang, then you can use the following method: const n = 1212121 if big.NewInt(n).ProbablyPrime(0) { fmt.Println(n, "is prime") } else { fmt.Println(n, "is not prime") }
Read More
How to Raise a Number to a Power in Golang
July 2, 2022
If you need to raise a number to a power in Golang, then you can use the math.Pow function: package main import ( "math" ) func main() { var exponent, base float64 output := math.Pow(base, exponent) }
Read More
How to get CPU Frequency in Linux
July 1, 2022
If you need to get the CPU Frequency in Linux, then you can run the following command: watch -n.1 "grep \"^[c]pu MHz\" /proc/cpuinfo"
Read More
How to Disable Warning with Python Pandas
June 30, 2022
How can python pandas disable warnings? If you need to disable warnings with Pandas on Python, then you can use the warnings module and ignore the filter as follows: import warnings warnings.filterwarnings('ignore')
Read More
How to Get all Caps Alphabet as List in Python
June 29, 2022
If we take the following list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] How do we extract only the UpperCase letters of a given word? How to get only the Capital Letters from a String word = 'AbcDefgHijkL' result = re.findall('([A-Z])', word) print(result) # ['A', 'D', 'H', 'L']
Read More
[Solved] Error creating RDS DB Instance: IAM role ARN value is not value or does not include the required permissions for: ENHANCED_MONITORING
June 28, 2022
When you are trying to create an RDS database and you get the dreaded error message: IAM role ARN value is invalid or does not include the required permissions for: ENHANCED_MONITORING Then you need to make sure that you are assuming the correct service principle: monitoring.rds.amazonaws.com Your code should look something like this: { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "cloudwatch.amazonaws.com" } }, { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "monitoring.
Read More
How to create an AWS Lambda in Terraform
June 27, 2022
Step 1 – Lambda Code in Python The following code expects a python file with the contents as follows in a file called python/script1.py: def lambda_handler(event, context): return { 'code': 200, 'message': 'Triggered' } Step 2 – Lambda Code in Terraform Now we create the lambda.tf: data "archive_file" "zip_python_code_create" { type = "zip" source_file = "python/script1.py" output_path = "python/script1.zip" } resource "aws_lambda_function" "lambda_script1" { filename = "python/script1.zip" function_name = "LambdaScript1" role = aws_iam_role.
Read More
[Solved] Instance Profile already exists in Terraform
June 26, 2022
If you get the Instance Profile already exists error when running your Terraform apply, then it is either because an instance profile with that name already existed in the account, or because the previous terraform destroy did not remove it. Step 1 – Identify the Instance Profiles in the account aws iam list-instance-profiles Step 2 – Delete the Instance Profile/s aws iam delete-instance-profile --instance-profile-name <name-of-instance-profile>
Read More
[Solved] An error occurred (UnauthorizedException) when calling ListAccounts operation: Session token not found or invalid
June 25, 2022
If you are using aws configure sso to populate your ~/.aws/credentials file and you get the following error when you try and reauthorize, then you can solve this problem as follows: An error occurred (UnauthorizedException) when calling ListAccounts operation: Session token not found or invalid Step 1 – Logout from SSO aws sso logout Step 2 – Reconfigure SSO with previous defaults aws configure sso
Read More
How to Match Multiple Strings with grep
June 24, 2022
If you need to match a string in a file, then grep is your friend. An example of using grep Let’s take a file called somefile.txt this is a test that looks for something We can look for the string something in this file using grep: cat somefile.txt | grep something # something But what if we want to look for both something and this? An example of using multiple greps It’s pretty easy, we just pass the -E flag, which is short for --extended-regexp, and separate our strings with a pipe |.
Read More
How to Invoke an AWS Lambda from the CLI
June 23, 2022
If you want to invoke an AWS Lambda from your CLI, then the best option is to have the AWS CLI installed. Getting started with the AWS CLI – AWS Command Line Interface (amazon.com) Once this is installed, you can invoke Lambdas as follows: Setting your AWS Region It is recommended to always set your AWS region in an environment variable called AWS_REGION export AWS_REGION=eu-west-1 Option 1 – Recommended with AWS CLI v2 aws lambda invoke --function-name YourFunction --region ${AWS_REGION} --cli-binary-format raw-in-base64-out --payload '{"keyName":"keyValue"}' response.
Read More
How to Exit if a Bash Variable in Not Set
June 22, 2022
Sometimes you might want to exit a command if a variable is not set in Bash. You can do this as follows: if [ -z "$VARIABLE_NAME" ]; then echo "VARIABLE_NAME is not set"; exit 1; fi
Read More
How to Force Gitlab pipeline to fail on condition
June 21, 2022
if you have a conditional in your Gitlab pipeline stage that checks if something has succeeded or failed, then you can use this to pass or fail your pipeline stage. Option 1 – Fail on String Found if cat log.txt | grep "Failure Summary" ; then exit 1 ; else exit 0 ; fi This will fail the pipeline if it find a string matching Failure Summary in a file called log.
Read More
How to run AWS CLI commands based on AWS CLI Version in Bash
June 20, 2022
If you find yourself having the requirements to support both AWS CLI v1 and v2 simultaneously, then you can use the following conditional in Bash to only run the specific version required: AWS_VERSION=$(aws --version | gawk '{print $1}' | gawk -F/ '{print $2}' | gawk -F. '{print $1}') if [ AWS_VERSION == "1" ] then aws lambda invoke --function-name YourFunction --payload $(echo '{"k":"v"}') response.json else aws lambda invoke --function-name YourFunction --cli-binary-format raw-in-base64-out --payload '{"k":"v"}' response.
Read More
[Solved] Unknown options: –cli-binary-format AWS CLI
June 19, 2022
If you have tried calling the AWS CLI and got the following error: Unknown options: --cli-binary-format Then it is because you are using the AWS CLI v1 and should be using the newer AWS CLI v2. Another error that you will see along with this is: An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Could not parse payload into json: Unrecognized token 'eyJwYXRoIjoiJEdMAAAAIgfQo': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') An example that fails on AWS CLI v1 aws lambda invoke --function-name YourFunction --cli-binary-format raw-in-base64-out --payload '{"yourKey":"yourValue"}' How to fix this error on AWS CLI v1 aws lambda invoke --function-name YourFunction --region eu-west-1 --payload '{"yourKey":"yourValue"}' response.
Read More
How to Generate Random Strings with Dash in-between in Python
June 18, 2022
If you need to generate a random string that looks something like this: VUNBXJ-230411, then you can use the following random generator: import random, string def generate_random_string_with_dash(): rand = "{0}-{1}".format(''.join(random.choice(string.ascii_uppercase) for x in range(6)), ''.join(random.choice(string.digits) for x in range(6))) return rand You simply call the above as follows: print( generate_random_string_with_dash() ) # JJXFNS-420809 If you need to adjust the length of string A and B, then you can change the value in the range above from something other than 6.
Read More
How to Check OS version and flavor in Linux
June 17, 2022
If you need to check the version and flavour of the running Linux instance, then you can try the below commands: cat /etc/os-release lsb_release -a hostnamectl
Read More
How to use a Backend-Config File for Terraform S3 State Configuration
June 16, 2022
If you are using S3 as the backend for your state management in Terraform, then you can create environment specific configuration files where you store the bucket, region among other things to be pulled in automatically when switching environments. Step 1 – Create environment specific configs Create a dev.conf file with the following content: bucket = "your-bucket" region = "your-aws-region" key = "path/to/key" Step 2 – Set the terraform backend In your main.
Read More
How to Refresh State in Terraform
June 15, 2022
Sometimes your infrastructure may be out of sync with your Terraform state because resources may have been amended or deleted manually. For this you can refresh the Terraform state. Using the refresh command terraform refresh [options] Why this command may appear strange at first, not that it is merely an alias for: terraform apply -refresh-only -auto-approve If you don’t want to auto-approve the transaction, then you can perform a refresh as follows:
Read More
How to get the Length of an Array in C
June 14, 2022
There isn’t really a standard way to get the length of array in C. This means you need to do some additional work to achieve getting the length of an array when using C. Creating and Looping through an Array in C Usually you would create an array as follows: int items[5] = {1, 2, 3, 4, 5}; You could always define the size right off the bat: const int SIZE = 5; int items[SIZE] = {1, 2, 3, 4, 5}; This way if you need to loop through the array later on, you can use your SIZE variable.
Read More
How to write If/Else Statements in Terraform
June 13, 2022
If/Else statements are conditional statements that perform decisions based on some known state, or variable. Terraform allows you to perform these if/else statements using a ternary operation which have become popular as short-form if/else statements in many programming languages. Where a language would write something similar to: let truthy = false if (something == "value") { truthy = true } else { truthy = false } The ternary alternative would be:
Read More
How to Reset Udemy Progress
June 12, 2022
If you need to redo a Udemy course and you would like to reset the course’s progress, then you can use the following Javascript snippet below. You have to do this manually because Udemy does not provide native functionality to do this. Step 1 – Navigate to Udemy in a web browser Make sure you are on the course content page you would like to reset. Step 2 – Open up the developer tools You will need to run a Javascript snippet, so press the following keyboard shortcuts, or right-click and select Inspect:
Read More
How to Get Last Digit of a Large Number in C
June 11, 2022
The challenge Define a function that takes in two non-negative integers aa_a_ and bb_b_ and returns the last decimal digit of aba^b_a__b_. Note that aa_a_ and bb_b_ may be very large! For example, the last decimal digit of 979^797 is 999, since 97=47829699^7 = 478296997=4782969. The last decimal digit of (2200)2300({2^{200}})^{2^{300}}(2200)2300, which has over 109210^{92}1092 decimal digits, is 666. Also, please take 000^000 to be 111. You may assume that the input will always be valid.
Read More
[Solved] Network interface is in use by another service in AWS
June 10, 2022
If you have tried to delete a Security Group, or VPC, or various other resources and you get the dreaded Network interface is in use by another service error, then you can resolve this by deleting the resource through the API. How to delete the Network Interface (ENI) aws ec2 delete-network-interface --network-interface-id eni-xxxxx Replace the eni-xxxxx with the ENI id that you are struggling to delete. How to find what services are using the ENI #!
Read More
How to Uninstall npm packages
June 9, 2022
We typically install an npm package as follows: npm install <package_name> But how do we uninstall an npm package? How to uninstall an npm package This will uninstall an npm package that was installed in your project. Just make sure to run the command from the root directory of your project. npm uninstall <package_name> This will remove the package from the node_modules directory and will also remove the reference to it from the package.
Read More
RBG Color Codes
June 8, 2022
Often you need to reference an HTML/CSS Color Code in RGB or Hex. This is known as rgb color codes. Below is an easy-to-use table to find the appropriate RGB and Hex Color Codes. Color Name #RRGGBB (Hex Code) R,G,B (Decimal code) maroon #800000 (128,0,0) dark red #8B0000 (139,0,0) brown #A52A2A (165,42,42) firebrick #B22222 (178,34,34) crimson #DC143C (220,20,60) red #FF0000 (255,0,0) tomato #FF6347 (255,99,71) coral #FF7F50 (255,127,80) indian red #CD5C5C (205,92,92) light coral #F08080 (240,128,128) dark salmon #E9967A (233,150,122) salmon #FA8072 (250,128,114) light salmon #FFA07A (255,160,122) orange red #FF4500 (255,69,0) dark orange #FF8C00 (255,140,0) orange #FFA500 (255,165,0) gold #FFD700 (255,215,0) dark golden rod #B8860B (184,134,11) golden rod #DAA520 (218,165,32) pale golden rod #EEE8AA (238,232,170) dark khaki #BDB76B (189,183,107) khaki #F0E68C (240,230,140) olive #808000 (128,128,0) yellow #FFFF00 (255,255,0) yellow green #9ACD32 (154,205,50) dark olive green #556B2F (85,107,47) olive drab #6B8E23 (107,142,35) lawn green #7CFC00 (124,252,0) chart reuse #7FFF00 (127,255,0) green yellow #ADFF2F (173,255,47) dark green #006400 (0,100,0) green #008000 (0,128,0) forest green #228B22 (34,139,34) lime #00FF00 (0,255,0) lime green #32CD32 (50,205,50) light green #90EE90 (144,238,144) pale green #98FB98 (152,251,152) dark sea green #8FBC8F (143,188,143) medium spring green #00FA9A (0,250,154) spring green #00FF7F (0,255,127) sea green #2E8B57 (46,139,87) medium aqua marine #66CDAA (102,205,170) medium sea green #3CB371 (60,179,113) light sea green #20B2AA (32,178,170) dark slate gray #2F4F4F (47,79,79) teal #008080 (0,128,128) dark cyan #008B8B (0,139,139) aqua #00FFFF (0,255,255) cyan #00FFFF (0,255,255) light cyan #E0FFFF (224,255,255) dark turquoise #00CED1 (0,206,209) turquoise #40E0D0 (64,224,208) medium turquoise #48D1CC (72,209,204) pale turquoise #AFEEEE (175,238,238) aqua marine #7FFFD4 (127,255,212) powder blue #B0E0E6 (176,224,230) cadet blue #5F9EA0 (95,158,160) steel blue #4682B4 (70,130,180) corn flower blue #6495ED (100,149,237) deep sky blue #00BFFF (0,191,255) dodger blue #1E90FF (30,144,255) light blue #ADD8E6 (173,216,230) sky blue #87CEEB (135,206,235) light sky blue #87CEFA (135,206,250) midnight blue #191970 (25,25,112) navy #000080 (0,0,128) dark blue #00008B (0,0,139) medium blue #0000CD (0,0,205) blue #0000FF (0,0,255) royal blue #4169E1 (65,105,225) blue violet #8A2BE2 (138,43,226) indigo #4B0082 (75,0,130) dark slate blue #483D8B (72,61,139) slate blue #6A5ACD (106,90,205) medium slate blue #7B68EE (123,104,238) medium purple #9370DB (147,112,219) dark magenta #8B008B (139,0,139) dark violet #9400D3 (148,0,211) dark orchid #9932CC (153,50,204) medium orchid #BA55D3 (186,85,211) purple #800080 (128,0,128) thistle #D8BFD8 (216,191,216) plum #DDA0DD (221,160,221) violet #EE82EE (238,130,238) magenta / fuchsia #FF00FF (255,0,255) orchid #DA70D6 (218,112,214) medium violet red #C71585 (199,21,133) pale violet red #DB7093 (219,112,147) deep pink #FF1493 (255,20,147) hot pink #FF69B4 (255,105,180) light pink #FFB6C1 (255,182,193) pink #FFC0CB (255,192,203) antique white #FAEBD7 (250,235,215) beige #F5F5DC (245,245,220) bisque #FFE4C4 (255,228,196) blanched almond #FFEBCD (255,235,205) wheat #F5DEB3 (245,222,179) corn silk #FFF8DC (255,248,220) lemon chiffon #FFFACD (255,250,205) light golden rod yellow #FAFAD2 (250,250,210) light yellow #FFFFE0 (255,255,224) saddle brown #8B4513 (139,69,19) sienna #A0522D (160,82,45) chocolate #D2691E (210,105,30) peru #CD853F (205,133,63) sandy brown #F4A460 (244,164,96) burly wood #DEB887 (222,184,135) tan #D2B48C (210,180,140) rosy brown #BC8F8F (188,143,143) moccasin #FFE4B5 (255,228,181) navajo white #FFDEAD (255,222,173) peach puff #FFDAB9 (255,218,185) misty rose #FFE4E1 (255,228,225) lavender blush #FFF0F5 (255,240,245) linen #FAF0E6 (250,240,230) old lace #FDF5E6 (253,245,230) papaya whip #FFEFD5 (255,239,213) sea shell #FFF5EE (255,245,238) mint cream #F5FFFA (245,255,250) slate gray #708090 (112,128,144) light slate gray #778899 (119,136,153) light steel blue #B0C4DE (176,196,222) lavender #E6E6FA (230,230,250) floral white #FFFAF0 (255,250,240) alice blue #F0F8FF (240,248,255) ghost white #F8F8FF (248,248,255) honeydew #F0FFF0 (240,255,240) ivory #FFFFF0 (255,255,240) azure #F0FFFF (240,255,255) snow #FFFAFA (255,250,250) black #000000 (0,0,0) dim gray / dim grey #696969 (105,105,105) gray / grey #808080 (128,128,128) dark gray / dark grey #A9A9A9 (169,169,169) silver #C0C0C0 (192,192,192) light gray / light grey #D3D3D3 (211,211,211) gainsboro #DCDCDC (220,220,220) white smoke #F5F5F5 (245,245,245) white #FFFFFF (255,255,255)
Read More
How to Sum the Two Lowest Positive Integers in C++
June 7, 2022
The challenge Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7. [10, 343445353, 3453445, 3453545353453] should return 3453455. The solution in C++ Option 1: #include <algorithm> #include <vector> long sumTwoSmallestNumbers(std::vector<int> numbers) { std::sort(numbers.
Read More
How to Sort an Array of Objects by Property in Javascript
June 6, 2022
If you need to sort an array of objects by their property values using Javascript, then you don’t need to look further than the built-in sort functionality. Step 1 – Create an array of objects to work with let people = [ { name : "John", surname : "Doe", age : 21 }, { name : "Jack", surname : "Bennington", age : 35 }, { name : "Jane", surname : "Doe", age : 19 } ]; Step 2 – Sort by keys Option 1 – Sort by surname people.
Read More
How to create a Countdown Timer in Python
June 5, 2022
If you need to count down a specific amount of time, say for example, when a token is set to expire, then a countdown timer will be useful. Step 1 – Writing the Python code Place the following Python code in a file called countdowntimer.py Option 1 – Text output import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Countdown time has elapsed!
Read More
How to Remove a Resource from Terraform State
June 4, 2022
Terraform state reflects the most up to date reference of the infrastructure. Sometimes you may need to remove a resource from the Terraform state manually. This is helpful if a resource has been deleted or modified manually and the resource definition has been removed in your Terraform code. This way you can re-run your Terraform plan and apply without deleting the remote infra resource that you removed from the state.
Read More
How to Delete a Specific Resource in Terraform
June 3, 2022
Running terraform destroy will tear down the whole stack associated to some terraform code. However, sometimes you might only want to remove a specific piece of your infrastructure. To do this, you can use the terraform destroy -target object. Step 1 – List the State Get a list of all the resources from the state: terraform state list #data.aws_ami.webserver_ami #aws_autoscaling_group.asg-web[0] #random_string.rand3 #... Step 2 – Remove a Specific Resource Run a terraform destroy -target and pass a resource from the state list above:
Read More
How to Create a DynamoDB Lock Table for Terraform
June 2, 2022
Provision the DynamoDB Table resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" { name = "terraform-state-lock-dynamo" hash_key = "LockID" read_capacity = 20 write_capacity = 20 attribute { name = "LockID" type = "S" } } Configure the DynamoDB table in Terraform Backend terraform { backend "s3" { encrypt = true bucket = "your-unique-bucket-name" dynamodb_table = "terraform-state-lock-dynamo" key = "terraform.tfstate" region = "us-east-1" } }
Read More
How to add Comments in Terraform
June 1, 2022
Terraform , a powerful Infrastructure as Code (IaC) tool, allows you to define and provision infrastructure resources. Properly commenting your Terraform code is essential for maintaining readability and sharing insights with your team. In this comprehensive guide, we’ll explore various methods to add comments in Terraform and address common questions related to Terraform syntax and best practices . Adding Comments in Terraform 1. # - Single Line Comment The # symbol marks the beginning of a single-line comment in Terraform.
Read More
How to log/debug in Terraform
May 31, 2022
If you have Terraform reporting an error but want more information, then you can configure debug logging. How to configure Bash export TF_LOG="TRACE" export TF_LOG_PATH="terraform.txt" How to configure PowerShell $env:TF_LOG="TRACE" $env:TF_LOG_PATH="terraform.txt"
Read More
How to find the number of trailing zeros of N in Rust
May 30, 2022
The challenge Write a program that will calculate the number of trailing zeros in a factorial of a given number. N! = 1 * 2 * 3 * ... * N Be careful 1000! has 2568 digits… For more info, see: http://mathworld.wolfram.com/Factorial.html Examples zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12!
Read More
How to do RGB To Hex Conversion in Rust
May 29, 2022
The challenge The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 – 255. Any values that fall out of that range must be rounded to the closest valid value. Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here. The following are examples of expected output values:
Read More
How to Rename a Git Branch
May 28, 2022
If you want to rename a git branch, then you have a few options, dependent on the use-case. Option 1 – Rename a Git Branch git branch -a <oldname> <newname> Option 2 – Rename the Current Branch git branch -m <newname> Option 3 – On Windows Windows required a capital “-M” instead. git branch -M <newname> Push the Local Branch and Reset the Upstream Branch git push origin -u <newname> Delete the Old Remote Branch git push origin --delete <oldname>
Read More
How to Find the Shortest Word in C++
May 27, 2022
The challenge Simple, given a string of words, return the length of the shortest word(s). The string will never be empty and you do not need to account for different data types. The solution in C++ Option 1: int find_short(const std::string &str) { std::istringstream inp(str); std::string s; int len = -1; while (std::getline(inp, s, ' ')) if (s.length() < len) len = s.length(); return len; } Option 2: int find_short(std::string str) { std::istringstream iss(str); std::vector<std::string> vec{ std::istream_iterator<std::string>(iss), {} }; return std::min_element(vec.
Read More
How to Square Every Digit in C++
May 26, 2022
The challenge You are asked to square every digit of a number and concatenate them. For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. Note: The function accepts an integer and returns an integer The solution in C++ Option 1: int square_digits(int n) { int a = 1; int m = 0; while (n > 0) { int d = n % 10; m += a * d * d; a *= d <= 3 ?
Read More
How to Count Vowels in C++
May 25, 2022
The challenge Return the number (count) of vowels in the given string. We will consider a, e, i, o, u as vowels for this challenge (but not y). The input string will only consist of lower case letters and/or spaces. The solution in C++ Option 1: #include <string> using namespace std; bool is_vowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } int getCount(const string& inputStr) { return count_if(inputStr.
Read More
How to Calculate the Sum of the Numbers in the Nth row of a Triangle in Golang
May 24, 2022
The challenge Given the triangle of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input –> Output) 1 --> 1 2 --> 3 + 5 = 8 The solution in Golang Option 1: package solution func RowSumOddNumbers(n int) int { return n * n * n } Option 2:
Read More
[Solved] Terraform Error accessing remote module registry in PowerShell
May 23, 2022
If you are using PowerShell and trying to run a terraform init, you may get an error as follows: Error: error accessing remote module registry Failed to retrieve available versions for module ... from registry.terraform.io: Failed to request discovery document: Get "https://registry.terraform.io/.well-known/terraform.json": read tcp x.x.x.x:xxxx->x.x.x.x: wsarecv: An existing connection was forcibly closed by the remote host.. Note that you will still be able to make a successful curl request, but terraform will fail!
Read More
How to Recursively Delete a Directory in PowerShell
May 22, 2022
If you want to recursively delete a directory/folder using PowerShell, then you have 2 options. Option 1 – With LiteralPath and Force Remove-Item -LiteralPath "myFolder" -Force -Recurse Option 2 – With implicit and Recurse Remove-Item myFolder/* -Recurse
Read More
[Solved] npm ERR! could not determine executable to run
May 21, 2022
If you get the following message, then there’s a very easy fix: npm ERR! could not determine executable to run The solution – using npm rm -rf .git/hooks npm install The solution – using yarn rm -rf .git/hooks yarn install
Read More
[Solved] npm ERR! path node_modules/node-sass
May 20, 2022
If you get the following error and need a solution, then look no further! npm ERR! code 1 npm ERR! path ./node_modules/node-sass npm ERR! command failed npm ERR! command sh -c node scripts/build.js npm ERR! gyp verb cli './node_modules/node-gyp/bin/node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose', Option 1 – With npm First, remove the node-sass dependency from your package.json, then: npm install npm i sass npm start Option 2 – With yarn First, remove the node-sass dependency from your package.
Read More
How to Install Lodash through Yarn for React
May 19, 2022
You can install lodash through yarn as follows: Step 1 – Install Lodash to get the Library yarn add lodash Step 2 – Get the Typescript info yarn add --dev @types/lodash
Read More
How to SHA256 a String in Golang
May 18, 2022
If you need to SHA256 a String in Go, then you can use the crypto/sha256 package. SHA256 a String in Go package main import ( "crypto/sha256" "fmt" ) func main() { s := "A sample string to SHA256!" h := sha256.New() h.Write([]byte(s)) bs := h.Sum(nil) fmt.Println(s) fmt.Printf("%x\n", bs) } The output will look like this: A sample string to SHA256! 9abf637c7e39cc4ef84d6d92cf7ffe168dc922b8ae666260d907e0353865ce89
Read More
How to Base64 Encode/Decode in Golang
May 17, 2022
Go ships with an encoding/base64 package that allows for encode and decoding of Base64 strings. Import the base64 package and then start using it! Base64 encode/decode a string package main import ( b64 "encoding/base64" "fmt" ) func main() { // define a string data := "This is a test string!" // Encode to Base64 sEnc := b64.StdEncoding.EncodeToString([]byte(data)) fmt.Println(sEnc) // Decode from Base64 sDec, _ := b64.StdEncoding.DecodeString(sEnc) fmt.Println(string(sDec)) // URL Encode uEnc := b64.
Read More
How to Base64 Encode a String in Java
May 16, 2022
Quick solution In short, you can just do this: new String(Base64.getEncoder().encode(bytes)); Examples and an explanation In Java 8 and above, you just need to import the Base64 class: import java.util.Base64; Then use the Base64 static methods as follows: byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes()); System.out.println("encodedBytes " + new String(encodedBytes)); byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes); System.out.println("decodedBytes " + new String(decodedBytes)); If you want to directly encode a string and get the result as an encoded string:
Read More
How to add a Lambda Environment Variable in Terraform
May 15, 2022
If you have an aws_lambda_function block that needs to make use of environment variables, then you can simply do the following: resource "aws_lambda_function" "test_lambda" { filename = "lambda_function_payload.zip" function_name = "lambda_function_name" runtime = "python3.9" ... environment { variables = { api_key = "secret-key" } } } The above example creates an environment variable called api_key with a value of secret-key
Read More
How to perform Array Element Parity in Golang
May 14, 2022
The challenge You will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. Examples: [1, -1, 2, -2, 3] => 3 3 has no matching negative appearance [-3, 1, 2, 3, -1, -4, -2] => -4 -4 has no matching positive appearance [1, -1, 2, -2, 3, 3] => 3
Read More
How to Reverse Letters in Kotlin
May 13, 2022
The challenge Given a string str, reverse it omitting all non-alphabetic characters. Examples: For str = "krishan", the output should be "nahsirk". For str = "ultr53o?n", the output should be "nortlu". Input/Output: [input] string str A string consists of lowercase Latin letters, digits, and symbols. [output] a string The solution in Kotlin Option 1: fun reverseLetter(str: String): String { return str.filter(Char::isLetter).reversed() } Option 2: fun reverseLetter(str: String) = str.reversed().filter{ it.isLetter() } Option 3:
Read More
How to Get the ASCII Value of Character in Kotlin
May 12, 2022
The challenge Get the ASCII value of a character. The solution in Kotlin Option 1: val getAscii = Char::toInt Option 2: fun getAscii(c: Char) = c.code Option 3: fun getAscii(c: Char): Int { return c.code.toByte().toInt() } Test cases to validate our solution import kotlin.test.assertEquals import org.junit.Test class TestExample { @Test fun `Basic tests`() { assertEquals(65, getAscii('A')) assertEquals(32, getAscii(' ')) assertEquals(33, getAscii('!')) } }
Read More
How to update each dependency in package.json to the latest version
May 11, 2022
You have 2 options: Option 1 – Recommended (Using npx) npx npm-check-updates -u npm install Option 2 – Older way (Using npm globally) npm i -g npm-check-updates ncu -u npm install
Read More
How to Convert IPv4 to int32 in Javascript
May 10, 2022
The challenge Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits). 1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 4th octet 1 has the binary representation: 00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001 Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.
Read More
How to Solve the Grouped by Commas Challenge in Javascript
May 9, 2022
The challenge Finish the solution so that it takes an input n (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits. Assume: 0 <= n < 2147483647 Examples: 1 -> "1" 10 -> "10" 100 -> "100" 1000 -> "1,000" 10000 -> "10,000" 100000 -> "100,000" 1000000 -> "1,000,000" 35235235 -> "35,235,235" The solution in Javascript Option 1: function groupByCommas(n) { return n.
Read More
How to Save sed Output Directly to a File
May 8, 2022
You have 3 options here: Option 1: use tee with sed sed 's/Hello/Hi/g' file-name | tee file Option 2: use > with sed sed 's/Hello/Hi/g' file-name > file Option 3: use sed with -i option sed -i 's/Hello/Hi/g' file-name
Read More
How to Convert BigNumber to Int/Number in Ethers/Web3
May 7, 2022
If you have a BigNumber when using web3, then you can convert this to a regular Javascript Number using the ethers library as follows: ethers.BigNumber.from(max).toNumber() <a href="https://github.com/ethers-io/ethers.js/" target="_blank" rel="noreferrer noopener nofollow">Ethers</a> is a complete Ethereum library and wallet implementation in Javascript.
Read More
How to Create a Pyramid Array in Javascript
May 6, 2022
The challenge Write a function that when given a number >= 0, returns an Array of ascending length subarrays. pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ] Note: the subarrays should be filled with 1s The solution in Javascript Option 1: function pyramid(n) { const res = []; for(let i = 0; i < n; i++){ res.
Read More
How to Create a Reverse Polish Notation Calculator in Javascript
May 5, 2022
The challenge Your job is to create a calculator which evaluates expressions in Reverse Polish notation. For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14. For your convenience, the input is formatted such that a space is provided between every token. The empty expression should evaluate to ``.
Read More
How to declare a global variable in React?
May 4, 2022
If you need to declare a global variable in React, then you can do the following: Create a file called config.js module.exports = global.config = { something: { somethingelse: { amount: 123, name: "Andrew" } } }; Then import the config file where you need it: import './config'; Then where you need it in your code: global.config.something.somethingelse.amount or global.config.something.somethingelse.name
Read More
How to Find the Missing Term in an Arithmetic Progression in Javascript
May 3, 2022
The challenge An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers that have been given to you. The rest of the given series is the same as the original AP.
Read More
How to Count Characters in a Javascript String
May 2, 2022
The challenge The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}. What if the string is empty? Then the result should be an empty object literal, {}. The solution in Javascript Option 1: function count (string) { var count = {}; string.split('').forEach(function(s) { count[s] ? count[s]++ : count[s] = 1; }); return count; } Option 2:
Read More
How to Increment/Decrement a value in React/NextJS
May 1, 2022
Use the following code block to get started: function GetCount() { const [count, setCount] = useState(1); const incrementCounter = () => { setCount(count+1) } const decrementCounter = () => { if (count>1) setCount(count-1) } return <div className="_counterWrapper"> <span className="_dec" onClick={() => decrementCounter()}>-</span> <span className="_val">{count}</span> <span className="_inc" onClick={() => incrementCounter()}>+</span> </div> } Then in your HTML code, add it like this: <GetCount />
Read More
How to disable text selection highlighting in CSS
April 30, 2022
If you would like to disable the text selection highlighting that is enabled by default on all browsers, then you can do this: user-select: none; If you are concerned about cross-browser support, then use this class: .noselect { -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Safari */ -khtml-user-select: none; /* Konqueror HTML */ -moz-user-select: none; /* Old versions of Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */ } You can then use it like this:
Read More
Irreducible Sum of Rationals in Golang
April 29, 2022
The challenge You will have a list of rationals in the form: lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ] where all numbers are positive integers. You have to produce their sum N / D in an irreducible form: this means that N and D have only 1 as a common divisor. Return the result in the form: "N/D" If the result is an integer (D evenly divides N) return: "n"
Read More
How to copy S3 objects between AWS accounts
April 28, 2022
In your source account create a customer-managed policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::source-EXAMPLE-BUCKET", "arn:aws:s3:::source-EXAMPLE-BUCKET/*" ] }, { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::destination-EXAMPLE-BUCKET", "arn:aws:s3:::destination-EXAMPLE-BUCKET/*" ] } ] } In your destination bucket, update the bucket policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::1234567890:user/Andrew" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::destination-EXAMPLE-BUCKET/*", "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } } }, { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::1234567890:user/Andrew" }, "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::destination-EXAMPLE-BUCKET" } ] } Testing the S3 copy between accounts:
Read More
How to find all symlinks in a directory tree on Mac
April 27, 2022
If you need to recursively find all symbolic links in a directory tree on a Mac, then you have a couple of options. You could be trying to find them because a tool like Dropbox is consuming high CPU and you need to remove them, or perhaps you want to move a directory to another machine or network drive and verifying a package is required. Option 1 – View all files that are symlinks ls -lR .
Read More
How to Install App Mesh on AWS EKS
April 26, 2022
You can follow the steps below to install App Mesh on AWS EKS (Kubernetes). Step 1 – Prerequisites curl -o pre_upgrade_check.sh https://raw.githubusercontent.com/aws/eks-charts/master/stable/appmesh-controller/upgrade/pre_upgrade_check.sh sh ./pre_upgrade_check.sh Step 2 – Add Helm Repo helm repo add eks https://aws.github.io/eks-charts Step 3 – Add Custom Resource Definitions (CRDs) kubectl apply -k "https://github.com/aws/eks-charts/stable/appmesh-controller/crds?ref=master" Step 4 – Create a Namespace for App Mesh kubectl create ns appmesh-system Step 5 – Set Environment Variables You will need to set a couple of environment variables to make things easier later.
Read More
[Solved] Kubernetes Namespace stuck in Terminating state
April 25, 2022
If you have tried to delete a Kubernetes namespace, and it has been hanging in ‘deleting’ for hours on end, it’s likely that you have dangling resources that have not deleted yet. $ kubectl get ns NAME STATUS AGE apps Active 2d19h default Active 3d8h my-apps Terminating 11h This will prevent the namespace from being removed. How to find resources that need to be deleted You can chain the api-resources verbs along with a kubectl get to find dangling resources:
Read More
[Solved] Error creating: pods “my-service-a-xxx” is forbidden: error looking up service account my-apps/my-service-a: serviceaccount “my-service-a” not found
April 24, 2022
So you’ve run a deployment and tried to check the pods and there’s nothing there! kubectl get pods Next step is to see what’s happening with the replicaset kubectl get rs Then take the replicaset name and do a describe on it: kubectl describe rs my-service-a-5549cbc6c8 The error Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedCreate 2m10s.. replicaset-controller Error creating: pods "my-service-a-5549cbc6c8-" is forbidden: error looking up service account my-apps/my-service-a: serviceaccount "my-service-a" not found It’s down to a missing Service Account!
Read More
[Solved] error: src refspec main does not match any
April 23, 2022
If you get the following error: error: src refspec main does not match any error: failed to push some refs to 'https://github.com/ao/xxx.git' This is because you probably haven’t committed any files to git yet! Fix for: src refspec main does not match any Make sure to add your files, if they have not been added yet: git add . Commit your files: git commit -m "your commit message" Push your changes to the git repo, remember to swap out the branch name as appropriate:
Read More
How to Force a Redeploy in Kubernetes
April 22, 2022
If you need to force a redeploy of a deployment in Kubernetes , then you can use the rollout feature. You may have an image that has been updated, but without changing the tag/version. Step 1 – Optionally update the imagePullPolicy If you have not changed the image version, then check your imagePullPolicy. In your deployment.yaml file: containers: - name: backend image: aoms/mock_backend_python:latest imagePullPolicy: Always Step 2 – Get the deployment name kubectl get deploy Step 3 – Force the Redeployment kubectl rollout restart deploy backend
Read More
How to Print to stdout in Flask using Python
April 21, 2022
If you are trying to print() to the console/stdout in your Flask app, but nothing is happening, then you just need to flush your prints, as follows: print('This will print', flush=True)
Read More
How to Restart a Deployment in Kubernetes
April 20, 2022
If you need to restart a deployment in Kubernetes, perhaps because you would like to force a cycle of pods, then you can do the following: Step 1 – Get the deployment name kubectl get deployment Step 2 – Restart the deployment kubectl rollout restart deployment <deployment_name>
Read More
How to push multiple Dockerfile apps to AWS ECR at the same time
April 19, 2022
I have a parent directory containing multiple sub-directories. Each of these child directories is a different application and contains a Dockerfile. I want to build and push each image to AWS ECR. The directory looks as follows: ├── apps ├── microservice1 ├── app.js ├── Dockerfile ├── package.json └── readiness.txt ├── frontend ├── Dockerfile ├── index.html ├── package.json ├── server.js ├── microservice2 ├── app.py ├── bootstrap.sh ├── Dockerfile └── requirements.txt Notice there are 3 apps, each with their own Dockerfile, under the parent apps directory.
Read More
How to Create a Horizontal Pod Autoscaler in Kubernetes
April 18, 2022
If you could like to a create a Horizontal Pod Autoscaler (hpa) in Kubernetes, then you could run the following: Step 1 – Create a Deployment If you already have a deployment, then ignore this step, otherwise: kubectl create deployment php-apache --image=us.gcr.io/k8s-artifacts-prod/hpa-example kubectl set resources deploy php-apache --requests=cpu=200m kubectl expose deploy php-apache --port 80 kubectl get pod -l app=php-apache Step 2 – Create a Horizontal Pod Autoscaler kubectl autoscale deployment php-apache `#The target average CPU utilization` \ --cpu-percent=50 \ --min=1 `#The lower limit for the number of pods that can be set by the autoscaler` \ --max=10 `#The upper limit for the number of pods that can be set by the autoscaler` Step 3 – Get your hpa kubectl get hpa
Read More
How to Run a Load Generator on Kubernetes
April 17, 2022
If you would like to test hpa, Horizontal Pod Autoscaling, or throw some chaos at a specific deployment in Kubernetes , then you could run a Load Generator Step 1 – Run a BusyBox container The following command will use a busybox container and dump you into it’s shell window: kubectl run -i --tty load-generator --image=busybox /bin/sh As an alternative, you could also run: kubectl --generator=run-pod/v1 run -i --tty load-generator --image=busybox /bin/sh Step 2 – Run a wget loop You can now trigger a wget loop to make HTTP request calls to your deployment:
Read More
How to Deploy a Metrics Server in Kubernetes
April 16, 2022
If you would like to deploy a Metrics Server in Kubernetes , then you first need to create a namespace for it to live it, followed by installing the actual metrics server. Step 1 – Install the Metrics Server Using kubectl kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.5.0/components.yaml Using helm kubectl create namespace metrics helm install metrics-server \ stable/metrics-server \ --version 2.9.0 \ --namepsace metrics Step 2 – Get the Metrics Server Status If you used kubectl above, then you should be able to run:
Read More
How to create an AWS EKS cluster using eksctl
April 15, 2022
eksctl dramatically simplifies the creation of AWS EKS clusters, by providing a simple command-line interface. Step 1 – Define a Cluster YAML You can either create a file called ekscluster.yaml and place the YAML in, or run the following command which will create a file called ekscluster.yaml and automatically add the default YAML configuration for you. cat << EOF > ekscluster.yaml --- apiVersion: eksctl.io/v1alpha5 kind: ClusterConfig metadata: name: eksworkshop-eksctl region: ${AWS_REGION} version: "1.
Read More
How to Dockerize a Flask App
April 14, 2022
If you have a Flask app that you would like packaged in a Docker container, then you can do the following. The steps outlined below will help you create the following directory tree: └── flaskapp ├── Dockerfile ├── app.py └── requirements.txt Step 1 – Create your Flask app In a new directory, create the following files: app.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_geek(): return '<h1>Hello world!</h2>' if __name__ == "__main__": app.
Read More
How to get an EKS Cluster name from an AWS Region
April 13, 2022
You can use the aws cli to get the EKS cluster name, parse the first result and return it into a variable. EKS_CLUSTER_NAME=$(aws eks list-clusters --region us-west-2 --query clusters[0] --output text) echo $EKS_CLUSTER_NAME
Read More
How to automatically generate a Manifests file in Kubernetes
April 12, 2022
If you want to automatically generate a manifest file in Kubernetes, you can do so by using the kubectl run command coupled with a --dry-run to output directly to yaml. kubectl run nginx --image=nginx --port=80 --replicas=2 --expose --dry-run -o yaml You can also output this directly to a file on disk as follows: kubectl run nginx --image=nginx --port=80 --replicas=2 --expose --dry-run -o yaml > your-deployment-manifest.yaml
Read More
How to Sort Pods by CreationTimestamp in Kubernetes
April 11, 2022
If you need to sort a list of your pods by their CreationTimestamp, then do the following: kubectl get pods -n kube-system --sort-by=metadata.creationTimestamp A better way to specify the JSON path is: kubectl get pods -n kube-system --sort-by='{.metadata.creationTimestamp}'
Read More
How to Jump onto a Kubernetes Pod with Bash
April 10, 2022
If you want to jump onto a particular Kubernetes Pod and run Bash within it, you can do so as follows: kubectl exec -ti <pod_name> /bin/bash You can get the <pod_name> by running kubectl get pods
Read More
How to run Shell Commands in a Kubernetes Cluster
April 9, 2022
If you would like to run shell commands inside of your Kubernetes cluster, then you can use the kubectl run command. What the syntax looks like kubectl run --image=<imagename> <name> -restart=Never -it --rm -- /bin/sh -c "<command>" Breaking this down, you pass in an imagename which is the container image you would like to execute the commands in, the name of this temporary container, and then command you would like to run in it.
Read More
How to Bulk Move All Email from One Account to Another using the CLI
April 8, 2022
If you find yourself in a position where you need to sync all emails from one account to another, then you can use the imapsync command-line tool to bulk copy, or move everything for you. Step 1 – Get imapsync You need to get the imapsync tool running locally. It can be found here https://github.com/imapsync/imapsync Alternatively, if you are using a Mac and have homebrew installed, then you’re in luck!
Read More
How to Install AWS CLI on Linux
April 7, 2022
You can download and install the AWS CLI on Linux as follows: Perform the install curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install Verify the install aws --version
Read More
How to Reboot Networking on Mac from CLI
April 6, 2022
If you need to reboot, or restart the networking interface on your Mac, by using the CLI, then you can issue the following commands: Using the ifconfig primary interface Tear down the networking interface sudo ifconfig en0 down Restart the networking interface sudo ifconfig en0 up Verify the networking restart ifconfig -u en0 Alternative without sudo, using networksetup If you need to perform the same result, but not able to run sudo, then look to the networksetup.
Read More
[Solved] fatal: unable to access <git>: SSL certificate problem: self signed certificate in certificate chain
April 5, 2022
If you get the following error: fatal: unable to access <git>: SSL certificate problem: self signed certificate in certificate chain ..when trying to clone a git repo, then you can quickly get around it by doing one of the following. Note that both of these solutions are merely workarounds and should be done at absolute worst case. Workaround Solution 1 Disable SSL verification while running the git clone. git -c http.
Read More
How to Extract the Files in a Docker Image
April 4, 2022
Ever needed to extract the files in a Docker container? Docker provides the save sub-command. Exporting Docker files into a Tar Archive The examples below use a Docker container called: aoms/hellojava Swap this out with your own container as required. docker save aoms/hellojava > hellojava.tar hellojava.tar now contains a list of files found in the Docker image. Taking it one step further You can make this a bit better by extracting it into a new directory and untarring automatically:
Read More
[Solved] Error response from daemon: No such image: Docker
April 3, 2022
If you’ve run into this dreaded error: Error response from daemon: No such image: Then you can solve it as follows: Step 1 Perform a docker pull -a <org/image> Then perform a docker images -a to see what the version is. Step 2 This issue can occur when it is trying to map tag to latest, but a specific version is explicitly listed instead. docker tag <org>/<image>:v1 <new_org>/<image> Make sure to replace :v1 with the specific TAG that was shown from the docker images command above.
Read More
How to Bootstrap a Web Server on AWS EC2
April 2, 2022
When you launch an EC2 instance, you can use the user-data to bootstrap a instance creation script. We can use the following code to start a web server and echo out it’s instance id: #!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "<h1>Hello World from $(hostname -f)</h1>" > /var/www/html/index.html Steps to create a new bootstrapped instance Step 1 – Launch a new instance Login to your EC2 console and click Launch instances.
Read More
How to Update Kubectl Config from AWS EKS
April 1, 2022
Ever searched for kubectl update config from aws eks and needed a quick result? Step 1 – Validate AWS CLI Make sure that you have valid AWS Credentials setup in your aws cli. You can check this by typing: aws sts get-caller-identity This will let you know where your aws cli is pointing to. You may need to update your ~/.aws/credentials file with a profile_name, aws_access_key_id, aws_secret_access_key and aws_session_token if these are generated for you by your Single Sign On (SSO).
Read More
How to Generate a Random String in Java
March 31, 2022
Java provides many ways to generate random strings. 1. Using Apache Commons public void generatingRandomAlphanumericString_ApacheCommons() { String generatedString = RandomStringUtils.randomAlphanumeric(10); System.out.println(generatedString); } 2. Using Java 8 public void generatingRandomAlphanumericString_Java8() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .
Read More
How to Generate a Random String in Python
March 30, 2022
Python gives the ability to generate random strings out of the box, by using a combination of the string and random modules. import string import random # How many characters do you want S = 10 # Call random.choices() string module to find the string in Uppercase + numeric data. ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S)) # Print the result print("The randomly generated string is : " + str(ran))
Read More
How to Generate a Random Number/String in Terraform
March 29, 2022
If you need to generate a random number or string in Terraform, then you can use the following: resource "random_id" "myrandom" { keepers = { first = "${timestamp()}" } byte_length = 8 } Then refer to it as: random_id.myrandom.hex
Read More
[Solved] Unable to connect to the server: dial tcp: lookup with AWS EKS
March 28, 2022
If you have received the following error while trying to issue commands to kubectl: Unable to connect to the server: dial tcp: lookup Then it may be due to your kube-config being out of date. You might just need to update the local kube-config. How to update the local kube-config Make sure to replace eu-west-1 with your cluster’s region, and replace cluster_name with the name of your EKS cluster. aws eks --region "eu-west-1" update-kubeconfig --name "cluster_name" How to update kube-config from Terraform state aws eks --region $(terraform output -raw region) update-kubeconfig --name $(terraform output -raw cluster_name) The above code makes use of the Terraform state’s output from when you generated the cluster.
Read More
How to Store Terraform State in AWS S3
March 27, 2022
Storing Terraform states files locally is not recommended. Instead you should use a backend such as as S3 from AWS. To do this, you just need to add the following backend information in a terraform block in your code: terraform { backend "s3" { bucket = "mybucket" key = "path/to/my/key" region = "eu-west-1" } }
Read More
[Solved] ZipArchive extension: disabled/not installed on Ubuntu
March 26, 2022
If you have come across the following error: ZipArchive extension:&nbsp;<strong>disabled/not installed</strong> This just means that you are missing the php-zip module. How to fix the ZipArchive extension problem Run the following command: sudo apt-get install -y php-zip Now restart Apache2, and you’re good! service apache2 restart
Read More
Calculating Cartesian Neighbors Distance in Golang
March 25, 2022
The challenge We have been searching for all the neighboring points in a Cartesian coordinate system. As we know each point in a coordinate system has eight neighboring points when we search it by range equal to 1, but now we will change the range by the third argument of our function (range is always greater than zero). For example, if range = 2, count of neighboring points = 24. In this challenge, a grid step is the same (= 1).
Read More
How to Calculate Dominant Primes in Golang
March 24, 2022
The challenge The prime number sequence starts with: 2,3,5,7,11,13,17,19.... Notice that 2 is in position one. 3 occupies position two, which is a prime-numbered position. Similarly, 5, 11 and 17 also occupy prime-numbered positions. We shall call primes such as 3,5,11,17 dominant primes because they occupy prime-numbered positions in the prime number sequence. Let’s call this listA. As you can see from listA, for the prime range range(0,10), there are only two dominant primes (3 and 5) and the sum of these primes is: 3 + 5 = 8.
Read More
[Solved] error: src refspec main does not match
March 23, 2022
When you first try and push to a git repository, you may get the following error message: error: src refspec master does not match any. error: failed to push some refs to 'git@github ... .git' This is because you have not committed your files! How to Fix src refspec main does not match git commit -m "initial commit" git push origin main The above code will commit your files that are staged, before pushing them to your desired branch.
Read More
How to Solve Simple Square Numbers in Golang
March 22, 2022
The challenge In this challenge, you will be given a number n (n > 0) and your task will be to return the smallest square number N (N > 0) such that n + N is also a perfect square. If there is no answer, return -1 (nil in Clojure, Nothing in Haskell, None in Rust). solve 13 = 36 <em>; because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49</em> solve 3 = 1 <em>; 3 + 1 = 4, a perfect square</em> solve 12 = 4 <em>; 12 + 4 = 16, a perfect square</em> solve 9 = 16 solve 4 = nil The solution in Golang Option 1:
Read More
How to perform Function Iteration in Golang
March 21, 2022
The challenge The purpose of this challenge is to write a higher-order function returning a new function that iterates on a specified function a given number of times. This new function takes in an argument as a seed to start the computation. For instance, consider the function getDouble. When run twice on value 3, yields 12 as shown below. getDouble(3) => 6 getDouble(6) => 12 Let us name the new function createIterator and we should be able to obtain the same result using createIterator as shown below:
Read More
Determining Integer Depth in Python
March 20, 2022
The challenge The depth of an integer n is defined to be how many multiples of n it is necessary to compute before all 10 digits have appeared at least once in some multiple. Example: let see n=42 Multiple value digits comment 42*1 42 2,4 42*2 84 8 4 existed 42*3 126 1,6 2 existed 42*4 168 - all existed 42*5 210 0 2,1 existed 42*6 252 5 2 existed 42*7 294 9 2,4 existed 42*8 336 3 6 existed 42*9 378 7 3,8 existed Looking at the above table under digits column you can find all the digits from `` to 9, Hence it required 9 multiples of 42 to get all the digits.
Read More
How to Reverse a singly-linked list in Python
March 19, 2022
The challenge Implement a function reverse_list that takes a singly-linked list of nodes and returns a matching list in the reverse order. Assume the presence of a class Node, which exposes the property value/Value and next/Next. next must either be set to the next Node in the list, or to None (or null) to indicate the end of the list. To assist in writing tests, a function make_linked_list (Node.asLinkedList() in Java) has also been defined, which converts a python list to a linked list of Node.
Read More
Calculating Simple Time Difference in Python
March 18, 2022
The challenge In this challenge, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any. Examples: # If the alarm goes off now, it will not go off for another 23 hours and 59 minutes.
Read More
Calculating Odd/Even number of divisors in Python
March 17, 2022
The challenge Given an integer n return "odd" if the number of its divisors is odd. Otherwise, return "even". Note: big inputs will be tested. Examples: All prime numbers have exactly two divisors (hence "even"). For n = 12 the divisors are [1, 2, 3, 4, 6, 12] – "even". For n = 4 the divisors are [1, 2, 4] – "odd". The solution in Python code Option 1: def oddity(n): #your code here return 'odd' if n**0.
Read More
Calculate possibilities of throwing a coin N times in Python
March 16, 2022
The challenge In this challenge, you will be given an integer n, which is the number of times that is thrown a coin. You will have to return an array of strings for all the possibilities (heads[H] and tails[T]). Examples: coin(1) should return {"H", "T"} coin(2) should return {"HH", "HT", "TH", "TT"} coin(3) should return {"HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"} When finished sort them alphabetically. In C and C++ just return a char* with all elements separated by, (without space):
Read More
How to Convert Integer to Whitespace format in Python
March 15, 2022
The challenge Hereinafter, [space] refers to " ", [tab] refers to "\t", and [LF] refers to "\n" for illustrative purposes. This does not mean that you can use these placeholders in your solution. In esoteric language called Whitespace, numbers are represented in the following format: first character represents the sign: [space] for plus, [tab] for minus; characters after that and until [LF] are the binary representation of the integer: [space] for 0, [tab] for 1.
Read More
How to Perform Frog Jumping in Python
March 14, 2022
The challenge You have an array of integers and have a frog at the first position [Frog, int, int, int, ..., int] The integer itself may tell you the length and the direction of the jump For instance: 2 = jump two indices to the right -3 = jump three indices to the left 0 = stay at the same position Your objective is to find how many jumps are needed to jump out of the array.
Read More
How to Calculate the area of a regular N sides polygon inside a circle of radius R in Python
March 13, 2022
The challenge Write the following function: def area_of_polygon_inside_circle(circle_radius, number_of_sides): It should calculate the area of a regular polygon of numberOfSides, number-of-sides, or number_of_sides sides inside a circle of radius circleRadius, circle-radius, or circle_radius which passes through all the vertices of the polygon (such a circle is called circumscribed circle or circumcircle). The answer should be a number rounded to 3 decimal places. Input/Output Examples area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.
Read More
How to create an Image Host Filename Generator in Python
March 12, 2022
The challenge You are developing an image hosting website. You have to create a function for generating random and unique image filenames. Create a function for generating a random 6 character string that will be used to access the photo URL. To make sure the name is not already in use, you are given access to a PhotoManager object. You can call it like so to make sure the name is unique
Read More
How to Find the Missing Alphabets in Python
March 11, 2022
The challenge Task Given string s, which contains only letters from a to z in lowercase. A set of the alphabet is given by abcdefghijklmnopqrstuvwxyz. 2 sets of alphabets mean 2 or more alphabets. Your task is to find the missing letter(s). You may need to output them by the order a-z. It is possible that there is more than one missing letter from more than one set of alphabet.
Read More
How to move MySQL database to another drive
March 10, 2022
Step 1: Login to your MySQL server, enter your password when prompted: mysql -u root -p Find out where the data directory is located: mysql> select @@datadir; Output +-----------------+ | @@datadir | +-----------------+ | /var/lib/mysql/ | +-----------------+ 1 row in set (0.00 sec) Step 2: Now you can stop the server and check the status: sudo systemctl stop mysql sudo systemctl status mysql It’s time to make a copy to your new mount location:
Read More
How to Find the Sum of Prime-Indexed Elements in Go
March 9, 2022
The challenge You will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. The first element of the array is at index ``. The solution in Golang Option 1: package solution import "math/big" func Solve(arr []int) int { c := 0 for i := 0; i < len(arr); i++ { n := arr[i] if big.NewInt(int64(i)).ProbablyPrime(0) { c += n } } return c } Option 2:
Read More
How to Find the Longest Substring in Alphabetical Order in Python
March 8, 2022
The challenge Find the longest substring in alphabetical order. Example: the longest alphabetical substring in "asdfaaaabbbbcttavvfffffdf" is "aaaabbbbctt". Overview: There are tests with strings up to 10 000 characters long so your code will need to be efficient. The input will only consist of lowercase characters and will be at least one letter long. If there are multiple solutions, return the one that appears first. The solution in Python Option 1:
Read More
Calculate the Most Frequent Weekdays in Go
March 7, 2022
The challenge What is your favourite day of the week? Check if it’s the most frequent day of the week in the year. You are given a year as integer (e. g. 2001). You should return the most frequent day(s) of the week in that year. The result has to be a list of days sorted by the order of days in week (e. g. ['Monday', 'Tuesday'], ['Saturday', 'Sunday'], ['Monday', 'Sunday']).
Read More
Return Index of Matching Closing Bracket in Go
March 6, 2022
The challenge In this challenge, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based. An opening brace will always have a closing brace. Return an error if there is no answer. Examples: solve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10 solve("((1)23(45))(aB)", 1) = 3 solve("((1)23(45))(aB)", 2) = -1 // there is no opening bracket at index 2, so return -1 solve("((1)23(45))(aB)", 6) = 9 solve("((1)23(45))(aB)", 11) = 14 solve("((>)|?
Read More
How to Presign an S3 URL in AWS using AWS CLI
March 5, 2022
You can use the AWS CLI to presign URLs so that objects in S3 can be shared publicly even if they are set as private. Presigned URLs are great for sharing private files in an S3 bucket aws s3 presign s3://<bucket>/<file.jpg> This can also be coupled with an expiry duration: aws s3 presign s3://<bucket>/<file.jpg> --expires-in 3600
Read More
How to Download using Aria2c with Multiple Connections
March 4, 2022
If you use aria2c to download files using the command-line, then you can also use it to download using multiple connections. aria2c -x16 -s16 <url> -x**, –max-connection-per-server=** The maximum number of connections to one server for each download. Default: 1 -s**, –-split=** Download a file using N connections. Default: 5
Read More
How to Parse HTML/CSS Colors in Java
March 3, 2022
The challenge In this challenge, you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function that takes a color as a string and returns the parsed color as a map (see Examples). Inputs: The input string represents one of the following: 6-digit hexadecimal – “#RRGGBB” e.g. “#012345”, “#789abc”, “#FFA077” Each pair of digits represents a value of the channel in hexadecimal: 00 to FF 3-digit hexadecimal – “#RGB”
Read More
Solving Simple Transposition in Java
March 2, 2022
The challenge Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in Row 1, the second in Row 2, third in Row 1, and so on until the end. Then we put the text from Row 2 next to the Row 1 text and that’s it. Complete the function that receives a string and encrypts it with this simple transposition. Example: For example, if the text to encrypt is: "Simple text", the 2 rows will be:
Read More
How to Binary to Text (ASCII) Conversion in Python
March 1, 2022
The challenge Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded). Each 8 bits on the binary string represent 1 character on the ASCII table. The input string will always be a valid binary string. Characters can be in the range from “00000000” to “11111111” (inclusive) Note: In the case of an empty binary string your function should return an empty string.
Read More
How to Find the Row of the Odd Triangle in Python
February 28, 2022
The challenge Given a triangle of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... find the triangle’s row knowing its index (the rows are 1-indexed), e.g.: odd_row(1) == [1] odd_row(2) == [3, 5] odd_row(3) == [7, 9, 11] Note: your code should be optimized to handle big inputs. The solution in Python code Option 1: def odd_row(n): m = (n - 1) * n + 1 return [*range(m, m + n * 2, 2)] Option 2:
Read More
Solving Number Zoo Patrol in Python
February 27, 2022
The challenge Write a function that takes a shuffled list of unique numbers from 1 to n with one element missing (which can be any number including n). Return this missing number. Note: huge lists will be tested. Examples: [1, 3, 4] => 2 [1, 2, 3] => 4 [4, 2, 3] => 1 The solution in Python code Option 1: def find_missing_number(a): n = len(a) + 1 return n * (n + 1) // 2 - sum(a) Option 2:
Read More
Common AWS CDK CLI Commands
February 26, 2022
The AWS Cloud Development Kit (CDK) comes with numerous CLI commands. Command Function cdk list (ls) Lists the stacks in the application cdk synthesize (synth) Synthesizes and prints the AWS CloudFormation template for the specified stack or stacks cdk bootstrap Deploys the AWS CDK Toolkit stack, required to deploy stacks containing assets cdk deploy Deploys the specified stacks cdk destroy Destroys the specified stacks cdk diff Compares the specified stack with the deployed stack or a local AWS CloudFormation template cdk metadata Displays metadata about the specified stack cdk init Creates a new AWS CDK project in the current directory from a specified template cdk context Manages cached context values cdk docs (doc) Opens the AWS CDK API reference in your browser cdk doctor Checks your AWS CDK project for potential problems Learn more about AWS CDK here , or read the Official Guides here .
Read More
How to Create an S3 bucket with PublicRead in CloudFormation
February 25, 2022
AWSTemplateFormatVersion: 2010-09-09 Description: Basic S3 Bucket CloudFormation template Resources: S3BucketForWebsiteContent: Type: AWS::S3::Bucket Properties: AccessControl: PublicRead Outputs: BucketName: Value: !Ref S3BucketForWebsiteContent Description: Name of the newly created Amazon S3 Distribution
Read More
How to Create a VPC in CloudFormation
February 24, 2022
It’s very easy to deploy a VPC using CloudFormation: AWSTemplateFormatVersion: 2010-09-09 Description: Deploy a VPC Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsHostnames: true Tags: - Key: Name Value: Lab VPC <meta charset="utf-8">Outputs: VPC: Description: VPC Value: !Ref VPC This will also output the created VPC resource information. But what if you also want to create Subnets and an attached Internet Gateway? AWSTemplateFormatVersion: 2010-09-09 Description: Deploy a VPC Resources: VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.
Read More
How to Setup Git on EC2 for AWS CodeCommit
February 23, 2022
Connect to the instance: chmod 400 KEYPAIR.pem ssh -i KEYPAIR.pem ec2-user@EC2PublicIP Install Git: sudo yum install -y git Setup Git Credential Helper: git config --global credential.helper '!aws codecommit credential-helper $@' git config --global credential.UseHttpPath true Now you can clone the CodeCommit repo which will look something like the following: https:&#47;&#47;git-codecommit.us-east-1.amazonaws.com/v1/repos/My-Repo
Read More
The Difference of 2 in Java
February 22, 2022
The challenge The objective is to return all pairs of integers from a given array of integers that have a difference of 2. The resulting array should be sorted in ascending order of values. Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter. Examples: [1, 2, 3, 4] should return [[1, 3], [2, 4]] [4, 1, 2, 3] should also return [[1, 3], [2, 4]] [1, 23, 3, 4, 7] should return [[1, 3]] [4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]] The solution in Java code Option 1:
Read More
How to Make the Deadfish Swim in Java
February 21, 2022
The challenge Write a simple parser that will parse and run Deadfish. Deadfish has 4 commands, each 1 character long: i increments the value (initially ``) d decrements the value s squares the value o outputs the value into the return array Invalid characters should be ignored. Deadfish.parse("iiisdoso") =- new int[] {8, 64}; The solution in Java code Option 1: import java.util.ArrayList; import java.util.List; public class DeadFish { public static int[] parse(String data) { int value = 0; List<Integer> result = new ArrayList<>(); for(char letter : data.
Read More
How to Write Number in Expanded Form in Java
February 20, 2022
The challenge You will be given a number and you will need to return it as a string in Expanded Form. Examples: Challenge.expandedForm(12); // Should return "10 + 2" Challenge.expandedForm(42); // Should return "40 + 2" Challenge.expandedForm(70304); // Should return "70000 + 300 + 4" NOTE: All numbers will be whole numbers greater than 0. The solution in Java code Option 1: public class Challenge { public static String expandedForm(int num) { StringBuffer res = new StringBuffer(); int d = 1; while(num > 0) { int nextDigit = num % 10; num /= 10; if (nextDigit > 0) { res.
Read More
Is a Number Prime in Java
February 19, 2022
The challenge Define a function that takes one integer argument and returns a logical value true or false depending on if the integer is a prime. Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. Requirements: You can assume you will be given an integer input. You can not assume that the integer will be only positive.
Read More
How to Calculate Minutes to Midnight in Java
February 18, 2022
The challenge Write a function minutesToMidnight(d) that will take a date object as the parameter. Return the number of minutes in the following format: “x minute(s)” You will always get a date object with of today with a random timestamp. You have to round the number of minutes. Milliseconds don’t matter!Some examples: 10.00 am => "840 minutes" 23.59 pm => "1 minute" The solution in Java code Option 1: import java.
Read More
How to Change the Timestamp of a File on Mac/Linux
February 17, 2022
If you have a file on your machine, and you want to change the created/modified time/date stamp, then you can use the touch command. touch -t 202202011308.57 someFile.jpg In the above example, the timestamp will be changed to <meta charset="utf-8">2022-02-01 13:08:57. Simply remove all non-decimal characters and place a period before the seconds.
Read More
How to Round up to the Next Multiple of 5 in Python
February 16, 2022
The challenge Given an integer as input, can you round it to the next (meaning, “higher”) multiple of 5? Examples: input: output: 0 -> 0 2 -> 5 3 -> 5 12 -> 15 21 -> 25 30 -> 30 -2 -> 0 -5 -> -5 etc. Input may be any positive or negative integer (including 0). You can assume that all inputs are valid integers. The solution in Python code Option 1:
Read More
How to get the Sum of the First nth Term of a Series in Java
February 15, 2022
The challenge Your task is to write a function that returns the sum of the following series up to nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... Rules: You need to round the answer to 2 decimal places and return it as String. If the given value is 0 then it should return 0.00 You will only be given Natural Numbers as arguments. Examples: (Input –> Output) 1 --> 1 --> "1.
Read More
How to satisfy Wilson Primes in Python
February 14, 2022
The challenge Wilson primes satisfy the following condition. Let P represent a prime number. Then ((P-1)! + 1) / (P * P) should give a whole number. Your task is to create a function that returns true if the given number is a Wilson prime. The solution in Python code Option 1: def am_i_wilson(n): return n in (5, 13, 563) Option 2: def am_i_wilson(n): if n < 2 or not all(n % i for i in xrange(2, n)): return False import math return (math.
Read More
How to Boot an EC2 with a WebServer Setup
February 13, 2022
Create a new AWS EC2 instance, and set the User Script to the following: #!/bin/bash sudo su yum update -y yum install -y httpd.x86_64 systemctl start httpd.service systemctl enable httpd.service echo "<h1>Serving from $(hostname -f)</h1>" > /var/www/html/index.html
Read More
Writing a Sleigh Authentication in Python
February 12, 2022
The challenge Christmas is coming and many people dreamed of having a ride with Santa’s sleigh. But, of course, only Santa himself is allowed to use this wonderful transportation. And in order to make sure, that only he can board the sleigh, there’s an authentication mechanism. Your task is to implement the authenticate() method of the sleigh, which takes the name of the person, who wants to board the sleigh and a secret password.
Read More
Solving for Multiple of Index in Python
February 11, 2022
The challenge Return a new array consisting of elements which are multiple of their own index in input array (length > 1). Examples: [22, -6, 32, 82, 9, 25] => [-6, 32, 25] [68, -1, 1, -7, 10, 10] => [-1, 10] [-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-85, 72, 0, 68] The solution in Python code Option 1: def multiple_of_index(l): return [l[i] for i in range(1, len(l)) if l[i] % i == 0] Option 2:
Read More
How to Find an item’s Alphabet Position in Python
February 10, 2022
The challenge When provided with a letter, return its position in the alphabet. Input :: “a” Ouput :: “Position of alphabet: 1” The solution in Python code Option 1: def position(alphabet): return "Position of alphabet: {}".format(ord(alphabet) - 96) Option 2: from string import ascii_lowercase def position(char): return "Position of alphabet: {0}".format( ascii_lowercase.index(char) + 1) Option 3: def position(alphabet): return "Position of alphabet: %s" % ("abcdefghijklmnopqrstuvwxyz".find(alphabet) + 1) Test cases to validate our solution import test from solution import position @test.
Read More
How to Keep up the Hoop in Java
February 9, 2022
The challenge Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message 🙂 If Alex gets 10 or more hoops, return the string “Great, now move on to tricks”. If he doesn’t get 10 hoops, return the string “Keep at it until you get it”.
Read More
Will there be Enough Space in Java
February 8, 2022
The challenge Bob is working as a bus driver. However, he has become extremely popular amongst the city’s residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not having enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers. The task: You have to write a function that accepts three parameters:
Read More
How to Swap Node Pairs In Linked List in Java
February 7, 2022
The challenge If you are given the head node in a linked list, write a method that swaps each pair of nodes in the list, then returns the head node of the list. Example: if you are given a list ordered A,B,C,D the resulting list should be B,A,D,C. The list will be composed of Nodes of the following specification: public class Node { private String value; public Node next; public Node(String value) { this.
Read More
How to Solve ‘Finding Neo’ in Java
February 6, 2022
The challenge Neo is somewhere in the Matrix. public interface Matrix { public int size(); public int get(int x, int y); } You are Morpheus, and your job is to find him. public class Morpheus { public int[] find(Matrix matrix, int neo) { // return Neo's x and y coordinates as a two-element array } } You will need a good search strategy – the matrix is huge! But it is controlled by machines, so it is also very orderly.
Read More
How to Solve a Pandigital Sequence in Java
February 5, 2022
The challenge In mathematics, a pandigital number is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10. For simplification, in this challenge, we will consider pandigital numbers in base 10 and with all digits used exactly once. The challenge is to calculate a sorted sequence of pandigital numbers, starting at a certain offset and with a specified size.
Read More
How to get Meta-Data information from an AWS EC2 Instance
February 4, 2022
If you need to query meta-data information from your running EC2 instance, you can curl the following location: curl http://169.254.169.254/latest/meta-data This will provide a list of all information that can be retrieved. Say you want to get the local IPv4 address, this can be done as follows: curl http://169.254.169.254/latest/meta-data/local-ipv4 You can also get JSON blocks of information back, such as querying the IAM Info: curl http://169.254.169.254/latest/meta-data/iam/info
Read More
How to write a Lazy Repeater Helper in Python
February 3, 2022
The challenge The make_looper() function takes a string (of non-zero length) as an argument. It returns a function. The function it returns will return successive characters of the string on successive invocations. It will start back at the beginning of the string once it reaches the end. Examples: abc = make_looper('abc') abc() # should return 'a' on this first call abc() # should return 'b' on this second call abc() # should return 'c' on this third call abc() # should return 'a' again on this fourth call The solution in Python code Option 1:
Read More
How to write a String Case Conversion Helper in Python
February 2, 2022
The challenge In this challenge, you will make a function that converts between camelCase, snake_case, and kebab-case. You must write a function that changes to a given case. It must be able to handle all three case types: change_case("snakeCase", "snake") # "snake_case" change_case("some-lisp-name", "camel") # "someLispName" change_case("map_to_all", "kebab") # "map-to-all" change_case("doHTMLRequest", "kebab") # "do-h-t-m-l-request" change_case("invalid-inPut_bad", "kebab") # None change_case("valid-input", "huh???") # None change_case("", "camel") # "" Your function must deal with invalid input as shown, though it will only be passed strings.
Read More
How to create Interleaving Arrays in Python
February 1, 2022
The challenge Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed-in arguments. If one of them is shorter than the others, the result should be padded with empty elements. Examples: interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) == [] The solution in Python code Option 1:
Read More
How to Find the Largest product in a Series in Python
January 31, 2022
The challenge Complete the greatestProduct method so that it’ll find the greatest product of five consecutive digits in the given string of digits. Example: greatestProduct("123834539327238239583") # should return 3240 The input string always has more than five digits. The solution in Python code Option 1: from itertools import islice from functools import reduce def greatest_product(n): numbers=[int(value) for value in n] result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)] return max(result) Option 2:
Read More
How to Calculate the Least Common Multiple in Python
January 30, 2022
The challenge Write a function that calculates the least common multiple of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return 1. The solution in Python code Option 1: from math import gcd def lcm(*args): lcm=1 for x in args: if x!=0: lcm=lcm*x//gcd(lcm,x) else: lcm=0 return lcm Option 2: def lcm(*args): gcd = lambda m,n: m if not n else gcd(n,m%n) return reduce( lambda x, y: x*y/gcd(x, y), args) Option 3:
Read More
How to Solve Caesar Cipher Helper in Python
January 29, 2022
The challenge Write a class that, when given a string, will return an uppercase string with each letter shifted forward in the alphabet by however many spots the cipher was initialized to. Example: c = CaesarCipher(5); # creates a CipherHelper with a shift of five c.decode('BFKKQJX') # returns 'WAFFLES' If something in the string is not in the alphabet (e.g. punctuation, spaces), simply leave it as is. The shift will always be in the range of [1, 26].
Read More
How to Write Out Numbers in Python
January 28, 2022
The challenge Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999. Examples: number2words(0) ==> "zero" number2words(1) ==> "one" number2words(9) ==> "nine" number2words(10) ==> "ten" number2words(17) ==> "seventeen" number2words(20) ==> "twenty" number2words(21) ==> "twenty-one" number2words(45) ==> "forty-five" number2words(80) ==> "eighty" number2words(99) ==> "ninety-nine" number2words(100) ==> "one hundred" number2words(301) ==> "three hundred one" number2words(799) ==> "seven hundred ninety-nine" number2words(800) ==> "eight hundred" number2words(950) ==> "nine hundred fifty" number2words(1000) ==> "one thousand" number2words(1002) ==> "one thousand two" number2words(3051) ==> "three thousand fifty-one" number2words(7200) ==> "seven thousand two hundred" number2words(7219) ==> "seven thousand two hundred nineteen" number2words(8330) ==> "eight thousand three hundred thirty" number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine" number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight" The solution in Python code Option 1:
Read More
How to do Base64 Encoding in Python
January 27, 2022
The challenge Create a function that converts the value of the String to and from Base64 using the ASCII character set. Do not use built-in functions. Examples: # should return 'dGhpcyBpcyBhIHN0cmluZyEh' to_base_64('this is a string!!') # should return 'this is a string!!' from_base_64('dGhpcyBpcyBhIHN0cmluZyEh') You can learn more about Base64 encoding and decoding here. The solution in Python code Option 1: CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; def to_base_64(string): padding = 3 - len(string) % 3 if len(string) % 3 else 0 binary = ''.
Read More
How to Calculate Transport on Vacation in Java
January 26, 2022
The challenge After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you. You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers. Every day you rent the car costs $40.
Read More
Playing with the letter ‘E’ in Java
January 25, 2022
The challenge Given String str, return: If given String doesn’t contain any “e”, return: “There is no “e”.” If given String is empty, return empty String. If given String is `null` The solution in Java code Option 1: public class WithoutLetterE { public static String findE(String str){ if (str==null) return null; if (str.equals("")) return ""; int len = str.length() - str.toLowerCase().replaceAll("e", "").length(); if (len > 0) return String.valueOf(len); if (!str.contains("e")) return "There is no \"e\".
Read More
How to Sum the Average for NBA Players in Golang
January 24, 2022
The challenge Write a function, called sumPPG, that takes two NBA player objects/struct/Hash/Dict/Class and sums their PPG Examples: iverson := NBAPlayer{ Team: "76ers", Ppg: 11.2 } jordan := NBAPlayer{ Team: "bulls", Ppg: 20.2 } SumPpg(iverson, jordan) // => 31.4 The solution in Golang Option 1: package solution type NBAPlayer struct { Team string Ppg float64 } func SumPpg(playerOne, playerTwo NBAPlayer) float64 { return playerOne.Ppg+playerTwo.Ppg } Option 2: package solution type NBAPlayer struct { Team string Ppg float64 } func SumPpg(a, b NBAPlayer) float64 { return float64(a.
Read More
How to Compute a Cube as Sums in Golang
January 23, 2022
The challenge You will be given a number n (where n >= 1) and your task is to find n consecutive odd numbers whose sum is exactly the cube of n. **Mathematically: ** cube = n ** 3 sum = a1 + a2 + a3 + ….. + an sum == cube a2 == a1 + 2, a3 == a2 + 2, ……. For example: FindSummands(3) == []int{7,9,11} // ..because 7 + 9 + 11 = 27, the cube of 3.
Read More
The Deaf Rats of Hamelin Challenge in Java
January 22, 2022
The challenge The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town. But some of the rats are deaf and are going the wrong way! Task How many deaf rats are there? Legend P = The Pied Piper O~ = Rat going left ~O = Rat going right Examples ex1 ~O~O~O~O P has 0 deaf rats ex2 P O~ O~ ~O O~ has 1 deaf rat ex3 ~O~O~O~OP~O~OO~ has 2 deaf rats The solution in Java code Option 1:
Read More
How to Find the Next Perfect Square in Java
January 21, 2022
The challenge You might know some pretty large perfect squares. But what about the NEXT one? Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is non-negative.
Read More
How to Find the Unique String in Python
January 20, 2022
The challenge There is an array of strings. All strings contain similar letters except one. Try to find it! find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter. E.g. A string that contains only spaces is like an empty string. It’s guaranteed that the array contains more than 3 strings.
Read More
How to convert a PascalCase string into snake_case in Python
January 19, 2022
The challenge Complete the function/method so that it takes a PascalCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If the method gets a number as input, it should return a string. Examples: "TestController" --> "test_controller" "MoviesAndBooks" --> "movies_and_books" "App7Test" --> "app7_test" 1 --> "1" The solution in Python code Option 1: import re def to_underscore(string): return re.sub(r'(.)([A-Z])', r'\1_\2', str(string)).lower() Option 2: def to_underscore(string): string = str(string) camel_case = string[0].
Read More
How to Convert a Hex String to RGB in Python
January 18, 2022
The challenge When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements: Accepts a case-insensitive hexadecimal color string as its parameter (ex. "#FF9933" or "#ff9933") Returns a Map<String, int> with the structure {r: 255, g: 153, b: 51} where r, g, and b range from 0 through 255 Note: your implementation does not need to support the shorthand form of hexadecimal notation (ie "#FFF")
Read More
How to Create a Hashtag Generator in Python
January 17, 2022
The challenge Write a hashtag generator function that takes a string and returns a #HashCodeString of it. The hashtag generator should perform the following tasks. Follow these rules: It must start with a hashtag (#). All words must have their first letter capitalized. If the final result is longer than 140 chars it must return false. If the input or the result is an empty string it must return false. Examples: " Hello World " => "#HelloWorld" "" => false The solution in Python code Option 1:
Read More
How to Move Zeros to the End in Python
January 16, 2022
The challenge Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0] The solution in Python code Option 1: def move_zeros(arr): l = [i for i in arr if isinstance(i, bool) or i!=0] return l+[0]*(len(arr)-len(l)) Option 2: def move_zeros(array): return sorted(array, key=lambda x: x==0 and type(x) is not bool) Option 3:
Read More
Regex for Gregorian Date Validation in Python
January 15, 2022
The challenge Write a regular expression that validates the gregorian date in the format “DD.MM.YYYY” Correct date examples: "23.12.2008" "01.08.1994" Incorrect examples: "12.23.2008" "01-Aug-1994" " 01.08.1994" Notes: maximum length of validator is 400 characters to avoid hardcoding. (shortest solution to date is 170 characters) validator should process leap days (February, 29) correctly. the date is Gregorian, it’s important to determine if year is leap: https://en.wikipedia.org/wiki/Gregorian_calendar The solution in Python code Option 1:
Read More
How to Create Your Own Python Split Function
January 14, 2022
The challenge Write your own implementation of the built-in split function in Python. The following rules must be adhered to: the function cannot use, in any way, the original split or rsplit functions, the new function must be a generator, it should behave as the built-in split, so it will be tested that way — think of split() and split('') The solution in Python Option 1: import re def my_very_own_split(string, delimiter = None): if delimiter == '': raise ValueError('empty delimiter') if delimiter == None: delimiter = '\s+' else: delimiter = re.
Read More
How to create a Domain Name Validator in Python
January 13, 2022
The challenge Create a domain name validator mostly compliant with RFC 1035, RFC 1123, and RFC 2181 The following rules apply: Domain name may contain subdomains (levels), hierarchically separated by . (period) character Domain name must not contain more than 127 levels, including top level (TLD) Domain name must not be longer than 253 characters (RFC specifies 255, but 2 characters are reserved for trailing dot and null character for root level) Level names must be composed out of lowercase and uppercase ASCII letters, digits and – (minus sign) character Level names must not start or end with – (minus sign) character Level names must not be longer than 63 characters Top level (TLD) must not be fully numerical Additionally:
Read More
How to start Java Jar as Service on Linux
January 12, 2022
If you have a Java Jar file, you can run it as a service under Linux/Ubuntu. sudo ln -s /var/www/japi-0.0.1-SNAPSHOT.jar /etc/init.d/japi Now you can use the default init.d verbs [start,stop,restart,status]. Additionally, init.d also gives the following. Usage for your new init.d service Usage: /etc/init.d/japi {start|stop|force-stop|restart|force-reload|status|run} Start Java Service sudo /etc/init.d/japi start Stop Java Service sudo /etc/init.d/japi stop Restart Java Service sudo /etc/init.d/japi restart Status Information sudo /etc/init.d/japi status
Read More
How to write a validDate Regex in Python
January 11, 2022
The challenge Your task is to write a regular expression (regex) that will match a string only if it contains at least one valid date, in the format [mm-dd] (that is, a two-digit month, followed by a dash, followed by a two-digit date, surrounded by square brackets). You should assume the year in question is not a leap year. Therefore, the number of days each month should have are as follows:
Read More
How to Validate Passwords with Regex in Python
January 10, 2022
The challenge You need to write regex that will validate a password to make sure it meets the following criteria: At least six characters long contains a lowercase letter contains an uppercase letter contains a number Valid passwords will only be alphanumeric characters. The solution in Python code Option 1: from re import compile, VERBOSE regex = compile(""" ^ # begin word (?=.*?[a-z]) # at least one lowercase letter (?=.*?[A-Z]) # at least one uppercase letter (?
Read More
How to create a Coordinates Validator in Golang
January 9, 2022
The challenge You need to create a function that will validate if given parameters are valid geographical coordinates. Valid coordinates look like the following: “23.32353342, -32.543534534”. The return value should be either true or false. Latitude (which is the first float) can be between 0 and 90, positive or negative. Longitude (which is the second float) can be between 0 and 180, positive or negative. Coordinates can only contain digits, or one of the following symbols (including space after the comma)
Read More
How to Validate ISBN-10 numbers in Golang
January 8, 2022
The challenge ISBN-10 identifiers are ten digits long. The first nine characters are digits 0-9. The last digit can be 0-9 or X, to indicate a value of 10. An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero. For example: ISBN : 1 1 1 2 2 2 3 3 3 9 position : 1 2 3 4 5 6 7 8 9 10 This is a valid ISBN, because:
Read More
How to Create a Java GUI App that shows the Logged-in User and Hostname
January 7, 2022
Create a new file called Application.java and paste the following: import javax.swing.*; import java.net.InetAddress; import java.net.UnknownHostException; public class Application { public static void main(String...args) throws UnknownHostException { JFrame frame = new JFrame("Sample App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); String user = System.getProperty("user.name"); String host = InetAddress.getLocalHost().getHostName(); JTextArea txt = new JTextArea(); txt.setText( "\n" + " User: "+user+"\n" + " Host: "+host+"\n" ); frame.getContentPane().add(txt); frame.setVisible(true); } } Now open the terminal/command-line and type: java Application.
Read More
How to view a Terraform Module’s Output
January 6, 2022
An output in Terraform is a way to view the result of an action that has been performed, or resource that has been created. Let’s say that you have some code to create a Load Balancer, or Assign a Public IP. Once this action is complete, the output block will have access to this created value. An simple output example outputs.tf output "instance_ips" { value = aws_instance.web.*.public_ip } output "lb_address" { value = aws_alb.
Read More
How to Count the Characters in Python
January 5, 2022
The challenge The goal of this challenge is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. Examples: count_char("fizzbuzz","z") # 4 count_char("Fancy fifth fly aloof","f") # 5 The character can be any alphanumeric character. The solution in Python code Option 1: def count_char(haystack, needle): count = 0 for c in haystack: if c.
Read More
How to Install Cuda driver for Nvidia on Ubuntu
January 4, 2022
If you have just upgraded Ubuntu on your AWS g4dn instance and need to install/reinstall Cuda drivers for your Nvidia chipset, then you can run the following: Install Cuda drivers for Nvidia on Ubuntu wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/ /" sudo apt-get update sudo apt-get -y install cuda How to get the versions for your own setup Or follow the wizard here to generate the correct version numbers for your specific environment/platform:
Read More
How to List all Running Services on Ubuntu
January 3, 2022
If you need to view a list of all the services that are either running or stopped (or both) on an Ubuntu server, then you can use the following command: service --status-all This will print out a list of services that may look something like this: # service --status-all [ - ] acpid [ + ] apache-htcacheclean [ + ] apache2 [ + ] apparmor [ + ] apport [ + ] atd [ - ] console-setup.
Read More
[Solved] conflict: unable to remove repository reference in Docker
January 2, 2022
If you get the following error while trying to delete an image in Docker: Error response from daemon: conflict: unable to remove repository reference "some-image" (must force) - container 3ab4c18d2219 is using its referenced image 133c1827439a You may already have tried looking for the container, but it seems to not exist! How to Remove the Docker Container and Image This usually means that the Docker container has already terminated, and is why you won’t see it running.
Read More
How to Upgrade an Ubuntu Server
January 1, 2022
Upgrading an Ubuntu Server is quite easy, just follow the below commands: Option 1: Tldr; (just run the below!) sudo apt-get update && sudo apt-get upgrade sudo apt dist-upgrade sudo do-release-upgrade reboot Option 2: Follow the steps to Upgrade Ubuntu Server 1: Update the packages: Start by making sure that you have all the packages and dependencies ready locally before we upgrade sudo apt-get update && sudo apt-get upgrade 2: Update the dependencies for the distribution: sudo apt dist-upgrade
Read More
How to Solve Two-Sum in Java
December 31, 2021
The challenge Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2). For the purposes of this challenge, some tests may have multiple answers; any valid solutions will be accepted.
Read More
How to Sort the Gift Code in Java
December 30, 2021
The challenge Santa’s senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code. Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes!
Read More
How to get the Numericals of a String in Java
December 29, 2021
You are given an input string. For each symbol in the string if it’s the first character occurrence, replace it with a ‘1’, else replace it with the amount of times you’ve already seen it. Examples: input = "Hello, World!" result = "1112111121311" input = "aaaaaaaaaaaa" result = "123456789101112" There might be some non-ascii characters in the string. Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
Read More
How to Replace Noun Phrases with Pronouns in Golang
December 28, 2021
The challenge A Noun Phrase is a phrase that can be replaced by a pronoun [he/she/it]. For example, in the sentence: a girl ate the cookie “A girl” is a Noun Phrase, so we can say “she ate the cookie.” “The cookie” is also a Noun Phrase, so we can even say “she ate it.” Both of these Noun Phrases are made up of an auxialliary (aux) [the/a] followed by a Noun (N) [girl/cookie].
Read More
Maximum Positive Integer Rotations in Golang
December 27, 2021
The challenge Write function MaxRot(n) which given a positive integer n returns the maximum number you got doing rotations similar to the above example. So MaxRot is such as: MaxRot(56789) should return 68957 MaxRot(38458215) should return 85821534 Examples: Take a number: 56789. Rotate left, you get 67895. Keep the first digit in place and rotate left the other digits: 68957. Keep the first two digits in place and rotate the other ones: 68579.
Read More
How to “Dashatize It” in Java
December 26, 2021
The challenge Given a variable n, If n is an integer, Return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. If n is negative, then the negative sign should be removed. If n is not an integer, return an empty value. Ex: dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5' The solution in Java code Option 1: public class Solution { public static String dashatize(int num) { String n = String.
Read More
How to create a Nickname Generator in Python
December 25, 2021
The challenge Write a nickname generator function, nicknameGenerator that takes a string name as an argument and returns the first 3 or 4 letters as a nickname. The nickname generator should perform the following tasks. If the 3rd letter is a consonant, return the first 3 letters. nickname("Robert") # "Rob" nickname("Kimberly") # "Kim" nickname("Samantha") # "Sam" If the 3rd letter is a vowel, return the first 4 letters. nickname("Jeannie") # "Jean" nickname("Douglas") # "Doug" nickname("Gregory") # "Greg" If the string is less than 4 characters, return “Error: Name too short”.
Read More
Comparing Array Multiplicities in Java
December 24, 2021
The challenge Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the “same” elements, with the same multiplicities. “Same” means, here, that the elements in b are the elements in a squared, regardless of the order. Examples Valid arrays a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on.
Read More
How to Find the Sum of Angles in Golang
December 23, 2021
The challenge Find the total sum of internal angles (in degrees) in an n-sided simple polygon. N will be greater than 2. The solution in Golang Option 1: package solution func Angle(n int) int { return (n - 2) * 180 } Option 2: package solution func Angle(n int) (r int) { r = (n-2)*180 return } Option 3: package solution func Angle(n int) int { return (n/2-1) * 360 + n%2 * 180 } Test cases to validate our solution package solution_test import ( .
Read More
How to Find the Max Tree Node Value in Java
December 22, 2021
The challenge You are given a binary tree. Implement the method findMax which returns the maximal node value in the tree. For example, the maximum in the following Tree is 11. 7 / \ / \ 5 2 \ \ 6 11 /\ / 1 9 4 Note: Tree node values range is Integer MIN VALUE – Integer MAX VALUE constants. Tree can unbalanced and unsorted. Root node is always not null.
Read More
How to String Search with a Wildcard in Java
December 21, 2021
The challenge The method below is the most simple string search algorithm. It will find the first occurrence of a word in a text string. haystack = the whole text needle = searchword wildcard = _ find("strike", "i will strike down upon thee"); // return 7 The find method is already made. The problem is to implement wildcard(s) in the needle. If you have a _ in the needle it will match any character in the haystack.
Read More
How to get the AWS AccountID in Terraform
December 20, 2021
If you are automating AWS resources in Terraform, then you will want to not hardcode things as much as possible. Terraform makes it possible to pull the account_id from the local credentials. How to get the AccountID data attributes Create a data.tf file and place the following item in it: data "aws_caller_identity" "current" {} Now the account_id will be available to you within your standard code as follows: data.aws_caller_identity.current.account_id How to use the AccountID data attributes This can now be used in a module, or wherever you need to reference the account id:
Read More
Error creating AppStream Fleet – InvalidRoleException
December 19, 2021
If you get the following error when trying to run some Terraform: error creating Appstream Fleet (): InvalidRoleException: AppStream 2.0 encountered an error because your service role 'arn:aws:iam::<ACCOUNT_ID>:role/service-role/AmazonAppStreamServiceAccess' is invalid ..then you just need to run your IaC again, as the roles are automatically created when you first interact with the service. Alternatively, go and have a look at what has already been created in the AWS Console. What roles are required for AppStream?
Read More
How to Create AWS AppStream resources in Terraform
December 18, 2021
AWS AppStream has finally made its way into the Terraform AWS Provider. If you are using hashicorp/aws version 3.67 or above, then you can do the following: terraform { required_version = "~> 1.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 3.67" } } } provider "aws" { region = "eu-west-1" default_tags { tags = { Contact = "you@example.com" Environment = "dev" DeployedBy = "Automation:Terraform" } } } resource "aws_appstream_fleet" "example" { name = "ao-tmp-fleet-1" image_name = "Amazon-AppStream2-Sample-Image-02-04-2019" instance_type = "stream.
Read More
How to Stop a Goroutine in Golang
December 17, 2021
It’s possible to stop a Goroutine by sending a value into it via a signal channel: exit := make(chan bool) go func() { for { select { case <- exit: return default: // Perform some tasks } } }() // Exit the Goroutine exit <- true As an alternative, you could also use a WaitGroup and range over it: package main import ( "fmt" "sync" ) func main() { var wg sync.
Read More
How to Create an Empty Branch in Git
December 16, 2021
If you need to create an empty branch in git, you can follow one of the below options. If you are using git version 2.27 or newer, then follow the switch route (option 1) below, otherwise fall back to the older way, using checkout and delete (option 2). Newer way – Using switch: git switch --orphan <new branch> git commit --allow-empty -m "Initial commit on orphan branch" git push -u origin <new branch> Older way – Using checkout and delete: git checkout --orphan <new branch> git rm -rf .
Read More
Get the Consonant Value in Java
December 15, 2021
The challenge Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except "aeiou". We shall assign the following values: a = 1, b = 2, c = 3, .... z = 26. For example, for the word “zodiacs”, let’s cross out the vowels. We get: “z o d ia cs” -- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22.
Read More
How to Check for Factor in Python
December 14, 2021
The challenge This function should test if the factor is a factor of base. Return true if it is a factor or false if it is not. About factors Factors are numbers you can multiply together to get another number. 2 and 3 are factors of 6 because: 2 * 3 = 6 You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor.
Read More
Understanding Bitwise Operators in Python
December 13, 2021
There are 6 binary/bitwise operators in Python: Complement/Not (~) And (&) Or (|) XOR (^) Left Shift (<<) Right Shift (>>) A fantastic python method to help us along our journey is bin(). The bin function will return a binary representation of a base 10 integer we pass to it. >>> bin(1) '0b1' >>> bin(5) '0b101' Now let’s explore the 6 bitwise operators by learning a bit about each of them.
Read More
Word Values Challenge in Java
December 12, 2021
The challenge Given a string "abc" and assuming that each letter in the string has a value equal to its position in the alphabet, our string will have a value of 1 + 2 + 3 = 6. This means that: a = 1, b = 2, c = 3 ....z = 26. You will be given a list of strings and your task will be to return the values of the strings as explained above multiplied by the position of that string in the list.
Read More
How to update/upgrade all Homebrew packages
December 11, 2021
If you use Homebrew – and you probably should if you’re on a Mac – then you have probably installed various different applications and packages as time went on. It’s probably likely that by now, you have many different packages that are out of date and need to be upgraded to their newer versions. Luckily, Homebrew makes it very easy to upgrade everything; run the following command to upgrade everything.
Read More
[Solved] FirebaseError: Missing or insufficient permissions
December 10, 2021
Using Firebase and get the following error in the console? Uncaught Error in onSnapshot: FirebaseError: Missing or insufficient permissions.<br>at new FirestoreError (index.cjs.js:x) How to fix the Missing or Insufficient Permissions Error Option 1: Change rules (Recommended) Login to Firebase Go to Database -> Rules Change: service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } } to: service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.
Read More
[Solved] Error: Cannot find module ‘../lib/cli.js’
December 9, 2021
If you try and run npm i and get Error: Cannot find module '../lib/cli.js', then you can easily fix the problem by running the following. How does the error look? Error: Cannot find module '../lib/cli.js' Require stack: - /usr/local/lib/node_modules/npm/bin/npm-cli.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:999:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:2:1) at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) { code: 'MODULE_NOT_FOUND', requireStack: [ '/usr/local/lib/node_modules/npm/bin/npm-cli.
Read More
How to use Git Commit in GitHub Actions
December 8, 2021
If you’ve tried to use git commit in GitHub Actions before, you may have come across the following error messages: Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: empty ident name (for <runner@fv-az191-422.gxxxxxjfkf.bx.internal.cloudapp.net>) not allowed Author identity unknown This can easily be fixed by doing the following:
Read More
[Solved] Error acquiring the state lock in Terraform
December 7, 2021
If you have been handed the Acquiring state lock error message about ConditionalCheckFailedException: The conditional request then you have 2 options for fixing it! The error looks something like this: Acquiring state lock. This may take a few moments... ╷ │ Error: Error acquiring the state lock │ │ Error message: ConditionalCheckFailedException: The conditional request │ failed │ Lock Info: │ ID: 3324a6cb-7401-3194-d650-fxxxxxx3864 │ Path: xxxx-terraformstate-nonprod/env:/xxxx/terraform.tfstate │ Operation: OperationTypeApply │ Who: root@ip-100-65-2-165 │ Version: 1.
Read More
How to Install Chocolatey on Windows PowerShell
December 6, 2021
Chocolatey is a software management automation for Windows that wraps installers, executables, zips, and scripts into compiled packages chocolatey.org How to Install Chocolatey in PowerShell Open PowerShell (Run PowerShell in Administrator mode) and paste the following script: Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) This will install Chocolatey, and get you to the point of being able to install packages. Install some Packages with Chocolatey Some example packages to install:
Read More
How to run PowerShell in Administrator Mode
December 5, 2021
Some PowerShell commands require elevated permissions to complete. To do this, you must first open PowerShell in Administrator Mode. Steps to Run PowerShell as an Administrator Click Start (super key) Type powershell Right-click on Windows PowerShell and select Run as administrator or; Select Run as Administrator from the right-hand-side menu. (Run as Administrator) The application will now be started in Administrator Mode.
Read More
[Solved] Permission denied @ apply2files – /usr/local/lib/node_modules/expo-cli/node_modules/extglob/lib
December 4, 2021
If you have recently upgraded your MacOS operating system, you may get the following error in your terminal when installing some Homebrew packages: Error: Permission denied @ apply2files - /usr/local/lib/node_modules/expo-cli/node_modules/.bin/detect-libc How to solve the Permissions Denied problem Simply run the following command in your terminal: sudo chown -R $(whoami):admin /usr/local/* \ && sudo chmod -R g+rwx /usr/local/* Or change the user directly: sudo chown -R ${LOGNAME}:staff /usr/local/lib/node_modules
Read More
How to Fix “is not authorized to create managed-rule” in AWS Step Functions
December 3, 2021
If you have ever received the following error is not authorized to create managed-rule when running a Step Function through Terraform’s AWS Provider, then you may have jumped through many different hoops trying to figure out what was wrong. What is the Quick Fix? Open the role in IAM and attach the CloudWatchEventsFullAccess AWS managed policy to the permissions policies. Need More Information? IAM Role Principal Policy required to AssumeRole { "Version" : "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Principal" : { "Service" : "states.
Read More
How to add Account Condition to AWS Lambda Permissions in Terraform
December 2, 2021
If you need to lock an AWS Lambda function down to a source account for security reasons (PCI.Lambda.1) then you can do so by using the source_account option of the aws_lambda_permission Terraform resource type. resource "aws_lambda_permission" "do_something_with_bucket" { statement_id = "AllowExecutionFromS3Bucket" action = "lambda:InvokeFunction" function_name = module.do_something_with_bucket.arn principal = "s3.amazonaws.com" source_arn = var.source_bucket_arn source_account = var.account_id # <---------- here } We have stored the account_id in a variable so that it can be updated when we initialize our Terraform context:
Read More
How to AssumeRole in Terraform LocalExec Provisioner Block
December 1, 2021
I needed to execute a Terraform null_resource provisioner (local-exec) block to run an awscli command, but assume a role passed down to it. There was no obvious way to pass the credentials to it, or assume a role directly, so the following workaround did the trick: AssumeRole and Pass LocalExec Provisioner Command resource "null_resource" "start-appstream-fleet" { provisioner "local-exec" { interpreter = ["/bin/bash", "-c"] command = <<EOF set -e CREDENTIALS=(`aws sts assume-role \ --role-arn ${local.
Read More
Split and then add both sides of an array together in Java
November 30, 2021
The challenge You will receive an array as a parameter that contains 1 or more integers and a number n. Here is a little visualization of the process: Step 1: Split the array in two:[1, 2, 5, 7, 2, 3, 5, 7, 8] / \ [1, 2, 5, 7] [2, 3, 5, 7, 8] Step 2: Put the arrays on top of each other: [1, 2, 5, 7] [2, 3, 5, 7, 8] Step 3: Add them together:[2, 4, 7, 12, 15] Repeat the above steps n times or until there is only one number left, and then return the array.
Read More
Highest Rank Number in an Array in Golang
November 29, 2021
The challenge Complete the method which returns the number which is most frequent in the given input array. If there is a tie for the most frequent number, return the largest number among them. Note: no empty arrays will be given. Examples [12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12 [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3 The solution in Golang Option 1:
Read More
Sort Words by Position Index in Java
November 28, 2021
The challenge Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Read More
How to get the Current Machine Name and Logged In User in Java
November 27, 2021
It’s very easy to get the current machine name and logged in user using Java. Get the Currently Logged in User String username = System.getProperty("user.name"); System.out.println("Username logged in: " + username); This is also platform-independent. Get the Hostname of the Machine java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); System.out.println("Hostname of local machine: " + hostname);
Read More
How to set ZSH as your default Shell
November 26, 2021
You may have installed ZSH and every-time you open your terminal, it opens BASH by default. How do you set your default shell to open as ZSH? It’s easy, you can just use the change shell command: chsh -s $(which zsh)
Read More
How to Base64 Encode/Decode in the Terminal/CLI
November 25, 2021
If you need to either Encode or Decode a Base64 value, there are many ways to achieve this, one of them is directly from your commandline itself! How to Encode a Base64 value in CLI echo 'This is a test' | base64 This will output a base64 encoded value of VGhpcyBpcyBhIHRlc3QK How to Decode a Base64 value in CLI echo VGhpcyBpcyBhIHRlc3QK | base64 --decode This will output a decoded value from our base64 value of This is a test
Read More
How to Enable Syntax Highlighting in Vim
November 24, 2021
There are a few different ways to enable Syntax Highlighting in Vim. Option 1 – Edit ~/.vimrc Add syntax on to your local ~/.vimrc echo "syntax on" >> ~/.vimrc Option 2 – Override System Vim (Mac) cd vim --version xcode-select --install ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew doctor brew install vim --override-system-vim vim --version Option 3 – Toggle in Vim You can use Vim Commands while in Vim itself: :syntax on
Read More
How to Create an AWS Security Group in Terraform - Securing AWS Resources with Terraform Security Groups
November 23, 2021
Security groups are a critical component for securing resources in AWS. This guide will show you how to create and manage security groups in AWS using Terraform, a popular infrastructure-as-code tool . Overview of AWS Security Groups Security groups act as a firewall to control inbound and outbound traffic to AWS resources like EC2 instances, RDS databases, ELB load balancers, etc. They operate at the instance level, not the subnet level.
Read More
How to Create an AWS Security Group in CloudFormation
November 22, 2021
Below is a simple CloudFormation script block to create a Security Group in AWS. Resources: SampleAppAppstreamSG: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Inbound and outbound traffic for service GroupName: 'sampleappsg-123' VpcId: !Ref vpcid Tags: - Key: "Name" Value: "Sample App Security Group" SecurityGroupEgress: - IpProtocol: "-1" FromPort: 0 ToPort: 0 CidrIp: 10.0.0.0/8 SecurityGroupIngress: - IpProtocol: "-1" FromPort: 0 ToPort: 0 CidrIp: 10.0.0.0/8 You can read up more about all the possible arguments in the AWS Security Group CloudFormation Reference.
Read More
How to provide Default Values for AWS CloudFormation Parameters
November 21, 2021
AWS CloudFormation is very useful for creating template-able infrastructure definitions. One of the sections of a template, is the Input Parameters, or simply Parameters as CloudFormation calls it. This is a section block that llows for user defined variables to be consumed by the template. When testing, it can be useful to specify default values here. This can be achieved by adding the Default key and setting a value. Parameters: environment: Type: String Default: DEV vpcid: Type: String Default: "vpc-123456789123456a"
Read More
How to Validate an AWS CloudFormation Template
November 20, 2021
The AWS CLI comes with a useful subcommand to validate a CloudFormation template. Simply run the following to validate a CloudFormation template file: aws cloudformation validate-template --template-body file://cf-infra.yaml Remember to swap out cf-infra.yaml with your CloudFormation template file.
Read More
How to Reverse Sort Integers in Go
November 19, 2021
The challenge The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age]. The order of the numbers passed in could be any order. The array will always include at least 2 items. If there are two or more oldest age, then return both of them in array format.
Read More
How to view the Encoded Authorization Failure Message in AWS
November 18, 2021
You may come across a message that reads similar to the following: <meta charset="utf-8">Encoded authorization failure message A full message, will look something like: API: ec2:CreateSecurityGroup You are not authorized to perform this operation. Encoded authorization failure message: B2UTpuAS30_naB5rE3Dw5v2ENy-V5w3H0wmt6rfE8hrpUz2dCIiA5XcBCtzo4cipk_JiGxAKCvlZQy0Rr2Xi3Fg2pKdkvojgn5LOZJzVroFPqMbyJguCJWxxxxxxxDNOZGGGlT2PIxTnqLQ561_piXzApfRL2kv-cYhxnuNwJWEeX8-N15mDcswhUyoV5pYtehdupp5umWZt8mcAiatlf7JIo0Q6tobs7Iw22tWTofMIZW-qkPtrTg7YrrY2--kTF3Q9qQBJw6gjr_QGznd9Fh0OMF_dCLC70bLRg5Jtxn5HyLxZWu9sC-y6x1tebYRokj32NVqr4h8pklocEKe6iqM88xV1cHJXcstP_gvoFf22yFmIll7DcE5Llsn-lD6bsB0QWWgy81m6_X0JW6s5ea4BD2nE1GM511BS20x-gGM65fm5z2SrjU09G-kmXngugnra135eY28qqjdvIl1Knb-KnEXzrtAj_DaAehx5HizwtIdi3_Yxxxxxxx_AmwgLBDZuqEL1BLZjClw7TtVjysGeO6WJyL2NMXN7Gtvzg2AL4q_z-ROH1xxxxxxxxxxx How to view the Encoded Message from AWS In your terminal/commandline, you need to paste the encoded message from above (your own one) into the following aws sts tool: aws sts decode-authorization-message --encoded-message <past_encoded_string_here> --query DecodedMessage --output text | jq '.
Read More
How to run/execute a program from Terraform
November 17, 2021
If you need to run a local application from your Terraform scripts, you can call out to the provisioner local-exec and issue the command syntax: resource "null_resource" "dig-aoms" { provisioner "local-exec" { # define your command below # this can be any application available in your terminal/commandline, # along with arguments command = "dig any andrewodendaal.com" } }
Read More
How to script AWS AppStream 2.0 ImageBuilder
November 16, 2021
AppStream (2.0) is a fully managed non-persistent desktop and application service for remotely accessing your work. The ImageBuilder forms the first stage in the creation and definition of an image that can be used to stream. You can use the AWS CLI to initiate the creation of an image in ImageBuilder: aws appstream create-image-builder \ --name <name> \ --image-name <image_name> \ --instance-type <instance_type> \ --vpc-config SubnetIds=<subnet_ids>,SecurityGroupIds=<security_group_ids> \ --iam-role-arn <iam_role_arn> \ --enable-default-internet-access Swap out the above items with your own values:
Read More
How to Reimplement the Unix Uniq Command in Golang
November 15, 2021
The challenge Implement a function which behaves like the uniq command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance. Example: ["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"] The solution in Golang Option 1: package uniq func Uniq(a []string) []string { array := []string{} for i, value := range a { if i == 0 { array = append(array, value) } else if a[i-1] !
Read More
How to install GraalVM on Mac
November 14, 2021
Install GraalVM with Homebrew Homebrew is the preferred way to install anything on your Mac. brew install graalvm/tap/graalvm-ce-java17 Install GraalVM without Homebrew Follow these 5 steps to get GraalVM installed on your Mac. Step1: Download the official binary: https://www.graalvm.org/downloads/ Unpack the archive into a folder. Step2: Move the folder into the JavaVirtualMachines directory: sudo mv graalvm-ce-java17-21.3.0 /Library/Java/JavaVirtualMachines sudo is required because /Library is a system directory. Step3: Verify the installation using the java_home utility:
Read More
How to Generate Random Integers with a Range in Java
November 13, 2021
Java comes with many different ways to generate random integers, even if you need to specify a lower and upper bound to constrain your required value for. Option 1 – ThreadLocalRandom Specify the min and max values: import java.util.concurrent.ThreadLocalRandom; int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); Option 2 – Random Between `` (inclusive) and the specified value (exclusive): import java.util.Random; Random rn = new Random(); int range = maximum - minimum + 1; int randomNum = rn.
Read More
How to create ArrayList from Array in Java
November 12, 2021
The problem If you have a traditional array, that looks something like the following: A[] array = {new A(1), new A(2), new A(3)}; And you would like to convert this to an ArrayList: ArrayList<Element> arraylist = ???; ..then you can do the following! The solution The technique new ArrayList<>(Arrays.asList(array)); How to use it Of course you could always simplify this one further directly as: List<ClassName> list = Arrays.asList(array) How to old Java If you are stuck in the old world of Java, you can fall back to:
Read More
How to Generate a Random AlphNumeric String in Linux/MacOS
November 11, 2021
If you need to generate a random AlphaNumeric string from the Linux/MacOS Command-Line, then you can use the following script: dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n' This can also be piped into a variable as follows: RANDOM_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') The above echo $RANDOM_ID will resemble something similar to: 90fa3bb51922eadc
Read More
How to check if a string is empty in Go
November 10, 2021
If you need to check if a string is empty in Go, then there are two possible ways to immediately verify this: Option 1 – Compare the length: if len(s) > 0 { // do something with string } Option 2 – Compare against blank: if s != "" { // do something with string }
Read More
How to read a file line by line in Go
November 9, 2021
If you need to read a file line by line in Go, then you can use the bufio package as follows: package main import ( "bufio" "fmt" "log" "os" ) func main() { file, err := os.Open("/path/to/file.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) } } Just note that the Scanner will throw an error if any line has a character count longer than 65536.
Read More
Floating-point Approximation in Golang
November 8, 2021
The challenge Consider the function f: x -> sqrt(1 + x) - 1 at x = 1e-15. We get: f(x) = 4.44089209850062616e-16 This function involves the subtraction of a pair of similar numbers when x is near 0 and the results are significantly erroneous in this region. Using pow instead of sqrt doesn’t give better results. A “good” answer is 4.99999999999999875... * 1e-16. Can you modify f(x) to give a good approximation of f(x) in the neighborhood of 0?
Read More
All the Ways to Divide an Array in Two in Golang
November 7, 2021
The challenge Write a function partlist that gives all the ways to divide an array of at least two elements into two non-empty parts. Each two non empty parts will be in a pair Each part will be in a string Elements of a pair must be in the same order as in the original array. Examples: a = ["az", "toto", "picaro", "zone", "kiwi"] --> [("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")] The solution in Golang Option 1:
Read More
How to check if a file exists in Go
November 6, 2021
If you need to check if a file exists using Go, then you can use one of the following methods, depending on the version of Go you may be using. If you are using Go >=1.13, then file, err := os.OpenFile("/path/to/file.txt") if errors.Is(err, os.ErrNotExist) { // The file does not exists } However, it is also possible to trap an error from an OpenFile attempt: file, err := os.OpenFile("/path/to/file.txt") if os.
Read More
How to convert a string value to an int in Go
November 5, 2021
If you need to convert a string to an int in Go, then you should use the strconv.Atoi function: package main import ( "strconv" "fmt" ) func main() { t := strconv.Atoi("123") fmt.Println(t) } Learn how to convert an int value to a string in Go .
Read More
How to convert an int value to string in Go
November 4, 2021
If you need to convert an int to a string in Go, then you should use the strconv.Itoa function: package main import ( "strconv" "fmt" ) func main() { t := strconv.Itoa(123) fmt.Println(t) } Learn how to convert a string value to an int in Go .
Read More
How to Efficiently Concatenate Strings in Go
November 3, 2021
If you are using a version of Go >= 1.10, then you should be using the newer strings.Builder pattern as follows: package main import ( "strings" "fmt" ) func main() { var sb strings.Builder for i := 0; i < 100; i++ { sb.WriteString("a") } fmt.Println(sb.String()) } For older version, you should be looking to use the bytes.Buffer instead: package main import ( "bytes" "fmt" ) func main() { var buffer bytes.
Read More
How to check if a map contains a key in Go
November 2, 2021
If you have a map in Go and want to only perform an action if it contains a certain key, then you can do so easily: if val, ok := myMap["someValue"]; ok { // your code here } The way this works is the conditional if statement checks to see if a value of someValue exists in the myMap map variable. If it exists, it assigns the key’s value to a val variable, and assigns the ok variable to a truthy boolean.
Read More
How to Remove all Vowels from a String in Java
November 1, 2021
The challenge Remove all vowels from the string. Vowels: a e i o u A E I O U The solution in Java code Option 1: public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("[aAeEiIoOuU]", ""); } } Option 2: public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("(?i)[aeiou]" , ""); } } Option 3: public class VowelRemoval { public static String disemvowel(String str) { return str .
Read More
How to Loop Forever in Golang
October 31, 2021
If you need to loop forever, or infinitely, in your Go code, then you have 2 options: Option 1: for { // your code here } Option 2: for true { // your code here } Just remember that you need to break out of this, otherwise it really will run forever! How to use in a Go Application package main func main() { // OPTION 1 for { // your code here } // OPTION 2 for true { // your code here } }
Read More
Understanding For Loops in Golang
October 30, 2021
In Golang a for loop is a way to loop through an iterable. The most basic For Loop i := 0 for i <= 3 { i = i + 1 } A classic For Loop for i := 7; i <= 9; i++ { // do something } For Loop without Conditions A for without a condition will loop forever, until either a break or return is hit. for { // do something break // kill the loop } When to use continue A continue will move to the next iteration of the loop
Read More
[Solved] go mod init: modules disabled by GO111MODULE=off
October 29, 2021
You’ve probably just tried to initialise a new Go module, and received the following error: go mod init: modules disabled by GO111MODULE=off; see 'go help modules' This usually happens after running a command like: go mod init github.com/<user>/<repo> What is GO111MODULE? From Go version 1.11, the way to deal with modules was revamped. Beforehand, it was required that you place all your Go code under a $GOPATH. Which many Go developers didn’t much like, as it seemed chaotic at best.
Read More
How to UpperCase the start of each Word in a String in Golang
October 28, 2021
The challenge The task is to take a string of lower-cased words and convert the sentence to upper-case the first letter/character of each word Example: this is the sentence would be This Is The Sentence The solution in Golang Option 1: As a first approach, we could loop through each word, and Title it before adding it back to a new string. Then make sure to trim any spaces before returning it.
Read More
How to Solve Max-Min Arrays in Java
October 27, 2021
The challenge You are given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc. For example: solve([15,11,10,7,12]) = [15,7,12,10,11] The first max is 15 and the first min is 7. The second max is 12 and the second min is 10 and so on.
Read More
How to Find the Smallest Integer in the Array in Golang
October 26, 2021
The challenge Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this challenge, that the supplied array will not be empty. The solution in Golang Option 1: package solution func SmallestIntegerFinder(numbers []int) int { curr := numbers[0] for _, v := range numbers { if v<curr { curr = v } } return curr } Option 2:
Read More
How to do Basic Encryption in Java
October 25, 2021
The challenge The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example ‘a’ + 1 would give us ‘b’, because ‘a’ value is 97 and ‘b’ value is 98. You will need to write a method that does exactly that – get a string as text and an int as the rule of manipulation, and should return encrypted text.
Read More
Forming Unique Array Combinations in Golang
October 24, 2021
The challenge You are given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray. For example: solve([[1,2],[4],[5,6]]) = 4, because it results in only 4 possibilites. They are [1,4,5],[1,4,6],[2,4,5],[2,4,6]. Make sure that you don’t count duplicates; for example solve([[1,2],[4,4],[5,6,6]]) = 4, since the extra outcomes are just duplicates. The solution in Golang Option 1:
Read More
How to Check if String is a Palindrome in Python
October 23, 2021
The challenge Write a function that checks if a given string (case insensitive) is a palindrome. The solution in Python Option 1: def is_palindrome(s): s = s.lower() for i, item in enumerate(s): if i<len(s)/2: if s[i]!=s[len(s)-i-1]: return False return True Option 2: def is_palindrome(s): s = s.lower() return s == s[::-1] Option 3: def is_palindrome(s): return s.lower()==s[::-1].lower() Test cases to validate our solution @test.describe('sample tests') def sample_tests(): test.assert_equals(is_palindrome('a'), True) test.assert_equals(is_palindrome('aba'), True) test.
Read More
How to Find the Squares in Java
October 22, 2021
The challenge Complete the function that takes an odd integer (0 < n < 1000000) which is the difference between two consecutive perfect squares, and return these squares as a string in the format "bigger-smaller". Examples 9 --> "25-16" 5 --> "9-4" 7 --> "16-9" The solution in Java code Option 1: public class Solution { public static String findSquares(final int n) { final long a = (n + 1) / 2; final long b = a - 1; return String.
Read More
How to Get Longest Word in Sentence in Java
October 21, 2021
The challenge When given a string of space-separated words, return the word with the longest length. If there are multiple words with the longest length, return the last instance of the word with the longest length. Example: 'red white blue' // returns string value of white 'red blue gold' // returns gold The solution in Java code Option 1: public class Solution { public static String longestWord(String wordString) { String longest = ""; for (String word: wordString.
Read More
How to Sum all the Integers in a String in Golang
October 20, 2021
The challenge Implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. Note: only positive integers will be tested. The solution in Golang Option 1: package solution import ( "fmt" "regexp" "strconv" ) func SumOfIntegersInString(strng string) int { re := regexp.MustCompile("[0-9]+") fmt.Println(re.FindAllString(strng, -1)) sum := 0 for _, i := range re.FindAllString(strng, -1) { number, _ := strconv.
Read More
How to Reverse a String in Golang
October 19, 2021
The challenge Complete the solution so that it reverses the string passed into it. 'world' => 'dlrow' 'word' => 'drow' The solution in Golang Option 1: package solution func Solution(word string) (out string) { for _, v := range word { out = string(v) + out } return } Option 2: package solution import "strings" func Solution(word string) string { var b strings.Builder for i:=len(word)-1; i>-1; i-- { b.WriteByte(word[i]) } return b.
Read More
Maximum Different of Int-Array in Java
October 18, 2021
The challenge You must implement a function that returns the difference between the biggest and the smallest value in a list(lst) received as a parameter. The list(lst) contains integers, which means it may contain some negative numbers. If the list is empty or contains a single element, return 0. The list(lst) is not sorted. maxDiff([1, 2, 3, 4]); // return 3, because 4 - 1 == 3 maxDiff([1, 2, 3, -4]); // return 7, because 3 - (-4) == 7 The solution in Java code Option 1:
Read More
Indexed Capitalization in Java
October 17, 2021
The challenge Given a string and an array of integers representing indices, capitalize all letters at the given indices. Example: capitalize("abcdef",[1,2,5]) = "aBCdeF" capitalize("abcdef",[1,2,5,100]) = "aBCdeF". There is no index 100. The input will be a lowercase string with no spaces and an array of digits. The solution in Java code Option 1: package solution; import java.util.*; public class Solution{ public static String capitalize(String s, int[] ind){ char[] chars = s.
Read More
How to Spacify a String in Java
October 16, 2021
The challenge Modify the spacify function so that it returns the given string with spaces inserted between each character. spacify("hello world") // returns "h e l l o w o r l d" The solution in Java code Option 1: import java.util.*; import java.util.stream.*; public class Spacify { public static String spacify(String str){ return Arrays.stream(str.split("")) .map(c -> c+" ") .collect(Collectors.joining()) .trim(); } } Option 2: public class Spacify { public static String spacify(String str){ return str.
Read More
How to Find the Last Digit of a Huge Number in Golang
October 15, 2021
The challenge For a given list [x1, x2, x3, ..., xn] compute the last (decimal) digit of x1 ^ (x2 ^ (x3 ^ (... ^ xn))). Example: last_digit({3, 4, 2}, 3) == 1 because 3 ^ (4 ^ 2) = 3 ^ 16 = 43046721. Beware: powers grow incredibly fast. For example, 9 ^ (9 ^ 9) has more than 369 millions of digits. lastDigit has to deal with such numbers efficiently.
Read More
Find the Maximum Length Difference between Lists/Arrays in Python
October 14, 2021
The challenge You are given two arrays a1 and a2 of strings. Each string is composed of letters from a to z. Let x be any string in the first array and y be any string in the second array. Find max(abs(length(x) − length(y))) If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None). Examples: a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"] a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"] mxdiflg(a1, a2) --> 13 The solution in Python Option 1:
Read More
How to Circularly Sort an Array in Golang
October 13, 2021
The challenge An array is circularly sorted if the elements are sorted in ascending order but displaced, or rotated, by any number of steps. Complete the function/method that determines if the given array of integers is circularly sorted. Examples: These arrays are circularly sorted (true): [2, 3, 4, 5, 0, 1] --> [0, 1] + [2, 3, 4, 5] [4, 5, 6, 9, 1] --> [1] + [4, 5, 6, 9] [10, 11, 6, 7, 9] --> [6, 7, 9] + [10, 11] [1, 2, 3, 4, 5] --> [1, 2, 3, 4, 5] [5, 7, 43, 987, -9, 0] --> [-9, 0] + [5, 7, 43, 987] [1, 2, 3, 4, 1] --> [1] + [1, 2, 3, 4] While these are not (false):
Read More
Largest Number Groupings in String in Python
October 12, 2021
The challenge You are be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, solve("gh12cdy695m1") = 695, because this is the largest of all number groupings. The solution in Python code Option 1: import re def solve(s): return max(map(int,re.findall(r"(\d+)", s))) Option 2: def solve(s): return max(map(int,"".join(" " if x.isalpha() else x for x in s).
Read More
How to Alternate String Casing in Golang
October 11, 2021
The challenge Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word uppercased, and all odd indexed characters in each word lowercased. The indexing just explained is zero-based, so the zero-ith index is even, therefore that character should be uppercased and you need to start over for each word. The passed-in string will only consist of alphabetical characters and spaces(' ').
Read More
How to Sort a List of Numbers in Python
October 10, 2021
The challenge Finish the solution so that it sorts the passed-in array/list of numbers. If the function passes in an empty array/list or null/None value then it should return an empty array/list. Examples: solution([1,2,3,10,5]) # should return [1,2,3,5,10] solution(None) # should return [] The solution in Python code Option 1: def solution(nums): if not nums: return [] return sorted(nums) Option 2: def solution(nums): return sorted(nums) if nums else [] Option 3:
Read More
How to Validate Usernames with Regex in Java
October 9, 2021
The challenge Write a simple regex to validate a username. Allowed characters are: lowercase letters, numbers, underscore Length should be between 4 and 16 characters (both included). The solution in Java code Option 1: public class PasswordValidation { public static boolean validateUsr(String s) { return s.matches("[a-z_\\d]{4,16}"); } } Option 2: import java.util.regex.Pattern; public class PasswordValidation { private static final Pattern usernamePattern = Pattern.compile("[a-z0-9_]{4,16}"); public static boolean validateUsr(String s) { return usernamePattern.
Read More
Sort Lexicographical Order of Substrings in Java
October 8, 2021
The challenge Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2. Example 1: a1 = ["arp", "live", "strong"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] returns ["arp", "live", "strong"] Example 2: a1 = ["tarp", "mice", "bull"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] returns [] The solution in Java code Option 1:
Read More
How to Perform Alphabetical Addition in Java
October 7, 2021
The challenge Your task is to add up letters to one letter. The function will be given an array of single-character Strings, each one being a letter to add. Notes: Letters will always be lowercase. Letters can overflow (see second to last example of the description) If no letters are given, the function should return 'z' Examples: addLetters("a", "b", "c") = "f" addLetters("a", "b") = "c" addLetters("z") = "z" addLetters("z", "a") = "a" addLetters("y", "c", "b") = "d" // notice the letters overflowing addLetters() = "z" The solution in Java code Option 1:
Read More
Roman Numerals Decoder in Golang
October 6, 2021
The challenge Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII).
Read More
How to Subtract from Time in Golang
October 5, 2021
The challenge Clock shows h hours, m minutes and s seconds after midnight. Your task is to write a function that returns the time since midnight in milliseconds. Example: h = 0 m = 1 s = 1 result = 61000 Input constraints: 0 <= h <= 23 0 <= m <= 59 0 <= s <= 59 The solution in Golang Option 1: package solution func Past(h, m, s int) int { return (h*3600000 + m*60000 + s*1000) } Option 2:
Read More
How to Encrypt Words in Java
October 4, 2021
The challenge You want to create secret messages which must be deciphered. Here are the conditions: Your message is a string containing space separated words. You need to encrypt each word in the message using the following rules: The first letter must be converted to its ASCII code. The second letter must be switched with the last letter Keepin’ it simple: There are no special characters in the input. Examples: EncryptWords.
Read More
Bit Counting in Golang
October 3, 2021
The challenge Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case The solution in Golang Option 1: package solution import "math/bits" func CountBits(n uint) int { return bits.OnesCount(n) } Option 2:
Read More
How to Find Next Higher Number with Same Bits in Golang
October 2, 2021
The challenge Find the next higher number (int) with same ‘1’- Bits. I.e. as much 1 bits as before and output next higher than input. Input is always an int in between 1 and 1«30 (inclusive). No bad cases or special tricks… Examples: Input: 129 => Output: 130 (10000001 => 10000010) Input: 127 => Output: 191 (01111111 => 10111111) Input: 1 => Output: 2 (01 => 10) Input: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111) The solution in Golang Option 1:
Read More
How to Find the First Non-Repeating Character in Golang
October 1, 2021
The challenge Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string. For example, if given the input 'stress', the function should return 't', since the letter t only occurs once in the string, and occurs first in the string. As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter.
Read More
How to Find the Last Fibonacci Digit in Golang
September 30, 2021
The challenge Return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers). LastFibDigit(1) == 1 LastFibDigit(2) == 1 LastFibDigit(3) == 2 LastFibDigit(1000) == 5 LastFibDigit(1000000) == 5 The solution in Golang Option 1: package solution func LastFibDigit(n int) int { n %= 60 a, b := 0, 1 for i := 0; i<n; i++ { a, b = b, a+b } return a % 10 } Option 2:
Read More
How to Validate an IP Address in Golang
September 29, 2021
The challenge Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between `` and 255, inclusive. Valid inputs examples: 1.2.3.4 123.45.67.89 Invalid input examples: 1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089 Notes: Leading zeros (e.g. 01.02.03.04) are considered invalid Inputs are guaranteed to be a single string The solution in Golang Option 1: package solution import "net" func Is_valid_ip(ip string) bool { if r := net.
Read More
How to Fold an Array in Java
September 28, 2021
The challenge In this challenge, you have to write a method that folds a given array of integers by the middle x-times. An example says more than a thousand words: Fold 1-times: [1,2,3,4,5] -> [6,6,3] A little visualization (NOT for the algorithm but for the idea of folding): Step 1 Step 2 Step 3 Step 4 Step5 5/ 5| 5\ 4/ 4| 4\ 1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3 ----*---- ----* ----* ----* ----* Fold 2-times: [1,2,3,4,5] -> [9,6] As you see, if the count of numbers is odd, the middle number will stay.
Read More
Formatting Strings with Fmt in Golang
September 27, 2021
Fmt provides printing to standard output (usually the console) and formatting of strings capabilities. The basics of Print and Println The main difference between fmt.Print and fmt.Println is that you only get a newline/carriage return by default with the second one. Other than that, you can make use of either for string formatting. Firstly, we need to import the fmt module as follows: package main import "fmt" // <--- include fmt func main() { // main } Example of fmt.
Read More
Delete Occurrences of an Element if it occurs more than N times in Java
September 26, 2021
The challenge Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3]. Examples // return [20,37,21] EnoughIsEnough.
Read More
How to Read from Standard Input in Golang
September 25, 2021
Reading from “standard input” is really useful if you are making a command-line application and require user input. package main import ( "bufio" "os" "fmt" ) func main() { reader := bufio.NewReader(os.Stdin) s, _ := reader.ReadString('\n') fmt.Printf(s) } First setup a new bufio reader, then use ReadString function, with a default wait character, which we have set to a newline (\n). The application will pause at this point and wait for user input before proceeding.
Read More
How to Install Golang on WSL/WSL2
September 24, 2021
If you need to install Golang on WSL under Windows 10 or higher, you can follow these few steps. First remove any old versions lying around sudo rm -rf /usr/local/go* && sudo rm -rf /usr/local/go Determine the latest Go version Go to https://golang.org/dl/ and find out what the latest version is. At the time of writing this, Go is on version 1.16. Install Go Make sure to replace 1.16 below with the updated version as required.
Read More
How to Validate Phone Numbers in Java
September 23, 2021
The challenge Write a function that accepts a string, and returns true if it is in the form of a phone number. Assume that any integer from 0-9 in any of the spots will produce a valid phone number. Only worry about the following format: (123) 456-7890 (don’t forget the space after the close parentheses) Examples: "(123) 456-7890" => true "(1111)555 2345" => false "(098) 123 4567" => false The solution in Java code Option 1:
Read More
How to Sort Array by Frequency in Java
September 22, 2021
The challenge Sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value. Solution.sortByFrequency(new int[]{2, 3, 5, 3, 7, 9, 5, 3, 7}); // Returns {3, 3, 3, 5, 5, 7, 7, 2, 9} // We sort by highest frequency to lowest frequency. // If two elements have same frequency, we sort by increasing value. The solution in Java code Option 1:
Read More
How to Calculate String Rotation in Java
September 21, 2021
The challenge Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. The check should be case-sensitive. For instance, take the strings “fatigue” and “tiguefa”. In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn’t a valid rotation of the first string, the method returns -1.
Read More
Compare Strings by Sum of Chars in Java
September 20, 2021
The challenge Compare two strings by comparing the sum of their values (ASCII character code). For comparing treat all letters as UpperCase null should be treated as empty strings If the string contains other characters than letters, treat the whole string as it would be empty Your method should return true, if the strings are equal and false if they are not equal. Examples: "AD", "BC" -> equal "AD", "DD" -> not equal "gf", "FG" -> equal "zz1", "" -> equal (both are considered empty) "ZzZz", "ffPFF" -> equal "kl", "lz" -> not equal null, "" -> equal The solution in Java code Option 1:
Read More
How to Add Two Integers Without Arithmetic Operator in Java
September 19, 2021
The challenge Given two integers a, b, find The sum of them, BUT You are not allowed to use the operators + and – Notes The numbers (a,b) may be positive , negative values or zeros . Returning value will be an integer . Java: the following methods are prohibited: addExact, average, collect, decrement, increment, nextAfter, nextDown, nextUp, reduce, subtractExact, sum, summing . The following classes are prohibited: BigDecimal and BigInteger .
Read More
Counting Method VarArgs in Java
September 18, 2021
The challenge Count how many arguments a method is called with. Examples args_count(1, 2, 3) -> 3 args_count(1, 2, 3, 10) -> 4 The solution in Java code Some languages refer to this as the spread operator. In Java, this is called a VarArg, which means a Variable Amount of Arguments. Simply prepend the argument’s name with three dots (...) and then refer to it like an array of elements.
Read More
How to Sum Consecutives in Java
September 17, 2021
The challenge You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list. Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer. Same meaning: 1 == 1 1 != -1 Examples: [1,4,4,4,0,4,3,3,1] # should return [1,12,0,4,6,1] """So as you can see sum of consecutives 1 is 1 sum of 3 consecutives 4 is 12 sum of 0.
Read More
Replacing Occurences of Words in Java
September 16, 2021
The challenge You are given a string. You must replace any occurrence of the sequence coverage by covfefe, however, if you don’t find the word coverage in the string, you must add covfefe at the end of the string with a leading space. The solution in Java code Option 1: public class Covfefe { public static String covfefe(String tweet) { return tweet.contains("coverage") ? tweet.replaceAll("coverage", "covfefe") : tweet+" covfefe"; } } Option 2:
Read More
Convert String to LeetSpeak in Java
September 15, 2021
The challenge Your task is to write a function toLeetSpeak that converts a regular english sentence to Leetspeak. More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet Consider only uppercase letters (no lowercase letters, no numbers) and spaces. For example: toLeetSpeak("LEET") returns "1337" In this challenge we use a simple LeetSpeak dialect. Use this alphabet: { A : '@', B : '8', C : '(', D : 'D', E : '3', F : 'F', G : '6', H : '#', I : '!
Read More
Ordered Count of Characters in Python
September 14, 2021
The challenge Count the number of occurrences of each character and return it as a list of tuples in order of appearance. For empty output return an empty list. Example: ordered_count("abracadabra") == [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)] The solution in Python code Option 1: from collections import Counter def ordered_count(input): c = Counter(input) return sorted(list(c.items()), key=lambda x: input.index(x[0])) Option 2: def ordered_count(_input): l = [] for i in _input: if i not in l: l.
Read More
Credit Card Issuer Checking in Java
September 13, 2021
The challenge Given a credit card number we can determine who the issuer/vendor is with a few basic knowns. Complete the function getIssuer() that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string Unknown. | Card Type | Begins With | Number Length | |------------|----------------------|---------------| | AMEX | 34 or 37 | 15 | | Discover | 6011 | 16 | | Mastercard | 51, 52, 53, 54 or 55 | 16 | | VISA | 4 | 13 or 16 | Examples getIssuer(4111111111111111) == "VISA" getIssuer(4111111111111) == "VISA" getIssuer(4012888888881881) == "VISA" getIssuer(378282246310005) == "AMEX" getIssuer(6011111111111117) == "Discover" getIssuer(5105105105105100) == "Mastercard" getIssuer(5105105105105106) == "Mastercard" getIssuer(9111111111111111) == "Unknown" The solution in Java code Option 1:
Read More
Find Count of Most Frequent Item in an Array in Java
September 12, 2021
The challenge Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return `` Example input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] ouptut: 5 The solution in Java code Option 1: import java.util.*; public class Solution { public static int mostFrequentItemCount(int[] collection) { if (collection.
Read More
Return Nth Smallest Element in Java
September 11, 2021
The challenge Given an array/list [] of integers, Find the Nth smallest element in this array of integers Notes Array/list size is at least 3 . Array/list’s numbers could be a mixture of positives , negatives and zeros . Repetition in array/list’s numbers could occur, so don’t Remove Duplications . Examples nthSmallest({3,1,2} ,2) ==> return (2) nthSmallest({15,20,7,10,4,3} ,3) ==> return (7) nthSmallest({2,169,13,-5,0,-1} ,4) ==> return (2) The solution in Java code Option 1:
Read More
What temperature does your Mac CPU idle at?
September 10, 2021
Sometimes you will find that your Mac is running very hot, and you may want to keep track of it over time to see if it’s persistent or only a spike. There are tools like Intel’s Power Widget, or even the TurboBoostSwitcher that will show you graphs of these sort of things, but what about getting this information directly from the CLI? You’re in luck! sudo powermetrics --samplers smc | grep -i "CPU die temperature"
Read More
Split String into Parts in Java
September 9, 2021
The challenge Split a given string into different strings of equal size. Example: Split the below string into other strings of size #3 'supercalifragilisticexpialidocious' Will return a new string 'sup erc ali fra gil ist ice xpi ali doc iou s' Assumptions: String length is always greater than 0 String has no spaces Size is always positive The solution in Java code Option 1: public class InParts { public static String splitInParts(String s, int partLength) { StringBuilder sb = new StringBuilder(); char[] c = s.
Read More
[Solved] ERROR 1030 (HY000): Got error 168 from storage engine
September 8, 2021
If you are getting the following error in MySQL: ERROR 1030 (HY000): Got error 168 from storage engine Then this usually means that your server has run out of disk space! This is never a good thing, but can be resolved by simply deleting some files on the server that you don’t need. Solution 1: Delete some files If you have some files on the server that you can delete to free up some space, then do so.
Read More
Largest Pair Sum in Array in Python
September 7, 2021
The challenge Given a sequence of numbers, find the largest pair sum in the sequence. For example [10, 14, 2, 23, 19] --> 42 (= 23 + 19) [99, 2, 2, 23, 19] --> 122 (= 99 + 23) Input sequence contains minimum two elements and every element is an integer. The solution in Python code Option 1: def largest_pair_sum(numbers): return sum(sorted(numbers)[-2:]) Option 2: def largest_pair_sum(numbers): max1 = max(numbers) numbers.remove(max1) max2 = max(numbers) return max1 + max2 Option 3:
Read More
Alphabet Symmetry in Python
September 6, 2021
The challenge Consider the word "abode". We can see that the letter a is in position 1 and b is in position 2. In the alphabet, a and b are also in positions 1 and 2. Notice also that d and e in abode occupy the positions they would occupy in the alphabet, which are positions 4 and 5. Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word.
Read More
Exes and Ohs in Java
September 5, 2021
The challenge Check to see if a string has the same amount of ‘x’s and ‘o’s. The method must return a boolean and be case insensitive. The string can contain any char. Examples input/output: XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO("zzoo") => false The solution in Java code Option 1: import java.util.*; public class XO { public static boolean getXO (String str) { Map<String, Integer> m = new HashMap<>(); m.
Read More
Sum of Odd Cubed Numbers in Python
September 4, 2021
The challenge Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return None if any of the values aren’t numbers. Note: Booleans should not be considered as numbers. The solution in Python code Option 1: def cube_odd(arr): if any(type(x) is not int for x in arr): return None return sum(x ** 3 for x in arr if x % 2 != 0) Option 2:
Read More
Halving Sum in Python
September 3, 2021
The challenge Given a positive integer n, calculate the following sum: n + n/2 + n/4 + n/8 + ... All elements of the sum are the results of integer division. Example 25 => 25 + 12 + 6 + 3 + 1 = 47 The solution in Python code Option 1: def halving_sum(n): total = [n] while n>=1: n = int(n/2) total.append(n) return sum(total) Option 2: def halving_sum(n): s=0 while n: s+=n ; n>>=1 return s Option 3:
Read More
Convert a LinkedList to a String in Python
September 2, 2021
The challenge Preloaded for you is a class, struct, or derived data type Node (depending on the language) used to construct linked lists in this challenge: class Node(): def __init__(self, data, next = None): self.data = data self.next = next Create a function stringify which accepts an argument list/$list and returns a string representation of the list. The string representation of the list starts with the value of the current Node, specified by its data/$data/Data property, followed by a whitespace character, an arrow, and another whitespace character (" -> "), followed by the rest of the list.
Read More
Most Digits from List in Python
September 1, 2021
The challenge Find the number with the most digits. If two numbers in the argument array have the same number of digits, return the first one in the array. The solution in Python code Option 1: def find_longest(xs): return max(xs, key=lambda x: len(str(x))) Option 2: def find_longest(arr): arr.sort(reverse=True) return arr[0] Option 3: def find_longest(arr): max_lenght = 0 max_index = 0 for cur_num in arr: lenght = len(str(cur_num)) if lenght > max_lenght: max_lenght = lenght max_index = arr.
Read More
Check if all Values in Array are Smaller in Python
August 31, 2021
The challenge You will be given an array and a limit value. You must check that all values in the array are below or equal to the limit value. If they are, return true. Else, return false. You can assume all values in the array are numbers. The solution in Python code Option 1: def small_enough(array, limit): return True if max(array)<=limit else False Option 2: def small_enough(array, limit): return max(array)<=limit Option 3:
Read More
Maximum Product from List of Integers in Python
August 30, 2021
The challenge Given an array of integers, Find the maximum product obtained from multiplying 2 adjacent numbers in the array. Notes Array/list size is at least 2. Array/list numbers could be a mixture of positives, negatives also zeroes . Input >Output Examples adjacentElementsProduct([1, 2, 3]); ==> return 6 Explanation: The maximum product is obtained from multiplying 2 * 3 = 6, and they’re adjacent numbers in the array. adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50 Explanation: Max product obtained from multiplying 5 * 10 = 50&nbsp;.
Read More
Sum of Array Singles in Python
August 29, 2021
The challenge You are given an array of numbers in which two numbers occur once and the rest occur only twice. Your task is to return the sum of the numbers that occur only once. For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 occur once, and their sum is 15. Every other number occurs twice. The solution in Python code Option 1: def repeats(arr): count = [] for i in arr: if i not in count: count.
Read More
Flatten and Sort an Array in Python
August 28, 2021
The challenge Given a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order. Example: Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9]. The solution in Python code Option 1: def flatten_and_sort(array): a = [] for b in array: for c in b: a.append(c) return sorted(a) Option 2:
Read More
Playing the Alphabet War in Python
August 27, 2021
The challenge Introduction There is a war and nobody knows – the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. Task Write a function that accepts fight string consists of only small letters and return who wins the fight. When the left side wins return Left side wins!, when the right side wins return Right side wins!
Read More
Sum of numbers from 0 to N in Python
August 26, 2021
The challenge We want to generate a function that computes the series starting from 0 and ending until the given number. Example: Input: > 6 Output: 0+1+2+3+4+5+6 = 21 Input: > -15 Output: -15<0 Input: > 0 Output: 0=0 The solution in Python code Option 1: def show_sequence(n): if n == 0: return "0=0" elif n < 0: return str(n) + "<0" else: counter = sum(range(n+1)) return '+'.join(map(str, range(n+1))) + " = " + str(counter) Option 2:
Read More
Sorted? yes? no? how? ..in Python
August 25, 2021
The challenge Complete the method which accepts an array of integers, and returns one of the following: "yes, ascending" – if the numbers in the array are sorted in an ascending order "yes, descending" – if the numbers in the array are sorted in a descending order "no" – otherwise You can assume the array will always be valid, and there will always be one correct answer. Complete the method which accepts an array of integers, and returns one of the following:
Read More
How to Fix String Casing in Python
August 24, 2021
The challenge You will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: make as few changes as possible. if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase. For example: solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase. solve("CODe") = "CODE".
Read More
How to Remove Duplicate Words from a String in Python
August 23, 2021
The challenge Remove all duplicate words from a string, leaving only single (first) words entries. Example: Input: ‘alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta' Output: ‘alpha beta gamma delta' The solution in Python code Option 1: def remove_duplicate_words(s): def unique_list(l): ulist = [] [ulist.append(x) for x in l if x not in ulist] return ulist return ' '.join(unique_list(s.split())) Option 2: def remove_duplicate_words(s): return ' '.
Read More
How to Validate a Regex PIN Code in Python
August 22, 2021
The challenge ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. Examples "1234" --> true "12345" --> false "a234" --> false The solution in Python code Option 1: def validate_pin(pin): return len(pin) in (4, 6) and pin.isdigit() Option 2: import re def validate_pin(pin): return bool(re.
Read More
Combine strings and remove duplicates in Python
August 21, 2021
The challenge Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters – each taken only once – coming from s1 or s2. Examples: a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" The solution in Python code Option 1 (Using a Dictionary): def longest(a1, a2): a3 = list(dict.fromkeys(sorted(a1+a2))) return "".
Read More
How to Repeat by String Index in Golang
August 20, 2021
The challenge Create a function that repeats each character by the amount of it’s index value of the original string. Examples: accum("abcd") -> "A-Bb-Ccc-Dddd" accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" accum("cwAt") -> "C-Ww-Aaa-Tttt" The parameter of accum is a string that includes only letters from a..z and A..Z. The solution in Golang Option 1: package solution import "strings" func Accum(s string) string { words := make([]string, len(s)) for i, c := range s { words[i] = strings.
Read More
How to make an arithmetic function in Java
August 19, 2021
The challenge Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them. a and b will both be positive integers, and a will always be the first number in the operation, and b always the second. The four operators are “add”, “subtract”, “divide”, “multiply”. A few examples: arithmetic(5, 2, "add") => returns 7 arithmetic(5, 2, "subtract") => returns 3 arithmetic(5, 2, "multiply") => returns 10 arithmetic(5, 2, "divide") => returns 2.
Read More
Calculate the Third Angle of a Triangle in Go
August 18, 2021
The challenge You are given two interior angles (in degrees) of a triangle. Write a function to return the 3rd. Note: only positive integers will be tested. The solution in Golang Option 1: package solution func OtherAngle(a int, b int) int { return 180-a-b } Option 2: package solution func OtherAngle(a int, b int) int { if a + b > 180{ return -1 } return 180 - a - b } Option 3:
Read More
Return Short Long Short in Python
August 17, 2021
The challenge Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty ( length `` ). For example: solution("1", "22") # returns "1221" solution("22", "1") # returns "1221" The solution in Python code Option 1: def solution(a, b): if a.isdigit(): if a<b: return f"{a}{b}{a}" else: return f"{b}{a}{b}" else: if len(a)<len(b): return f"{a}{b}{a}" else: return f"{b}{a}{b}" Option 2:
Read More
Hello, Name or World in Python
August 16, 2021
The challenge Define a method hello that returns “Hello, Name!” to a given name, or says Hello, World! if name is not given (or passed as an empty String). Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx). Examples: hello "john" => "Hello, John!" hello "aliCE" => "Hello, Alice!" hello => "Hello, World!" <em># name not given</em> hello "" => "Hello, World!
Read More
Add Length to Strings in Python
August 15, 2021
The challenge What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array? add_length('apple ban') => ["apple 5", "ban 3"] add_length('you will win') => ["you 3", "will 4", "win 3"] Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element.
Read More
How to Reversing Words in a String in Python
August 14, 2021
The challenge Write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples: As the input may have trailing spaces, you will also need to ignore unnecessary whitespace. Example (Input –> Output) "Hello World" --> "World Hello" "Hi There." --> "There. Hi" The solution in Python code Option 1: import re def reverse(st): return " ".
Read More
How to Remove Duplicates from List in Python
August 13, 2021
The challenge Define a function that removes duplicates from an array of numbers and returns it as a result. The order of the sequence has to stay the same. The solution in Python code Option 1: def distinct(seq): return list(dict.fromkeys(seq)) Option 2: distinct = lambda s: [e for i,e in enumerate(s) if e not in s[:i]] Option 3: def distinct(seq): result = [] seen = set() for a in seq: if a not in seen: result.
Read More
How to Format Dollars and Cents in Python
August 12, 2021
The challenge The company you work for has just been awarded a contract to build a payment gateway. In order to help move things along, you have volunteered to create a function that will take a float and return the amount formatting in dollars and cents. 39.99 becomes $39.99 The rest of your team will make sure that the argument is sanitized before being passed to your function although you will need to account for adding trailing zeros if they are missing (though you won’t have to worry about a dangling period).
Read More
Return `5` without any numbers in Python
August 11, 2021
The challenge Write a function that always returns 5 Sounds easy right? Just bear in mind that you can’t use any of the following characters: 0123456789*+-/ The solution in Python code Option 1: def unusual_five(): return len(['a','b','c','d','e']) Option 2: def unusual_five(): return len("five!") Option 3: def unusual_five(): return (int(True << True << True ^ True)) Option 4: def unusual_five(): return "fiftyfive divided by eleven".count("e") Test cases to validate our solution import test from solution import unusual_five @test.
Read More
How to Generate Range of Integers in Python
August 10, 2021
The challenge Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max) Task Implement a function named generate_range(2, 10, 2) # should return list of [2,4,6,8,10] generate_range(1, 10, 3) # should return list of [1,4,7,10] generate_range(2, 10, 2) # should return array of [2, 4, 6, 8, 10] generate_range(1, 10, 3) # should return array of [1, 4, 7, 10] Note min < max step > 0 the range does not HAVE to include max (depending on the step) The solution in Python code Option 1:
Read More
Blue/Green Deployment Techniques in AWS
August 9, 2021
What are Blue/Green Deployments? “Blue/Green Deployments” is a software deployment methodology. A terminology to suggest two mostly equal states of potential different deployable artefacts. Within the context of Amazon Web Services (AWS), there are a couple of ways to do this. Let’s explore the two most common ones, then extend that theory to a third one. Thereafter, we will touch on two more that could be looked at. 1. Route53 Update the DNS routing.
Read More
How to Calculate Powers of 2 in Python
August 8, 2021
The challenge Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n (inclusive). Examples n = 0 ==> [1] # [2^0] n = 1 ==> [1, 2] # [2^0, 2^1] n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2] The solution in Python code Option 1: def powers_of_two(n): out = [] for i in range(n+1): out.
Read More
How to Get Planet Name By ID in Python
August 7, 2021
The challenge Create a function that takes in an id and returns the planet name. The solution in Python code Option 1: def get_planet_name(id): return { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus" , 8: "Neptune" }[id] Option 2: def get_planet_name(id): return ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"][id-1] Option 3: def get_planet_name(id): if id == 1: return "Mercury" elif id == 2: return "Venus" elif id == 3: return "Earth" elif id == 4: return "Mars" elif id == 5: return "Jupiter" elif id == 6: return "Saturn" elif id == 7: return "Uranus" elif id == 8: return "Neptune" Test cases to validate our solution import test from solution import get_planet_name @test.
Read More
How to Make a Directory if Not Exists in Python
August 6, 2021
If you want to create a directory in Python, but only if it doesn’t exist, you have the following option. Using Python 3.5 or newer? from pathlib import Path Path("/your/directory").mkdir(parents=True, exist_ok=True) Alternative option import os if not os.path.exists("/your/directory"): os.makedirs("/your/directory")
Read More
Square(n) Sum in Python
August 5, 2021
The challenge Complete the square sum function so that it squares each number passed into it and then sums the results together. For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9. Complete the square sum function so that it squares each number passed into it and then sums the results together. For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.
Read More
How to Fill an Array in Python
August 4, 2021
The challenge We want an array, but not just any old array, an array with contents! Write a function that produces an array with the numbers `` to N-1 in it. For example, the following code will result in an array containing the numbers `` to 4: arr(5) # => [0,1,2,3,4] Note: The parameter is optional. So you have to give it a default value. The solution in Python code Option 1:
Read More
How to Fix the ‘Bad Interpreter’ Error from AWS and Python 3.7
August 3, 2021
This error often looks something like: .zshrc: /usr/local/bin/aws: bad interpreter: /usr/local/opt/python/bin/python3.6: no such file or directory Reinstall AWSCLI If you have started getting the Bad Interpreter error when you call awscli, then you can easily fix it by running: brew reinstall awscli Force link the version Then make sure to link to the correct version: brew link --overwrite awscli
Read More
Retrieve records from MSSQLServer in Python
August 2, 2021
The below Python code will create a connection to a MSSQLServer instance, and retrieve data from it back into a variable called tblResults. # use pyodbc for database connection import pyodbc # keep our database credentials in a store secrets = { 'host': '<db_host>', 'Name': '<db_name>', 'username': '<db_username>', 'password': '<db_password>', } # create a connection string conn_str = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER=tcp:{secrets['host']};DATABASE={secrets['Name']};UID={secrets['username']};PWD={secrets['password']}" # create a connection to the database conn = pyodbc.
Read More
How to Remove Trailing Zeroes in Python
August 1, 2021
The challenge Numbers ending with zeros are boring. They might be fun in your world, but not here. Get rid of them. Only the ending ones. 1450 -> 145 960000 -> 96 1050 -> 105 -1050 -> -105 The solution in Python code Option 1: def no_boring_zeros(n): n = str(n) for i in range(len(n)-1, 0, -1): if n[i]=="0": n = n[:-1:] else: return int(n) return int(n) Option 2: def no_boring_zeros(n): try: return int(str(n).
Read More
How to use Profilers in Python
July 31, 2021
When you have performance problems in your Python application, you can use a Profiler to help you. Step 1: Using cProfile Your first option is to run your application with -m cProfile in the cli. Let’s take an example application that is run as follows: python app.py We can run it with a Profiler by doing the following: python -m cProfile -o outfile app.py This will give you a report that shows where most of the time is spent while running your app.
Read More
If you can’t Sleep, just count Sheep in Python
July 30, 2021
The challenge Given a non-negative integer, 3 for example, return a string with a murmur: "1 sheep...2 sheep...3 sheep...". Input will always be valid, i.e. no negative integers. The solution in Python code Option 1: def count_sheep(n): sheep = '' for i in range(n): sheep+=f"{i+1} sheep..." return sheep Option 2: def count_sheep(n): return ''.join(f"{i} sheep..." for i in range(1,n+1)) Option 3: def count_sheep(n): return ('{} sheep...'*n).format(*list(range(1,n+1))) Test cases to validate our solution import test from solution import count_sheep @test.
Read More
Key-Value CLI Arguments in Python
July 29, 2021
If you have a CommandLine application (CLI) written in Python, you have a number of ways that you can take arguments from the user. You could take the order from the user and assign those to variables: import sys print( sys.argv ) This will give you a list of all the space separated values. So if your app is called like: python app.py var1 var2 # ['app.py', 'var1', 'var2'] As you can see, sys.
Read More
How to use a Translation Table to Replace Characters in Python
July 28, 2021
Python provides the ability to create Translation Tables. our_text = "This is an example of some text" translation_table = str.maketrans("abefilostz", "4636110572") print(our_text) #This is an example of some text print(our_text.translate(translation_table)) # Th15 15 4n 3x4mp13 06 50m3 73x7 First we create a Translation Table by calling str.maketrans(x, y, z), passing in our characters we want to translate from and to. Then we apply our translate(table) to a string using our newly created Translation Table.
Read More
How to Calculate the Sum of all Numbers in a String in Python
July 27, 2021
Let’s take the following string: numbers = "this 1 2 3 4 5 is not a 8 9 10" How can we sum up all the numbers in this string? print(sum([int(num) for num in numbers.split(" ") if num.isnumeric()])) #42 In the above code snippet, we split the string by the space character, then loop through it and ignore anything that is not numeric. Then we sum up the numbers that are remaining.
Read More
How to Find all Permutations of a String in Python
July 26, 2021
Python comes with a very useful module called itertools, which allows us to calculate permutations directly. from itertools import permutations perms = [''.join(p) for p in set(permutations('hello'))] print(perms) print(len(perms)) This will result in 60 permutations: #['helol', 'heoll', 'ehlol', 'eholl', 'ollhe', 'lheol', 'lhoel', 'lehol', 'leohl', 'hoell', 'holel', 'eohll', 'eolhl', 'olhel', 'olehl', 'lhelo', 'lhleo', 'lehlo', 'lelho', 'hlelo', 'hlleo', 'elhlo', 'ellho', 'lhloe', 'lhole', 'leloh', 'leolh', 'hlloe', 'hlole', 'elloh', 'elolh', 'lohel', 'loehl', 'oelhl', 'elhol', 'ohlel', 'olleh', 'holle', 'eollh', 'olhle', 'olelh', 'ehllo', 'hello', 'ohlle', 'oellh', 'llheo', 'lleho', 'llhoe', 'lleoh', 'llohe', 'lloeh', 'oehll', 'elohl', 'lohle', 'loelh', 'lolhe', 'loleh', 'hleol', 'hloel', 'ohell'] #60 How to Find all Permutations without Itertools def permutations(string): if len(string) == 1: return string recursive_perms = [] for c in string: for perm in permutations(string.
Read More
How to Fix ‘no basic auth credentials’ with Docker and AWS ECR
July 25, 2021
If you are trying to push a Docker image to AWS ECR (Elastic Container Registry) and you get a no basic auth credentials error. Then you can easily fix it as follows! Replicating the no basic auth credentials error You ran something like this: docker tag <image> <account>.dkr.ecr.<region>.amazonaws.com/<app> docker push <image> <account>.dkr.ecr.<region>.amazonaws.com/<app> You saw something like this: Using default tag: latest The push refers to repository [<account>.dkr.ecr.<region>.amazonaws.com/<app>] 2e6d5f7bxxxx: Preparing d8db3303xxxx: Preparing 32f366d6xxxx: Preparing no basic auth credentials How to fix the problem no basic auth credentials error
Read More
How to Reverse Words or Sentences in Python
July 24, 2021
Let’s take the following sentence: words = "These are some words" We can use slices to reverse the order of the string: print( words[::-1] ) #sdrow emos era esehT Let’s say we wanted to reverse each word in the sentence, but keep the order of words. We can once again use slices, but we will compliment it with a list comprehension: print( " ".join([word[::-1] for word in words.split(" ")]) ) #esehT era emos sdrow How to Reverse words without using inbuilt modules Let’s take this a bit further.
Read More
How to solve AttributeError: ‘int’ object has no attribute ‘split’ – make: [sharedmods] Error 1
July 23, 2021
If you get the following error while trying to install something via Homebrew AttributeError: 'int' object has no attribute 'split' - make: *** [sharedmods] Error 1 The solution to this Homebrew issue First try to solve the actual Homebrew issues: git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow This will then allow you to update: homebrew update Then: brew tap aws/tap brew install aws-sam-cli Worst case scenario solution Then you can solve it like this:
Read More
How to Push a Docker image to AWS ECR
July 22, 2021
By default, Docker pushes its images to Docker Hub. While Docker Hub is a great way to share both your public and private images, you may find the rest of your infrastructure on one of the prominent cloud providers. In this instance, you are using many of the other AWS resources, so why not use Elastic Container Registry – or ECR for short – instead? In this guide, we will replace <region> with your desired region in AWS.
Read More
Complete Guide: How to Base64 Encode a String in Python | Python Base64 Encoding Explained
July 21, 2021
How to Base64 Encode a String in Python: A Comprehensive Guide Welcome to our comprehensive guide on how to python base64 encode a string in Python. Whether you’re a beginner or an experienced Python developer, this guide will equip you with the knowledge and techniques to perform efficient and accurate base64 encoding. Let’s dive in and explore the world of Python base64 encoding together! Understanding Python’s base64 Module Python’s built-in base64 module provides a convenient way to encode and decode data using the base64 encoding scheme.
Read More
How to Get 10 Random Numbers in Python
July 20, 2021
The random module allows you to generate choices. import random print(random.choices([i for i in range(1000)], k=10)) This might give us back something like: [635, 450, 26, 829, 786, 563, 294, 586, 893, 953] Explaining random.choice and random.choices random.choice takes a sequence as a parameter and return a single random item from it. While random.choices takes a sequence as a parameter and returns a few random items from it. You can specify how many random items to return by populating the k= parameter, as above.
Read More
Get the Middle Character in Python
July 19, 2021
The challenge Return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters. Examples: getMiddle("test") # should return "es" getMiddle("testing") # should return "t" getMiddle("middle") # should return "dd" getMiddle("A") # should return "A" Input A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases).
Read More
Convert String to Datetime in Python
July 18, 2021
If you have a string and want to create a Datetime object out of it in Python, then you can use the Datetime Parse Time method, as follows: from datetime import datetime your_datetime = datetime.strptime('May 31 2021 1:23PM', '%Y-%m-%d') There are 2 very useful functions of datetime, namely: strptime – Parse a string strftime – Format a string A common format you may be looking for is: %Y-%m-%d %H:%M:%S
Read More
How to Abort SQL statements after a set time in MariaDB
July 17, 2021
Sometimes you don’t want a SELECT query to run for more than a set amount of time. This is a roundabout way to make your server doesn’t die from slow-running queries. Obviously, you should tweak your database and potentially run your SELECT queries through an EXPLAIN plan first. This allows you to create appropriate indexes and find why things are slow in the first place. But: sometimes you still find yourself wanting to kill queries that may run over a certain amount of time.
Read More
Multiprocessing Pools in Python
July 16, 2021
Python ships with a multiprocessing module that allows your code to run functions in parallel by offloading calls to available processors. In this guide, we will explore the concept of Pools and what a Pool in multiprocessing is. A Python snippet to play with Let’s take the following code. import random, time def calculate_something(i): time.sleep(5) print(random.randint(10, 100)*i) for i in range(5): calculate_something(i) This function will take about 5*5seconds to complete (25seconds?
Read More
How to Double Characters in Python
July 15, 2021
The challenge Given a string, you have to return a string in which each character (case-sensitive) is repeated once. double_char("String") ==> "SSttrriinngg" double_char("Hello World") ==> "HHeelllloo WWoorrlldd" double_char("1234!_ ") ==> "11223344!!__ " The solution in Python code This can easily be done by looping through each character and appending it to a list, which we then join and return at the end: def double_char(s): out = [] for i in s: out.
Read More
How to Reverse Words in Python
July 14, 2021
The challenge Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained. Examples "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" The solution in Python code Option 1: def reverse_words(text): out = [] for word in text.split(" "): out.append(word[::-1]) return " ".join(out) Option 2: def reverse_words(str): return ' '.join(s[::-1] for s in str.
Read More
How to Count by X in Python
July 13, 2021
The challenge Create a function with two arguments that will return an array of the first (n) multiples of (x). Assume both the given number and the number of times to count will be positive numbers greater than 0. Return the results as a list. Examples count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10] count_by(2,5) #should return [2,4,6,8,10] The solution in Python code Option 1: def count_by(x, n): out = [] for i in range(n): out.
Read More
Calculate the Sum of Pairs in Python
July 12, 2021
The challenge Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2.
Read More
How to break a list into multiple lists (with maximum size) in Python
July 11, 2021
If you have a large list and want to create smaller lists of it, with a maximum amount of elements, then: commands = [str(i) for i in range(100)] print(len(commands)) #100 chunks = [commands[x:x+5] for x in range(0, len(commands), 5)] print(len(chunks)) #20 print(chunks) This will look like: [ ['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19'], ['20', '21', '22', '23', '24'], ['25', '26', '27', '28', '29'], ['30', '31', '32', '33', '34'], ['35', '36', '37', '38', '39'], ['40', '41', '42', '43', '44'], ['45', '46', '47', '48', '49'], ['50', '51', '52', '53', '54'], ['55', '56', '57', '58', '59'], ['60', '61', '62', '63', '64'], ['65', '66', '67', '68', '69'], ['70', '71', '72', '73', '74'], ['75', '76', '77', '78', '79'], ['80', '81', '82', '83', '84'], ['85', '86', '87', '88', '89'], ['90', '91', '92', '93', '94'], ['95', '96', '97', '98', '99'] ]
Read More
Get all dates between two dates inclusive in Python
July 10, 2021
If you want to print out a list of all dates between 2 dates (a date range), then you can use the following script: from datetime import date, timedelta start_date = date(2021, 5, 31) end_date = date(2021, 7, 28) delta = end_date - start_date for i in range(delta.days + 1): day = start_date + timedelta(days=i) print(day) This will result in the following range: 2021-05-31 2021-06-01 ... 2021-07-27 2021-07-28 To make sure that you get the format you want back:
Read More
How to Append a Python Dictionary to a Pandas DataFrame
July 9, 2021
If you want to append a Python dictionary to a Pandas DataFrame, you can do this: # Create a new DataFrame output = pd.DataFrame() # Append the dictionary by ignoring the index output = output.append(dictionary, ignore_index=True) # View the new DataFrame print(output.head()) Notice the reassignment output = output.append(...)
Read More
Get Secret from AWS Secrets Manager in Python
July 8, 2021
You can store secrets in AWS Secret Manager and reference their ARN in AWS Systems Secret Manager. The below snippet allows you to specify the associated parameter to get the secret value. import boto3 ssm = boto3.client('ssm') secretsmanager = boto3.client('secretsmanager') parameter = ssm.get_parameter(Name="/your/parameter/name", WithDecryption=True) secret = secretsmanager.get_secret_value(SecretId=parameter['Parameter']['Value']) secret = json.loads(secret['SecretString']) print(secret)
Read More
How to do Binary Addition in Python
July 7, 2021
The challenge Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before or after the addition. The binary number returned should be a string. Examples: add_binary(1, 1) == "10" (1 + 1 = 2 in decimal or 10 in binary) add_binary(5, 9) == "1110" (5 + 9 = 14 in decimal or 1110 in binary) The solution in Python code There are multiple ways to solve an int to binary string problem in Python.
Read More
How to Auto-Adjust Excel column widths with pandas.ExcelWriter
July 6, 2021
You have successfully written your pandas Dataframe to an Excel file, but when you open it, all the columns are squashed up against each other. There is an easy fix to auto-adjusting your column widths. Auto Adjusting Column Widths in Pandas writer = pd.ExcelWriter('file.xlsx') df.to_excel(writer, sheet_name='sheetName', index=False, na_rep='NaN') for column in df: column_length = max(df[column].astype(str).map(len).max(), len(column)) col_idx = df.columns.get_loc(column) writer.sheets['sheetName'].set_column(col_idx, col_idx, column_length) writer.save()
Read More
How to Sort the Odd in Python
July 5, 2021
The challenge You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions. Examples [7, 1] => [1, 7] [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0] The solution in Python code Option 1:
Read More
Calculate the Sum of the two lowest positive integers in Python
July 4, 2021
The challenge Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7. [10, 343445353, 3453445, 3453545353453] should return 3453455. The solution in Python code Option 1: def sum_two_smallest_numbers(numbers): return sum(sorted(numbers)[:2]) Option 2: def sum_two_smallest_numbers(num_list): num_list.
Read More
Unique In Order in Python
July 3, 2021
The challenge Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3] The solution in Python code Option 1: def unique_in_order(iterable): result = [] prev = None for char in iterable[0:]: if char !
Read More
How to Change the Hostname on Linux
July 2, 2021
On Linux, you can change the hostname by using the hostnamectl command. How to Set the Hostname on Linux sudo hostnamectl set-hostname <new-hostname> For example: sudo hostnamectl set-hostname server1 At this point, you will need to logout and back in to see the changes have taken effect.
Read More
How to Deploy a Docker Container to Kubernetes
July 1, 2021
Once you have a Docker container, it is really simple to deploy containers to Kubernetes . Generate a Deployment YAML kubectl provides a fantastic way to help generate deployment yamls. kubectl create deployment <app_name> --image=<some/image> --dry-run=client -o yaml > <deployment_file_name>.yaml Perform the Deployment Now that we have a deployment yaml, we can simply run: kubectl apply -f <deployment_file_name>.yaml What next? Next you might want to add a Service so that the deployment is available to the world.
Read More
How to Replace Characters with Alphabet Positions in Python
June 30, 2021
The challenge Given a string, replace every letter with its position in the alphabet. If anything in the text isn’t a letter, ignore it and don’t return it. "a" = 1, "b" = 2, etc. Example alphabet_position("The sunset sets at twelve o'clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)
Read More
Returning Highest and Lowest in Python
June 29, 2021
The challenge You are given a string of space-separated numbers and have to return the highest and lowest number. Example: high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5" Notes: All numbers are valid Int32, no need to validate them. There will always be at least one number in the input string. Output string must be two numbers separated by a single space, and highest number is first.
Read More
How to Subtract Arrays in Python
June 28, 2021
The challenge Implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b keeping their order. arrayDiff([1,2],[1]) == [2] If a value is present in b, all of its occurrences must be removed from the other: arrayDiff([1,2,2,2,3],[2]) == [1,3] The solution in Python Option 1: def array_diff(a, b): return [x for x in a if x not in b] Option 2:
Read More
How to Detect if Numbers are in Order in Golang
June 27, 2021
The challenge In this challenge, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value. For the purposes of this challenge, you may assume that all inputs are valid, i.e. non-empty arrays containing only integers.
Read More
Alternate Capitalization in Golang
June 26, 2021
The challenge Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `` will be considered even. For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples. The input will be a lowercase string with no spaces. The solution in Golang Option 1: package solution import "unicode" func Capitalize(s string) []string { a, b := []rune(s),[]rune(s) for i := range a { if i%2 == 0 { a[i] = unicode.
Read More
Check if a String is Uppercase in Golang
June 25, 2021
The challenge Create a method IsUpperCase to see whether the string is ALL CAPS. For example: type MyString string MyString("c").IsUpperCase() == false MyString("C").IsUpperCase() == true MyString("hello I AM DONALD").IsUpperCase() == false MyString("HELLO I AM DONALD").IsUpperCase() == true MyString("ACSKLDFJSgSKLDFJSKLDFJ").IsUpperCase() == false MyString("ACSKLDFJSGSKLDFJSKLDFJ").IsUpperCase() == true In this challenge, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
Read More
How to UpperCase a String in Golang
June 24, 2021
In Go, there are multiple ways to make a string UpperCase, each of them are by using the strings package. Option 1 (strings.ToUpper): func ToUpper(str string) string package main import ( "fmt" "strings" ) func main() { str1 := "This is a Test" fmt.Println(strings.ToUpper(str1)) // "THIS IS A TEST" } Option 2 (strings.ToTitle): func ToTitle(str string) string package main import ( "fmt" "strings" ) func main() { str1 := "This is a Test" fmt.
Read More
Return the Shortest Words in Golang
June 23, 2021
The challenge Given a string of words, return the length of the shortest word(s). The input string will never be empty and you do not need to account for different data types. The solution in Golang Option 1: package solution import "strings" func FindShort(s string) int { shortest := len(s) for _, word := range strings.Split(s, " ") { if len(word) < shortest { shortest = len(word) } } return shortest } Option 2:
Read More
How to Solve Pascal’s Triangle in Python
June 22, 2021
The challenge Given an integer numRows, return the first numRows of Pascal’s triangle. In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 30 The solution in Python code class Solution: def generate(self, numRows: int) -> List[List[int]]: triangle = [[1]] for j in range(1, numRows): prev = triangle[-1] triangle.
Read More
Creating a Multiplication Table for a Number in Golang
June 21, 2021
The challenge Your goal is to return multiplication table for number that is always an integer from 1 to 10. For example, a multiplication table (string) for number == 5 looks like below: 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50 P.
Read More
How to Remove Duplicates in an Array in Golang
June 20, 2021
The challenge Remove the left-most duplicates from a list of integers and return the result. // Remove the 3's at indices 0 and 3 // followed by removing a 4 at index 1 solve([3, 4, 4, 3, 6, 3]); // => [4, 6, 3] The solution in Golang Option 1: package solution func Solve(arr []int) (res []int) { visited := map[int]bool{} for i := len(arr) - 1; i >= 0; i-- { n := arr[i] if visited[n] { continue } visited[n] = true res = append([]int{n}, res.
Read More
How to Dry Potatoes in Golang
June 19, 2021
The challenge All we eat is water and dry matter. John bought potatoes: their weight is 100 kilograms. Potatoes contain water and dry matter. The water content is 99 percent of the total weight. He thinks they are too wet and puts them in an oven – at low temperature – for them to lose some water. At the output the water content is only 98%. What is the total weight in kilograms (water content plus dry matter) coming out of the oven?
Read More
How to Reverse or Rotate in Golang
June 18, 2021
The challenge The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz). If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position.
Read More
How to use Coroutines in Kotlin
June 17, 2021
Coroutines are a way to handle multithreading in Kotlin, read more about it from the official docs: https://kotlinlang.org/docs/coroutines-overview.html An example of a Coroutine in Kotlin val runBlocking = runBlocking { sleep(5) delay(1_000L) launch { delay(1_100L) note("inside launch") } note("outside launch") } Introducing the suspend keyword coroutineScopes need to be in wrapping suspend: suspend fun coroutineFunction(): String { return coroutineScope { launch { println("test") } "we return this string" } } runBlocking { println(coroutineFunction()) } Making Asynchronous API calls using Coroutines suspend fun call2Apis() { val call1 = async { delay(1_000L) println("got data from api1 @ ${Instant.
Read More
The Pair Type in Kotlin
June 16, 2021
val pair: Pair<String, Int> = "myKey" to 2 What is a Pair Type? A utility class when you want to return 2 values that are not related to one another. Some examples val (a, b) = Pair(1, "x") println(a) // 1 println(b) // x Alterantively, you could use: val p = Pair("x", "y") println(p) // (x, y) You can refer to it as first and second val p = Pair("x", "y") println(p.
Read More
Get which Quarter of the Year in Golang
June 15, 2021
The challenge Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number. For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter. The solution in Golang Option 1: package solution func QuarterOf(month int) int { return (month + 2) / 3 } Option 2:
Read More
How to Sum The Strings in Python
June 14, 2021
The challenge Create a function that takes 2 nonnegative integers in form of a string as an input, and outputs the sum (also as a string): Example: (Input1, Input2 –>Output) "4", "5" --> "9" "34", "5" --> "39" Notes: If either input is an empty string, consider it as zero. Inputs and the expected output will never exceed the signed 32-bit integer limit (2^31 - 1) The solution in Python code Option 1:
Read More
Fixing: ImmutableService requires getRowNodeId() callback to be implemented, your row data need IDs
June 13, 2021
If you have gotten this error before, then you have been trying to implement a rowData mapping onto Ag-Grid.. and failed! ImmutableService requires getRowNodeId() callback to be implemented, your row data need IDs How to fix the ‘Your row data need IDs’ error The good thing, is that it’s actually quite an easy fix: Make sure that you have implemented the getRowNodeId function to return an actual id: this.getRowNodeId = function(data) { return data.
Read More
How to Undo the most recent local commits in Git
June 12, 2021
If you have accidentally committed the wrong files into Git, but haven’t yet pushed it to the server, you can recover, or undo your commit as follows: How to Undo a Commit and Redo it You have just committed a file, and find yourself here; We will call this “your accident location”. Step 1 git commit -m "This is what you've just done" Step 2 Start by resetting: git reset HEAD~ Step 3 Now you can edit your files as required.
Read More
Deconstruction in Kotlin
June 11, 2021
There are times when you need to extract an object into a number of variables. Let’s take the example below: val (id, name, position, department) = employee In Kotlin, this is known as a destructuring declaration. These new variables can now be used independently. The compilation thereof would look something like this, but is not required: val id = employee.component1() val name = employee.component2() val position = employee.component3() val department = employee.
Read More
Playing with passphrases in Python
June 10, 2021
The challenge Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following: choose a text in capital letters including or not digits and non alphabetic characters, shift each letter by a given number but the transformed letter must be a letter (circular shift), replace each digit by its complement to 9, keep such as non alphabetic and non digit characters, downcase each letter in odd position, upcase each letter in even position (the first character is in position 0), reverse the whole result.
Read More
What is a Unit in Kotlin?
June 9, 2021
Unit corresponds to the void keyword in Java. What is a Unit in Kotlin? If you have a function that does not return a value, you can return a Unit object. Generally, you would return a Unit in Kotlin where you would traditionally return a void in Java. fun doesntReturnAnythign(): Unit { val one = 1 }
Read More
How to declare a Function in Kotlin?
June 8, 2021
Functions are reusable pieces of code, often called Blocks, that as the name suggests, act as building blocks to piece together a program. Each language has its own keyword for defining a function block. What is fun? The fun keyword in Kotlin denotes a function, or method to wrap a reusable code block. fun prepends the name of a function as illustrated below. fun functionName(): String { return "A String" } The structure of a Kotlin function The function can take any number of parameters, and a return type.
Read More
The differences between Val and Var in Kotlin
June 7, 2021
Among all the many keywords that Kotlin comes with, there exists val and var. What are they used for? What are the differences, and why would you use one over another? They are both used to declare variables in Kotlin. But how are they different? What is val? val is used to declare a variable that is read-only, and who’s value does not change. Note that this only applies to the parent variable, and not it’s properties.
Read More
Automatically Resize All Columns to Fit in Ag-Grid
June 6, 2021
If you have an Ag-Grid, and want to automatically resize all the columns to fit the width of the viewport, you can use this hack. The implementation /** * resizes the columns to fit the width of the grid * @param allowShrink if false, columns will NOT be resized when there is no "empty" horizontal space * https://stackoverflow.com/questions/55587083/ag-grid-sizecolumnstofit-only-when-there-is-space-available-in-the-total-grid-wi#answer-60753786 */ public resizeColumnsToFit(allowShrink = true) { if (this.gridApi) { if (allowShrink) { this.
Read More
How to Get All Rows in Ag-Grid
June 5, 2021
The easiest way to get the content of all rows’ data, back into a Javascript/Typescript array, is as follows. Simply create a blank array, then loop through the rows of the grid and append each row to the array. getAllRows() { let rowData = []; this.gridApi.forEachNode(node => rowData.push(node.data)); return rowData; }
Read More
Find the Max Area of an Island in Python
June 4, 2021
The challenge You are given an m x n binary matrix grid. An island is a group of 1‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return ``.
Read More
Using Apache POI to Get or Create a Sheet in Excel using Java
June 3, 2021
Apache POI provides a mechanism to work with Excel documents. However, it has a missing feature when you want to only create a new sheet if one with that name doesn’t already exist. Luckily, it’s quite simple to get around this using the following code. List<String> sheets = new ArrayList<>(); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); sheets.add(sheet.getSheetName()); } Sheet sheet = sheets.contains(name) ?
Read More
A Simplistic TCP Finite State Machine (FSM) in Python
June 2, 2021
The challenge Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session. The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given. The input array of events will consist of one or more of the following strings:
Read More
How to Resolve Scaling Squared Strings in Java
June 1, 2021
The challenge You are given a string of n lines, each substring being n characters long. For example: s = "abcd\nefgh\nijkl\nmnop" We will study the “horizontal” and the “vertical” scaling of this square of strings. A k-horizontal scaling of a string consists of replicating k times each character of the string (except ‘\n’). Example: 2-horizontal scaling of s: => “aabbccdd\neeffgghh\niijjkkll\nmmnnoopp” A v-vertical scaling of a string consists of replicating v times each part of the squared string.
Read More
How to Build a Square in Python
May 31, 2021
The challenge I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 1 and 50. Example n = 3, so I expect a 3×3 square back just like below as a string: +++ +++ +++ The solution in Python Option 1: def generateShape(i): return (i-1)*(('+'*i)+'\n')+('+'*i) Option 2: def generateShape(integer): return '\n'.join('+' * integer for i in range(integer)) Option 3:
Read More
Check if String EndsWith in Python
May 30, 2021
The challenge Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). Examples: strEndsWith('abc', 'bc') # returns true strEndsWith('abc', 'd') # returns false The solution in Python def solution(string, ending): return string.endswith(ending) Test cases to validate our solution test.assert_equals(solution('abcde', 'cde'), True) test.assert_equals(solution('abcde', 'abc'), False) test.assert_equals(solution('abcde', ''), True)
Read More
How to add a Git Submodule to an existing codebase
May 29, 2021
Git submodules are a way of including another repository’s code into an existing codebase, without associating it’s code or tracking history in the parent repository. Add a Git Submodule to an Existing Codebase cd <parent_codebase_root> git submodule add <remote_url> <destination_folder> So let’s say that we have a project called project_website, a repository at the following path https://github.com/user/repo.git and a target folder we’d like the submodule added to at user_repo, we could construct our query like this:
Read More
How to LowerCase a String in Python
May 28, 2021
Python comes with a built-in method on all String types, by calling lower() on a String, you can immediately lower the case of that String. An example to LowerCase a String in Python words = "These are some WORDS" words.lower() # <- How to lowerCase a String # output: these are some words "These are some WORDS".lower() # <- How to lowerCase a String # output: these are some words Now let’s try and see how it may look in a coding challenge:
Read More
How to Restart Sound Driver on a Mac
May 27, 2021
So for some strange reason, your audio has stopped playing through the Macbook Pro speakers, but if you plug in an external audio device, it still works? Or perhaps some other undesirable combination? If so, you could just try restarting the computer. That usually fixes thing right? But you have all those million apps open, all in unsaved states.. So rebooting is not the preferred approach. Try the below option to give your Apple the kick it needs!
Read More
Number to Binary Conversion in Python
May 26, 2021
If you have a decimal number, and want to get it’s binary value, you can use the built-in bin method. decimal = 32 binary = bin(decimal) # '0b100000' We can see that it prepends the string with a 0b. Let’s remove this to return a usable binary value: decimal = 32 binary = str(bin(decimal)[2:]) # '100000'
Read More
Counting Binary Gaps with Python
May 25, 2021
The challenge A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1.
Read More
How to Delete a Secret in Kubernetes
May 24, 2021
Once you have a secret in Kubernetes, if you know it’s name, you can delete it. How to find the secret name You can get the secret name as follows: kubectl get secrets This will produce an output similar to: NAME TYPE DATA AGE admin-user-pass Opaque 2 11s Now that we have the secret name, we can delete the secret Deleting a Secret in Kubernetes kubectl delete secret admin-user-pass
Read More
How to Decode a Secret in Kubernetes
May 23, 2021
Secrets in Kubernetes are encoded using base64. If you have the secret name, you can ask for its value. If not, then learn how to get a secret in Kubernetes. How to retrieve the value of a secret in Kubernetes kubectl get secret admin-user-pass -o jsonpath='{.data}' This will output a JSON as follows: {"password":"amYzOTJoZjc4MmhmOTMyaAo=","username":"YWRtaW51c2VyCg=="} How to decode the value of a secret in Kubernetes Values are always base64 encoded, so decoding it will look like this:
Read More
How to Verify a Secret in Kubernetes
May 22, 2021
You have created a secret, and would like to retrieve it. Get a list of all the secrets in Kubernetes kubectl get secrets This will result in: NAME TYPE DATA AGE admin-user-pass Opaque 2 11s How to view a secret in Kubernetes Now that we have our secret’s name, we can view it directly kubectl describe secrets/admin-user-pass With the following output: Name: admin-user-pass Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== password: 12 bytes username: 5 bytes
Read More
How to Create a Secret in Kubernetes
May 21, 2021
Secrets allow applications to not hardcode usernames, passwords or additional information such as hostnames, IP addresses or other protected/sensitive information. Create a Secret in Kubernetes It’s simple to create a secret in Kubernetes . It can either be done --from-file or --from-literal. Option 1: From a File echo -n 'adminuser' > ./username.txt echo -n 'jf392hf782hf932h' > ./password.txt kubectl create secret generic admin-user-pass \ --from-file=./username.txt \ --from-file=./password.txt The result will be something like:
Read More
How to Divide an Array into Chunks in PHP
May 20, 2021
If you have a single-dimensional array, and want to break it into chunks, you can use the array_chunks method. It takes 3 arguments: The input array / original array The length of the new array (how many dimensions to create) A boolean to preserve the original keys or not <strong>array_chunk</strong>(array&nbsp;$array,&nbsp;int&nbsp;$length,&nbsp;bool&nbsp;$preserve_keys=<strong>false</strong>&nbsp;):array An example of dividing an array into chunks Let’s take an initial starter array with 5 values $input_array = array('a', 'b', 'c', 'd', 'e'); If we said we would like to create 2 chunks:
Read More
How to setup Certbot wildcard certificate on Apache
May 19, 2021
Certbot allows simple, quick and free provisioning of SSL certificates using LetsEncrypt. How to install Certbot Option 1 (recommended) sudo snap install core; sudo snap refresh core sudo snap install --classic certbot sudo ln -s /snap/bin/certbot /usr/bin/certbot Option 2 apt update apt install certbot How to run Certbot If you want to run the automated setup and get your certificate installed directly to apache, then: sudo certbot --apache If you only want the certificate, then:
Read More
How to retrieve a Secret from AWS Secrets Manager in the CLI
May 18, 2021
If you have stored a secret in AWS using the Secrets Manager, it is possible to use the AWS CLI to retrieve this value at a later date. aws secretsmanager get-secret-value --secret-id <ARN> The arn is the Amazon Resource Name, which will look something like this: aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:<region>:<account>:<secretname> Get a Secret from AWS Secrets Manager using the CLI aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:eu-west-1:4872719xxxxx:secret:NameOfOurSecret-xxx
Read More
Determine the Last Digits of N^2 == N in Java
May 17, 2021
The challenge Let’s call an integer number N ‘green’ if N² ends with all of the digits of N. Some examples: 5 is green, because 5² = 25 and 25 ends with 5. 11 is not green, because 11² = 121 and 121 does not end with 11. 376 is green, because 376² = 141376 and 141376 ends with 376. Your task is to write a function green that returns nth green number, starting with 1 – green (1) == 1
Read More
How to Expose your App through a Service in Kubernetes
May 16, 2021
Once you have deployed an application into Kubernetes , it will not be available to the outside world. For this to be possible, you need to expose it via a Service. Services can be exposed in 4 different ways: ClusterIP (default) – Exposes the Service via an internal IP to the cluster (only available internally) NodePort – Exposes the Service via the same port on all Nodes LoadBalancer – Creates an external LoadBalancer in the current cloud ExternalName – Maps the Service to the externalName, and returns a CNAME record with it’s value How to Expose your App via a Service in Kubernetes kubectl get pods to list your available pods.
Read More
How to connect to Bash on a Kubernetes pod
May 15, 2021
If you find yourself needing to jump into a Kubernetes pod to either diagnose an issue, or run a particular command, you can use the bash connectivity functionality available from kubectl itself. 1. Get the pod name to connect to First, you will need the pod name you want to connect to, you can get this by running kubectl get pods This will return a list similar to: $ kubectl get pods NAME READY STATUS RESTARTS AGE kubernetes-bootcamp-fb5c67579-8tghg 1/1 Running 0 7m39s Take node of the name cell for later use.
Read More
How to get the Environment variables in a Kubernetes Pod
May 14, 2021
In this comprehensive guide, you will learn how to effectively get and list environment variables within a Kubernetes pod . Understanding how to work with environment variables is essential for managing and configuring applications running in Kubernetes clusters. We will cover step-by-step instructions to retrieve the environment variables of a pod, along with in-depth explanations and practical examples for a deeper understanding. By the end of this post, you will be proficient in using kubectl commands to handle environment variables in your Kubernetes environment.
Read More
How to find out Cluster Info in Kubernetes
May 13, 2021
In Kubernetes, a cluster is a group of machines working together. By running the kubectl cluster-info command, we can find out high level information about the Kubernetes cluster , such as: What address the cluster is running from Where the CoreDNS is running from Example use of KubeCtl Cluser Info kubectl cluster-info will return the following: $ kubectl cluster-info Kubernetes master is running at https://998a8a4d-354e-4203-bafb-2e25d7b39269.k8s.example.com CoreDNS is running at https://998a8a4d-354e-4203-bafb-2e25d7b39269.k8s.example.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
Read More
How to set and use a kubeconfig in Kubernetes
May 12, 2021
The kubeconfig file is the main configuration file that allows access to a Kubernetes cluster. When you first create your Kubernetes cluster , you are given a generated yaml file. How to configure the kubeconfig file The kubectl CLI has the followings preference in which kubeconfig file to use: by adding the --kubeconfig <file> by setting a KUBECONFIG environment variable by using the $HOME/.kube/config file on the local machine
Read More
How to Map over a List of Lists in Java
May 11, 2021
The challenge Write a function which maps a function over the lists in a list: public static <T,R> R[][] gridMap(Function<T,R> fn, T[][] list) Example 1: int[][] x = {{1,2,3}, {4,5,6}}; gridMap(e -> e + 1, x); // {{2,3,4},{5,6,7}} gridMap(e -> e * e, x); // {{1,4,9},{16,25,36}} Example 2: char[][] x = {{'h','E','l','l','O'},{'w','O','r','L','d'}}; gridMap(e -> Character.toUpperCase(e), x); // {{'H','E','L','L','O'},{'W','O','R','L','D'}} The solution in Java code Option 1: import java.util.function.Function; import java.util.Arrays; public class Solution { public static <T, R> Object[][] gridMap(Function<T, R> fn, T[][] list) { return Arrays.
Read More
How to Differentiate a Polynomial in Java
May 10, 2021
The challenge Create a function that differentiates a polynomial for a given value of x. Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer. Assumptions: There will be a coefficient near each x, unless the coefficient equals 1 or -1. There will be an exponent near each x, unless the exponent equals `` or 1. All exponents will be greater or equal to zero Examples: Equation.
Read More
Find the Sums of Perfect Squares in Java
May 9, 2021
The challenge The task is simply stated. Given an integer n (3 < n < 10<sup>9</sup>), find the length of the smallest list of perfect squares which add up to n. Come up with the best algorithm you can; you’ll need it! Examples: sum_of_squares(17) = 2 17 = 16 + 1 (4 and 1 are perfect squares). sum_of_squares(15) = 4 15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.
Read More
[Solved] Error: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.4.4:repackage (repackage)
May 8, 2021
If you have come across this error when trying to build and deploy your Spring Boot Maven application then this post will help you! Error: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.4.4:repackage (repackage) How to fix the Repackage Execute Goal Error You need to make sure you have the mainClass explicitly defined under your build->plugin as follows: <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.example.apps.YourApplication</mainClass> </configuration> </plugin> </plugins> </build>
Read More
[Solved] No main manifest attribute Solution for Jar/Maven/Gradle/Spring Boot
May 7, 2021
You’ve built a Java project and packaged a .jar file. You are ready to run it outside your IDE, or deploy it somewhere. When you run it using java -jar <your.jar> it says something like this: no main manifest attribute, in /src/project/target/your-jar-1.0-SNAPSHOT.jar How to add a Manifest file You need to create a META-INF/MANIFEST.MF file with the following content: Main-Class: com.mypackage.MyClass The class name com.mypackage.MyClass is the main class that has the public static void main(String[] args) entry point in your application.
Read More
[Solved] Error – The following untracked working tree files would be overwritten by merge
May 6, 2021
So you just tried to do a git pull and got the following error: error: The following untracked working tree files would be overwritten by merge: How to fix Untracked Working Trees Overwritten Merge You can fix this error by first adding and stashing your local files before performing the pull. git add * git stash git pull
Read More
How to Strip Script Tags in PHP
May 5, 2021
If you have some HTML input submitted from a user to your application, before saving it to the database, you may want to strip all <script> tags so that you can prevent cross site scripting attacks and other potential issues. Below we use a Regular Expression to strip the script tag out of a variable. $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
Read More
How to Make a Spiral in Java
May 4, 2021
The challenge Your task, is to create a NxN spiral with a given size. For example, spiral with size 5 should look like this: 00000 ....0 000.0 0...0 00000 and with the size 10: 0000000000 .........0 00000000.0 0......0.0 0.0000.0.0 0.0..0.0.0 0.0....0.0 0.000000.0 0........0 0000000000 Return value should contain array of arrays, of `` and 1, for example for given size 5 result should be: [[1,1,1,1,1],[0,0,0,0,1],[1,1,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Because of the edge-cases for tiny spirals, the size will be at least 5.
Read More
Find the Longest Common Subsequence in Java
May 3, 2021
The challenge from Wikipedia: The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to all sequences in a set of sequences. It differs from problems of finding common substrings: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences. Task Write a function lcs that accepts two strings and returns their longest common subsequence as a string. Performance matters. Examples lcs( "abcdef", "abc" ) => "abc" lcs( "abcdef", "acf" ) => "acf" lcs( "132535365", "123456789" ) => "12356" lcs( "abcdefghijklmnopq", "apcdefghijklmnobq" ) => "acdefghijklmnoq" Notes The subsequences of "abc" are "", "a", "b", "c", "ab", "ac", "bc", "abc".
Read More
Find First and Last Position of Element in Sorted Array in Java
May 2, 2021
The challenge Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. Follow up: Could you write an algorithm with O(log n) runtime complexity? Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] Example 3:
Read More
Determine if Number is a Power of Three in Java
May 1, 2021
The challenge Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3<sup>x</sup>. Example 1: Input: n = 27 Output: true Example 2: Input: n = 0 Output: false Example 3: Input: n = 9 Output: true Example 4: Input: n = 45 Output: false Constraints:
Read More
How to Count Binary Substrings in Java
April 30, 2021
The challenge Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. Example 1: Input: "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "
Read More
How to Download a CSV file using Javascript
April 29, 2021
Ever wanted to generate a CSV (comma separated values) file directly from the browser, using Javascript? Instead of going to the server.. Look no further! Create a function to download a csv file function downloadCsv(csvData: string, filename: string) { const blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' }); const dwldLink = document.createElement("a"); const url = URL.createObjectURL(blob); const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1; //if Safari open in new window to save file with random filename.
Read More
Array Range between Integers in Java
April 28, 2021
The challenge Complete the function that takes two integers (a, b, where a < b) and return an array of all integers between the input parameters, including them. For example: a = 1 b = 4 //[1, 2, 3, 4] The solution in Java code Option 1: public class Solution { public static int[] between(int a, int b) { return java.util.stream.IntStream.rangeClosed(a, b).toArray(); } } Option 2: public class Solution { public static int[] between(int a, int b) { int length = 0; for(int k = a; k <= b; k++){ length++; } int[] array = new int[length]; int first = a; for(int i = 0; i < length; i++){ array[i] = first; first++; } return array; } } Option 3:
Read More
How to clone a table structure in MySQL
April 27, 2021
I have often needed to clone a table without it’s data in MySQL. Oftentimes this has been because I have a continually growing temporary table and I just need to clear up some disk space. And it’s a lot faster and more guaranteed than trying to delete and optimise the table. Clone a table structure without it’s data Let’s say that your table in question is called table1: create table table1tmp like table1; drop table table1; rename table table1tmp to table1; If you run the above queries either in quick succession, or altogether in a single statement, you will notice that this is a very fast method even on very big tables.
Read More
Number of Rectangles in a Grid in Java
April 26, 2021
The challenge Given a grid of size m x n, calculate the total number of rectangles contained in this rectangle. All integer sizes and positions are counted. Examples: numberOfRectangles(3, 2) == 18 numberOfRectangles(4, 4) == 100 Here is how the 3×2 grid works (Thanks to GiacomoSorbi for the idea): 1 rectangle of size 3×2: [][][] [][][] 2 rectangles of size 3×1: [][][] 4 rectangles of size 2×1: [][] 2 rectangles of size 2×2
Read More
Longest vowel chain in Java
April 25, 2021
The challenge The vowel substrings in the word codewarriors are o,e,a,io. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any of aeiou. The solution in Java code Option 1: import static java.util.stream.Stream.of; interface Solution { static int solve(String s) { return of(s.split("[^aeiou]")).mapToInt(String::length).max().orElse(0); } } Option 2:
Read More
Determine Unique String Characters in Java
April 24, 2021
The challenge In this challenge, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings. For example: solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first string. Notice also that you return the characters from the first string concatenated with those from the second string.
Read More
Difference of Volumes of Cuboids in Java
April 23, 2021
The challenge In this simple exercise, you will create a program that will take two lists of integers, a and b. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids a and b. You must find the difference of the cuboids’ volumes regardless of which is bigger. For example, if the parameters passed are ([2, 2, 3], [5, 4, 1]), the volume of a is 12 and the volume of b is 20.
Read More
Sort by binary ones in Java
April 22, 2021
The challenge In this example you need to implement a function that sort a list of integers based on it’s binary representation. The rules are simple: sort the list based on the amount of 1’s in the binary representation of each number. if two numbers have the same amount of 1’s, the shorter string goes first. (ex: “11” goes before “101” when sorting 3 and 5 respectively) if the amount of 1’s is same, lower decimal number goes first.
Read More
Binomial Expansion in Java
April 21, 2021
The challenge Write a program that can do some algebra. Write a function expand that takes in an expression with a single, one character variable, and expands it. The expression is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any single character variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable.
Read More
Consecutive strings in Java
April 20, 2021
The challenge You are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array. Examples strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2 Concatenate the consecutive strings of strarr by 2, we get: treefoling (length 10) concatenation of strarr[0] and strarr[1] folingtrashy (" 12) concatenation of strarr[1] and strarr[2] trashyblue (" 10) concatenation of strarr[2] and strarr[3] blueabcdef (" 10) concatenation of strarr[3] and strarr[4] abcdefuvwxyz (" 12) concatenation of strarr[4] and strarr[5] Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
Read More
Determine the Highest Scoring Word in Java
April 19, 2021
The challenge Given a string of words, you need to find the highest scoring word. Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. You need to return the highest scoring word as a string. If two words score the same, return the word that appears earliest in the original string. All letters will be lowercase and all inputs will be valid.
Read More
Solving Speed Control in Java
April 18, 2021
The challenge In John’s car the GPS records every s seconds the distance travelled from an origin (distances are measured in an arbitrary but consistent unit). For example, below is part of a record with s = 15: x = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25] The sections are: 0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25 We can calculate John’s average hourly speed on every section and we get:
Read More
Calculate Miles per Gallon to Kilometers per Litre in Java
April 17, 2021
The challenge Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input). Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5. Some useful associations relevant to this challenge: 1 Imperial Gallon = 4.
Read More
How to Convert an Int to a List of Ints in Python
April 16, 2021
The challenge Given a non-negative integer, return an array / a list of the individual digits in order. Examples: 123 => [1,2,3] 1 => [1] 8675309 => [8,6,7,5,3,0,9] The solution in Python code Option 1: def digitize(n): return [int(d) for d in str(n)] Option 2: def digitize(n): return list(map(int, str(n))) Option 3: def digitize(n): lst = [] if n == 0: return [0] while n: n,r = divmod(n,10) lst.append(r) lst.reverse() return lst Test cases to validate our solution import test from solution import digitize @test.
Read More
Find the Greatest Common Divisor in Java
April 15, 2021
The challenge Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution. The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1. The solution in Java code Option 1 (using Euclidean Algorithm): public class GCD { public static int compute(int x, int y) { return (x % y !
Read More
How to Create a Circular List in Python
April 14, 2021
The challenge Create a Circular List A circular list is of finite size, but can infititely be asked for its previous and next elements. This is because it acts like it is joined at the ends and loops around. For example, imagine a CircularList of [1, 2, 3, 4]. Five invocations of next() in a row should return 1, 2, 3, 4 and then 1 again. At this point, five invocations of prev() in a row should return 4, 3, 2, 1 and then 4 again.
Read More
How to Guess the Sequence in Java
April 13, 2021
The challenge You must guess a sequence and it has something to do with the number given. Example x = 16 result = [1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9] The solution in Java code Option 1: import java.util.stream.IntStream; class Challenge { static int[] sequence(int x) { return IntStream.rangeClosed(1, x) .mapToObj(String::valueOf) .sorted() .mapToInt(Integer::parseInt) .toArray(); } } Option 2: import java.util.*; class Challenge { static int[] sequence(int x) { String arr[] = new String[x]; for(int i =1;i<=x;i++){ arr[i-1]= ""+i; } Arrays.
Read More
Reversed sequence in Java
April 12, 2021
The challenge Build a function that returns an array of integers from n to 1 where n>0. Example : n=5 –> [5,4,3,2,1] The solution in Java code Option 1: public class Sequence{ public static int[] reverse(int n) { if (n<=0) return null; int[] out = new int[n]; for (int i=n, j=0; i>0; i--) { out[j] = i; j++; } return out; } } Option 2: import java.util.stream.IntStream; public class Sequence{ public static int[] reverse(int n) { return IntStream.
Read More
Count the Digit in Java
April 11, 2021
The challenge Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or …) the function taking n and d as parameters and returning this count. Examples: n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 We are using the digit 1 in 1, 16, 81, 100.
Read More
Multiply all elements in an array in Java
April 10, 2021
The challenge Create a function multiplyAll/multiply_all which takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array. The returned array should consist of each of the elements from the first array multiplied by the integer. Example: multiplyAll([1, 2, 3])(2) = [2, 4, 6]; You must not mutate the original array. The solution in Java code Option 1:
Read More
[Solved] Fatal: refusing to merge unrelated histories in Git
April 9, 2021
You have received the dreaded fatal: refusing to merge unrelated histories error! You might find yourself asking one of the following questions: What is refusing to merge unrelated histories? How do you combine two unrelated histories? What is unrelated history in git? How do you fix unrelated branches? Well look no further, below you will learn how to solve this problem quickly and also learn about why it happens in the first place.
Read More
Credit Card Mask in Java
April 8, 2021
The challenge Usually when you buy something, you’re asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don’t want that shown on your screen. Instead, we mask it. Your task is to write a function maskify, which changes all but the last four characters into '#'. Examples Maskify.Maskify("4556364607935616"); // should return "############5616" Maskify.
Read More
How to Reverse a Number in Java
April 7, 2021
The challenge Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321) Numbers should preserve their sign; i.e. a negative number should still be negative when reversed. Examples 123 -> 321 -456 -> -654 1000 -> 1 The solution in Java code Option 1: public class ReverseNumber { public static int reverse(int number) { int result = 0; while(number != 0) { result = result * 10 + number % 10; number = number / 10; } return result; } } Option 2:
Read More
Positions Average in Java
April 6, 2021
The challenge Suppose you have 4 numbers: '0', '9', '6', '4' and 3 strings composed with them: s1 = "6900690040" s2 = "4690606946" s3 = "9990494604" Compare s1 and s2 to see how many positions they have in common: `` at index 3, 6 at index 4, 4 at index 8 ie 3 common positions out of ten. Compare s1 and s3 to see how many positions they have in common: 9 at index 1, `` at index 3, 9 at index 5 ie 3 common positions out of ten.
Read More
Determine the Date by the Day Number in Java
April 5, 2021
The challenge What date corresponds to the nth day of the year? The answer depends on whether the year is a leap year or not. Write a function that will help you determine the date if you know the number of the day in the year, as well as whether the year is a leap year or not. The function accepts the day number and a boolean value isLeap as arguments, and returns the corresponding date of the year as a string "Month, day".
Read More
Correct the time-string in Java
April 4, 2021
The challenge You have to create a method, that corrects a given time string. There was a problem in addition, so many of the time strings are broken. Time is formatted using the 24-hour clock, so from 00:00:00 to 23:59:59. Examples "09:10:01" -> "09:10:01" "11:70:10" -> "12:10:10" "19:99:99" -> "20:40:39" "24:01:01" -> "00:01:01" The solution in Java code Option 1: public class Solution { public static String timeCorrect(String timestring) { if (timestring == null || !
Read More
Shifter Words Challenge in Java
April 3, 2021
The challenge You probably know that some characters written on a piece of paper, after turning this sheet 180 degrees, can be read, although sometimes in a different way. So, uppercase letters “H”, “I”, “N”, “O”, “S”, “X”, “Z” after rotation are not changed, the letter “M” becomes a “W”, and Vice versa, the letter “W” becomes a “M”. We will call a word “shifter” if it consists only of letters “H”, “I”, “N”, “O”, “S”, “X”, “Z”, “M” and “W”.
Read More
Find Maximum and Minimum Values of a List in Java
April 2, 2021
The challenge Make two functions, max and min that take a(n) array/vector of integers list as input and outputs, respectively, the largest and lowest number in that array/vector. Examples max({4,6,2,1,9,63,-134,566}) returns 566 min({-52, 56, 30, 29, -54, 0, -110}) returns -110 max({5}) returns 5 min({42, 54, 65, 87, 0}) returns 0 Additionally You may consider that there will not be any empty arrays/vectors. The solution in Java code Option 1:
Read More
Valid Parentheses in Java
April 1, 2021
The challenge Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it’s invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all.
Read More
Boggle Word Checker in Java
March 31, 2021
The challenge Write a function that determines whether a string is a valid guess in a Boggle board, as per the rules of Boggle. A Boggle board is a 2D array of individual characters, e.g.: [ ['I','L','A','W'], ['B','N','G','E'], ['I','U','A','O'], ['A','S','R','L'] ] Valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without re-using any previously used cells. For example, in the above board “BINGO”, “LINGO”, and “ILNBIA” would all be valid guesses, while “BUNGIE”, “BINS”, and “SINUS” would not.
Read More
Build a pile of Cubes in Kotlin
March 30, 2021
The challenge Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
Read More
Which x for that sum in Kotlin
March 29, 2021
The challenge Consider the sequence U(n, x) = x + 2x**2 + 3x**3 + .. + nx**n where x is a real number and n a positive integer. When n goes to infinity and x has a correct value (ie x is in its domain of convergence D), U(n, x) goes to a finite limit m depending on x. Usually given x we try to find m. Here we will try to find x (x real, 0 < x < 1) when m is given (m real, m > 0).
Read More
Reverse the bits in an integer in Java
March 28, 2021
The challenge Write a function that reverses the bits in an integer. For example, the number 417 is 110100001 in binary. Reversing the binary is 100001011 which is 267. You can assume that the number is not negative. The solution in Java code Option 1: import static java.lang.Integer.*; interface BitsOfInteger { static int reverse_bits(int n) { return parseInt(new StringBuilder(toBinaryString(n)).reverse() + "", 2); } } Option 2: public class BitsOfInteger { public static int reverse_bits(int n) { return Integer.
Read More
Invert values in Kotlin
March 27, 2021
The challenge Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] The solution in Kotlin code Option 1: fun invert(arr: IntArray) = arr.map { -it }.toIntArray() Option 2: fun invert(arr: IntArray): IntArray { return IntArray(arr.size){ -arr[it] } } Option 3: fun invert(arr: IntArray): IntArray { var x = 0 while (x < arr.
Read More
Spring Boot no main manifest attribute, in
March 26, 2021
You have created a ./target/.jar and have tried to run it using java -jar <app>.jar yet receive a spring boot no main manifest attribute, in <app>.jar error. Good thing is that this is really easy to solve! You can generate your jar as follows instead: mvn package spring-boot:repackage Or you could adjust your pom.xml so that you can generate your jar using a simple mvn package: <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.
Read More
Moduli number system in Kotlin
March 25, 2021
The challenge A number system with moduli is defined by a vector of k moduli, [m1,m2, ···,mk]. The moduli must be pairwise co-prime, which means that, for any pair of moduli, the only common factor is 1. In such a system each number n is represented by a string "-x1--x2-- ... --xk-" of its residues, one for each modulus. The product m1 * ... * mk must be greater than the given number n which is to be converted in the moduli number system.
Read More
Smallest possible sum in Kotlin
March 24, 2021
The challenge Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required: if X[i] > X[j] then X[i] = X[i] - X[j] When no more transformations are possible, return its sum (“smallest possible sum”). For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below: X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9 X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6 X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6 X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3 X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3 The returning output is the sum of the final transformation (here 9).
Read More
Floating-point Approximation in Kotlin
March 23, 2021
The challenge Given a semi-inclusive interval I = [l, u) (l is in interval I but u is not) l and u being floating numbers (0 <= l < u), an integer n (n > 0) a function f: x (float number) -> f(x) (float number) we want to return as a list the n values: f(l), f(l + d), ..., f(u -d) where d = (u - l) / n
Read More
Multiplication table in Kotlin
March 22, 2021
The challenge Create an NxN multiplication table, of size provided in parameter. for example, when given size is 3: 1 2 3 2 4 6 3 6 9 for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]] The solution in Kotlin Option 1: package solution object Solution { fun multiplicationTable(size: Int) = Array<IntArray>(size) { i -> (1..size).map { it * (i + 1) }.toIntArray() } } Option 2: package solution object Solution { fun multiplicationTable(size: Int): Array<IntArray> { return Array(size){i -> IntArray(size){(it + 1) * (i + 1)}} } } Option 3:
Read More
Strip Comments in Kotlin
March 21, 2021
The challenge Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. Example: Given an input string of: apples, pears # and bananas grapes bananas !apples The output expected would be: apples, pears grapes bananas The code would be called like so: var result = solution("apples, pears # and bananas\ngrapes\nbananas !
Read More
Experimenting with a sequence of complex numbers in Kotlin
March 20, 2021
The challenge Consider the sequence S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n) where z is a complex number and n a positive integer (n > 0). When n goes to infinity and z has a correct value (ie z is in its domain of convergence D), S(n, z) goes to a finite limit lim depending on z. Experiment with S(n, z) to guess the domain of convergence Dof S and lim value when z is in D.
Read More
pt-online-schema-change Add Index
March 19, 2021
Percona has a great toolkit that allows you to perform schema changes on a MySQL or MariaDB database without any downtime, it works by creating a new table with the same schema, making the changes to it and applying triggers for insertion, deletion and all updates, all while performing your valuable schema updates for you! How to Add an Index to a MySQL or MariaDB database without downtime pt-online-schema-change --alter 'add index ix_<COLUMN_NAME> (<COLUMN_NAME>)' D=<DATABASE_NAME>,t=<TABLE_NAME> --dry-run
Read More
Sums of Parts in Kotlin
March 18, 2021
The challenge Let us consider this example (array written in general format): ls = [0, 1, 3, 6, 10] Its following parts: ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = [] The corresponding sums are (put together in a list): [20, 20, 19, 16, 10, 0] The function parts_sums (or its variants in other languages) will take as parameter a list ls and return a list of the sums of its parts as defined above.
Read More
Diophantine Equation in Kotlin
March 17, 2021
The challenge In mathematics, a Diophantine equation is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied. In this challenge we want to find all integers x, y (x >= 0, y >= 0) solutions of a diophantine equation of the form: x2 – 4 * y2 = n (where the unknowns are x and y, and n is a given positive number) in decreasing order of the positive xi.
Read More
Matrix Addition in Java
March 16, 2021
The challenge Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers. How to sum two matrices: Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix.
Read More
Numbers that are a power of their sum of digits in Java
March 15, 2021
The challenge The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let’s see both cases with the details 8 + 1 = 9 and 92 = 81 512 = 5 + 1 + 2 = 8 and 83 = 512
Read More
Integer triangles in Java
March 14, 2021
The challenge You have to give the number of different integer triangles with one angle of 120 degrees which perimeters are under or equal a certain value. Each side of an integer triangle is an integer value. // number of integer triangles, give_triang(max. perimeter) with sides a, b, and c integers such that: a + b + c <= max. perimeter See some of the following cases // No Integer triangles with perimeter under or equal five give_triang(5) // 0 // One integer triangle of (120 degrees).
Read More
Minimum path in squares in Java
March 13, 2021
The challenge You’re given a square consisting of random numbers, like so: var square = [ [1,2,3], [4,8,2], [1,5,3] ]; Your job is to calculate the minimum total cost when moving from the upper left corner to the coordinate given. You’re only allowed to move right or down. In the above example the minimum path would be: var square = [ [1,2,3], [_,_,2], [_,_,3] ]; Giving a total of 11. Start and end position are included.
Read More
Pascal’s Diagonals in Java
March 12, 2021
The challenge Create a function that returns an array containing the first l digits from the nth diagonal of Pascal’s triangle. n = 0 should generate the first diagonal of the triangle (the ‘ones’). The first number in each diagonal should be 1. If l = 0, return an empty array. Assume that both n and l will be non-negative integers in all test cases. The solution in Java code Option 1:
Read More
Maximum Contiguous Sum in Java
March 11, 2021
The challenge Given an unsorted array of integer values, find the maximum positive sum of any contiguous range within the array. An array containing only negative values can return 0. Your solution should be efficient enough to not throw a timeout exception. Example: // returns 24 maxContiguousSum([3, -4, 8, 7, -10, 19, -3]); // returns 5 maxContiguousSum([-8, -10, -12, -2, -3, 5]); Visual example: [3, -4, 8, 7, -10, 19, -3] |_____________| || \/ 24 The solution in Java code Option 1:
Read More
Fibonacci Streaming in Java
March 10, 2021
The challenge You’re going to provide a needy programmer a utility method that generates an infinite sized, sequential IntStream which contains all the numbers in a fibonacci sequence. A fibonacci sequence starts with two 1s. Every element afterwards is the sum of the two previous elements. See: 1, 1, 2, 3, 5, 8, 13, ..., 89, 144, 233, 377, ... The solution in Java code Option 1: import java.util.function.IntSupplier; import java.
Read More
Base-2 in Java
March 9, 2021
The challenge In this challenge you must convert integers numbers from and to a negative-base binary system. Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations. To help understand, the first eight digits (in decimal) of the Base(-2) system is:
Read More
Unique digits sequence in Java
March 8, 2021
The challenge Consider the following series: 0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...There is nothing special between numbers `` and 10. Let’s start with the number 10 and derive the sequence. 10 has digits 1 and . The next possible number that does not have a&nbsp;`1`&nbsp;or a&nbsp; is 22. All other numbers between 10 and 22 have a 1 or a ``. From 22, the next number that does not have a 2 is 11. Note that 30 is also a possibility because it is the next higher number that does not have a 2, but we must select the lowest number that fits and is not already in the sequence.
Read More
Palindrome integer composition in Java
March 7, 2021
The challenge The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that 1 = 0^2 + 1^2 has not been included as this problem is concerned with the squares of positive integers.
Read More
Count IP Addresses in Java
March 6, 2021
The challenge Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one. Examples ips_between("10.0.0.0", "10.0.0.50") == 50 ips_between("10.0.0.0", "10.0.1.0") == 256 ips_between("20.0.0.10", "20.0.1.0") == 246 The solution in Java code Option 1: public class CountIPAddresses { public static long ipsBetween(String start, String end) { return convertToLong(end) - convertToLong(start); } private static long convertToLong(String ip) { long res = 0; for (String s : ip.
Read More
Shortest Knight Path in Java
March 5, 2021
The challenge Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other. The positions will be passed as two arguments in algebraic notation. For example, knight("a3", "b5") should return 1. The knight is not allowed to move off the board. The board is 8×8. For information on knight moves, see https://en.wikipedia.org/wiki/Knight_%28chess%29 For information on algebraic notation, see https://en.
Read More
All Balanced Parentheses in Java
March 4, 2021
The challenge Write a function that makes a list of strings representing all of the ways you can balance n pairs of parentheses Examples balancedParens(0) returns ArrayList<String> with element: "" balancedParens(1) returns ArrayList<String> with element: "()" balancedParens(2) returns ArrayList<String> with elements: "()()","(())" balancedParens(3) returns ArrayList<String> with elements: "()()()","(())()","()(())","(()())","((()))" The solution in Java code Option 1: import java.util.ArrayList; public class BalancedParens { public static ArrayList <String> balancedParens (int n) { ArrayList<String> lst = new ArrayList<>(); StringBuilder sb = new StringBuilder(); dfs(sb,lst,0,0,n); return lst; } private static void dfs(StringBuilder sb, ArrayList<String> lst, int open, int close, int max) { if (close==max) { lst.
Read More
Human readable duration format in Java
March 3, 2021
The challenge Your task in order to complete this challenge is to write a function which formats a duration, given as a number of seconds, in a human-friendly way. The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds. It is much easier to understand with an example: //returns "1 minute and 2 seconds" TimeFormatter.
Read More
Simple string expansion in Java
March 2, 2021
The challenge Consider the following expansion: // because "ab" repeats 3 times solve("3(ab)") == "ababab" // because "a3(b)" == "abbb", which repeats twice. solve("2(a3(b))") == "abbbabbb" Given a string, return the expansion of that string. Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis. The solution in Java code Option 1: class Solution{ public static String solve(String s){ String new_s = ""; for(char ch : new StringBuilder(s).
Read More
Hamming Numbers in Java
March 1, 2021
The challenge A Hamming number is a positive integer of the form 2i3j5k, for some non-negative integers i, j, and k. Write a function that computes the _n_th smallest Hamming number. Specifically: The first smallest Hamming number is 1 = 235 The second smallest Hamming number is 2 = 2135 The third smallest Hamming number is 3 = 2315 The fourth smallest Hamming number is 4 = 2235 The fifth smallest Hamming number is 5 = 2351 The 20 smallest Hamming numbers are given in example test fixture.
Read More
Block sequence in Java
February 28, 2021
The challenge Consider the following array: [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...] If we join these blocks of numbers, we come up with an infinite sequence which starts with 112123123412345123456.... The list is infinite. You will be given an number (n) and your task will be to return the element at that index in the sequence, where 1 ≤ n ≤ 10^18. Assume the indexes start with 1, not ``.
Read More
Roman Numerals Helper in Java
February 27, 2021
The challenge Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method. Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC.
Read More
Closest pair of points in linearithmic time in Java
February 26, 2021
The challenge Given a number of points on a plane, your task is to find two points with the smallest distance between them in linearithmic O(n log n) time. Example 1 2 3 4 5 6 7 8 9 1 2 . A 3 . D 4 . F 5 . C 6 7 . E 8 . B 9 . G For the plane above, the input will be:
Read More
Find sum of top-left to bottom-right diagonals in Java
February 25, 2021
The challenge Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on… Examples array = [[1, 2], [3, 4]] diagonal sum: 1 + 4 = 5 array = [[5, 9, 1, 0], [8, 7, 2, 3], [1, 4, 1, 9], [2, 3, 8, 2]] diagonal sum: 5 + 7 + 1 + 2 = 15 The solution in Java code Option 1:
Read More
Sweeping trees in Java
February 24, 2021
The challenge You will be given a list of strings representing nodes in a rooted tree. A visual representation of a very simple rooted tree could be: +----+ |root| ++--++ | | +----+ +----+ v v +------+ +------+ |node A| |node B| +------+ +------+ In this case, the root node has two children, nodes A and B. A more complex example would be: +----+ |root| ++--++ | | +----+ +----+ v v +------+ +------+ |node A| |node B| +--+---+ +------+ | +-------------+ v v +------+ +------+ |Node C| |node D| +------+ +------+ Here, The root has two children (nodes A and B), and node A in turn also has two children (nodes C and D).
Read More
Detect Pangram in Java
February 23, 2021
The challenge A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence “The quick brown fox jumps over the lazy dog” is a pangram, because it uses the letters A-Z at least once (case is irrelevant). Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. The solution in Java code Option 1 (using a Character loop):
Read More
Remove the parentheses in Java
February 22, 2021
The challenge In this challenge you are given a string for example: "example(unwanted thing)example" Your task is to remove everything inside the parentheses as well as the parentheses themselves. The example above would return: "exampleexample" Notes Other than parentheses only letters and spaces can occur in the string. Don’t worry about other brackets like "[]" and "{}" as these will never appear. There can be multiple parentheses. The parentheses can be nested.
Read More
What century is it in Java
February 21, 2021
The challenge Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. Examples "1999" --> "20th" "2011" --> "21st" "2154" --> "22nd" "2259" --> "23rd" "1124" --> "12th" "2000" --> "20th" The solution in Java code Option 1: public class Solution{ public static String whatCentury(int year) { int century = (year + 99) / 100; if (century / 10 == 1) return century + "th"; switch(century % 10) { case 1: return century + "st"; case 2: return century + "nd"; case 3: return century + "rd"; default: return century + "th"; } } } Option 2:
Read More
Lost number in number sequence in Java
February 20, 2021
The challenge An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted. Example: The starting array sequence is [1,2,3,4,5,6,7,8,9] The mixed array with one deleted number is [3,2,4,6,7,8,1,9] Your function should return the int 5. If no number was deleted from the array and no difference with it, your function should return the int ``.
Read More
Simple string reversal in Java
February 19, 2021
The challenge In this challenge, we are going to reverse a string while maintaining the spaces (if any) in their original place. For example: solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo cruoy". solve("andrew") = "werdna" More examples in the test cases. All input will be lower case letters and in some cases spaces.
Read More
int32 to IPv4 in Java
February 18, 2021
The challenge Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits). 1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 4th octet 1 has the binary representation: 00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001 Because the above IP address has 32 bits, we can represent it as the unsigned 32-bit number: 2149583361
Read More
Perimeter of squares in a rectangle in Java
February 17, 2021
The challenge The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80 Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:
Read More
Palindrome chain length in Java
February 16, 2021
The challenge Number is a palindrome if it is equal to the number with digits in reversed order. For example, 5, 44, 171, 4884 are palindromes, and 43, 194, 4773 are not. Write a function which takes a positive integer and returns the number of special steps needed to obtain a palindrome. The special step is: “reverse the digits, and add to the original number”. If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
Read More
String array duplicates in Java
February 15, 2021
The challenge You are given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array. For example: dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]. dup(["kelless","keenness"]) = ["keles","kenes"]. Strings will be lowercase only, no spaces. See test cases for more examples. The solution in Java code Option 1 (using StringBuilders): class Solution{ public static String[] dup(String[] arr){ String[] strings = new String[arr.length]; for (int h = 0; h < arr.
Read More
Even or Odd Array Sum in Java
February 14, 2021
The challenge Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching "odd" or "even". If the input array is empty consider it as: [0] (array with a zero). Example: odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even" The solution in Java code Option 1 (using streams): public class Solution { public static String oddOrEven (int[] array) { return (java.
Read More
String Permutations in Java
February 13, 2021
The challenge In this challenge, you have to create all permutations of an input string and remove duplicates if present. This means you have to shuffle all letters from the input in all possible orders. Examples: Permutations.singlePermutations("a") // ["a"] Permutations.singlePermutations("ab") // ["ab", "ba"] Permutations.singlePermutations("aabb") // ["aabb","abab","abba","baab","baba","bbaa"] The order of the permutations doesn’t matter. The solution in Java code Option 1: import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import java.util.List; class Permutations { public static List<String> singlePermutations(final String s) { return permute("", s); } private static List<String> permute(final String prefix, final String s) { return s.
Read More
Remove a Specific Element of an Array in Java
February 12, 2021
The challenge You will be given a certain array of length n, such that n > 4, having positive and negative integers but there will be no zeroes and all the elements will occur once in it. We may obtain an amount of n sub-arrays of length n - 1, removing one element at a time (from left to right). For each subarray, let’s calculate the product and sum of its elements with the corresponding absolute value of the quotient, q = SubProduct/SubSum (if it is possible, SubSum cannot be 0).
Read More
Upside down numbers in Java
February 11, 2021
The challenge Consider the numbers 6969 and 9116. When you rotate them 180 degrees (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as 2 or 5 don’t yield numbers when rotated. Given a range, return the count of upside down numbers within that range.
Read More
Rotate matrix counter-clockwise N times in Java
February 10, 2021
The challenge In this challenge your mission is to rotate matrix counter-clockwise N times. So, you will have 2 inputs: 1) matrix 2) a number, how many times to turn it And the output is turned matrix. Example: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] times_to_turn = 1 It should return this: [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]) Note: all matrixes will be square.
Read More
Unable to import module “lambda_function”: No module named “pymysql”
February 9, 2021
If you receive the following error message when trying to run pymysql on AWS Lambda: Unable to import module "lambda_function": No module named "pymysql" then you can fix this by running a Custom Lambda Layer. To do this, you can boot up an EC2 instance (or a Linux instance anywhere else) and run the following set of commands: #create module directory mkdir -p temp/python cd temp/python #install pymysql module pip install pymysql -t .
Read More
Square Matrix Multiplication in Java
February 8, 2021
The challenge Write a function that accepts two square (NxN) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given. How to multiply two square matrices: We are given two matrices, A and B, of size 2×2 (note: tests are not limited to 2×2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell [0][0] of matrix C, you need to compute: A[0][0] * B[0][0] + A[0][1] * B[1][0].
Read More
Count the divisible numbers in Java
February 7, 2021
The challenge Complete the function that takes 3 numbers x, y and k (where x ≤ y), and returns the number of integers within the range [x..y] (both ends included) that are divisible by k. More scientifically: { i : x ≤ i ≤ y, i mod k = 0 } Example Given x = 6, y = 11, k = 2 the function should return 3, because there are three numbers divisible by 2 between 6 and 11: 6, 8, 10
Read More
Averages of numbers in Java
February 6, 2021
The challenge Get the averages of these numbers Write a method, that gets an array of integer-numbers and return an array of the averages of each integer-number and his follower, if there is one. Example: Input: [ 1, 3, 5, 1, -10] Output: [ 2, 4, 3, -4.5] If the array has 0 or 1 values or is null, your method should return an empty array. The solution in Java code Option 1:
Read More
Decimal to Factorial and Back in Java
February 5, 2021
The challenge Coding decimal numbers with factorials is a way of writing out numbers in a base system that depends on factorials, rather than powers of numbers. In this system, the last digit is always `` and is in base 0!. The digit before that is either 0 or 1 and is in base 1!. The digit before that is either 0, 1, or 2 and is in base 2!, etc.
Read More
Vowel Count in Java
February 4, 2021
The challenge Return the number (count) of vowels in the given string. We will consider a, e, i, o, u as vowels for this challenge (but not y). The input string will only consist of lower case letters and/or spaces. The solution in Java code Option 1: public class Vowels { public static int getCount(String str) { int vowelsCount = 0; char[] chars = str.toCharArray(); for (char c : chars) { if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') vowelsCount++; } return vowelsCount; } } Option 2:
Read More
Equal Sides Of An Array in Java
February 3, 2021
The challenge You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. For example: Let’s say you are given the array {1,2,3,4,3,2,1}:
Read More
Largest 5 digit number in a series in Java
February 2, 2021
The challenge In the following 6 digit number: 283910 91 is the greatest sequence of 2 consecutive digits. In the following 10 digit number: 1234567890 67890 is the greatest sequence of 5 consecutive digits. Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five-digit integer.
Read More
Next smaller number with the same digits in Java
February 1, 2021
The challenge Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits. For example: nextSmaller(21) == 12 nextSmaller(531) == 513 nextSmaller(2071) == 2017 Return -1 (for Haskell: return Nothing, for Rust: return None), when there is no smaller number that contains the same digits. Also return -1 when the next smaller number with the same digits would require the leading digit to be zero.
Read More
Count of positives / sum of negatives in Java
January 31, 2021
The challenge Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. If the input array is empty or null, return an empty array. Example For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65]. The solution in Java code Option 1:
Read More
Find the stray number in Java
January 30, 2021
The challenge You are given an odd-length array of integers, in which all of them are the same, except for one single number. Complete the method which accepts such an array, and returns that single different number. The input array will always be valid! (odd-length >= 3) Examples [1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3 The solution in Java code Option 1: import java.
Read More
4 By 4 Skyscrapers in Java
January 29, 2021
The challenge In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues: The height of the skyscrapers is between 1 and 4 No two skyscrapers in a row or column may have the same number of floors A clue is the number of skyscrapers that you can see in a row or column from the outside Higher skyscrapers block the view of lower skyscrapers located behind them Can you write a program that can solve this puzzle?
Read More
How to Fix: package org.junit.jupiter.api does not exist
January 28, 2021
The problem If you have received the package org.junit.jupiter.api deos not exist error when trying to run a JUnit Java Test with Maven, it’s because of a missing dependency in your pom.xml file. The solution Add the following dependency entry to your pom.xml file: <dependencies> <!-- add the junit dependency here --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> </dependencies>
Read More
How to Programmatically Filter ag-Grid Columns in Angular
January 27, 2021
You can easily control the column filtering in ag-Grid by using the getFilterInstance and setModel methods associated to the column you need filtering. Once done, remember to call onFilterChanged to apply your changes. // a list of all your items you want to filter // make sure to create a list of strings // a list of numbers won't work const listOfItems = data.map((row) => row.ComeColumnItem.toString()) // get the filter instance per column const filterInstance = this.
Read More
Sum by Factors in Java
January 26, 2021
The challenge Given an array of positive or negative integers I= [i<sub>1</sub>,..,i<sub>n</sub>] you have to produce a sorted array P of the form [ [p, sum of all i<sub>j</sub>&nbsp;of I for which p is a prime factor (p positive) of i<sub>j</sub>] ...] P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages.
Read More
Count the divisors of a number in Java
January 25, 2021
The challenge Count the number of divisors of a positive integer n. Random tests go up to n = 500000. Examples numberOfDivisors(4) == 3 // 1, 2, 4 numberOfDivisors(5) == 2 // 1, 5 numberOfDivisors(12) == 6 // 1, 2, 3, 4, 6, 12 numberOfDivisors(30) == 8 // 1, 2, 3, 5, 6, 10, 15, 30 The solution in Java code Option 1: public class FindDivisor { public long numberOfDivisors(int n) { long counter = 0; for(int i=1; i<=n; i++){ if(n % i == 0){ counter++; } } return counter; } } Option 2:
Read More
My smallest code interpreter in Java
January 24, 2021
The challenge Inspired from real-world Brainf**k, we want to create an interpreter of that language which will support the following instructions: > increment the data pointer (to point to the next cell to the right). < decrement the data pointer (to point to the next cell to the left). + increment (increase by one, truncate overflow: 255 + 1 = 0) the byte at the data pointer. - decrement (decrease by one, treat as unsigned byte: 0 – 1 = 255 ) the byte at the data pointer.
Read More
Pick peaks in Java
January 23, 2021
The challenge Write a function that returns the positions and the values of the “peaks” (or local maxima) of a numeric array. For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5). The output will be returned as a “Map<String,List>with two key-value pairs:“pos”and“peaks”. If there is no peak in the given array, simply return{“pos” => [], “peaks” => []}`.
Read More
Number of trailing zeros of N in Java
January 22, 2021
The challenge Write a program that will calculate the number of trailing zeros in a factorial of a given number. N! = 1 * 2 * 3 * ... * N Be careful 1000! has 2568 digits… For more info, see: http://mathworld.wolfram.com/Factorial.html Examples zeros(6) = 1 // 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 // 12!
Read More
Alphabetic Anagrams in Java
January 21, 2021
The challenge Consider a “word” as any sequence of capital letters A-Z (not limited to just “dictionary words”). For any word with at least two different letters, there are other words composed of the same letters but in a different order (for instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words; for our purposes “AAIILNORSTTY” is also a “word” composed of the same letters as these two). We can then assign a number to every word, based on where it falls in an alphabetically sorted list of all words made up of the same group of letters.
Read More
Remove file from Git without deleting locally
January 20, 2021
If you find yourself in a position where you have already committed some files to git, and they are in the remote repository already, but you want to remove them from you repository without deleting them locally, you can do the following: Introducing the git rm --cached command: Remove a folder from Git git rm --cached -r FolderName Remove a file from git git rm --cached SomeFile.ext And then what? Now that the files have been removed from the local git cache, you should probably either commit the changes you’ve made, or add an entry to your local .
Read More
Recover a secret string from random triplets in Java
January 19, 2021
The challenge There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string. A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. “whi” is a triplet for the string “whatisup”. As a simplification, you may assume that no letter occurs more than once in the secret string.
Read More
Range Extraction in Java
January 18, 2021
The challenge A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, ‘-‘. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example “12,13,15-17” Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Read More
Reversed Words in Java
January 17, 2021
The challenge Complete the solution so that it reverses all of the words within the string passed in. Example: ReverseWords.reverseWords("The greatest victory is that which requires no battle"); // should return "battle no requires which that is victory greatest The" The solution in Java code Option 1 (using StringBuilder): public class ReverseWords{ public static String reverseWords(String str){ String[] words = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i=words.length-1; i>=0; i--) { sb.
Read More
CamelCase Method in Java
January 16, 2021
The challenge Write a simple CamelCase method for strings. All words must have their first letter capitalized without spaces. Example: // "HelloCase" camelCase("hello case"); // "CamelCaseWord" camelCase("camel case word"); The solution in Java code Option 1: public class Solution { public static String camelCase(String str) { String[] words = str.trim().split("\\s+"); if (words.length==0) return ""; StringBuilder sb = new StringBuilder(); for (int i=0; i<words.length; i++) { String word = words[i]; if (word.
Read More
Even or Odd in Java
January 15, 2021
The challenge Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers. The solution in Java code public class EvenOrOdd { public static String even_or_odd(int number) { return number%2==0 ? "Even" : "Odd"; } } Test cases to validate our solution import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class EvenOrOddTest { @Test public void testEvenOrOdd() { EvenOrOdd eoo = new EvenOrOdd(); assertEquals(eoo.
Read More
Square Every Digit in Java
January 14, 2021
The challenge You need to square every digit of a number and concatenate them. For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. Note: The function accepts an integer and returns an integer. The solution in Java code Option 1: public class SquareDigit { public int squareDigits(int n) { String result = ""; while (n != 0) { int digit = n % 10 ; result = digit*digit + result ; n /= 10 ; } return Integer.
Read More
Simple number sequence in Java
January 13, 2021
The challenge You are given a string of numbers in sequence and your task will be to return the missing number. If there is no number missing or there is an error in the sequence, return -1. For example: missing("123567") = 4 missing("899091939495") = 92 missing("9899101102") = 100 missing("599600601602") = -1 -- no number missing missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing. The sequence will always be in ascending order.
Read More
Roman Numerals Encoder in Java
January 12, 2021
The challenge Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Read More
First Variation on Caesar Cipher in Java
January 11, 2021
The challenge The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from ‘a’ to ‘z’ or from ‘A’ to ‘Z’) with a different one a fixed number of places up or down the alphabet. This program performs a variation of the Caesar shift. The shift increases by 1 for each character (on each iteration). If the shift is initially 1, the first character of the message to be encoded will be shifted by 1, the second character will be shifted by 2, etc…
Read More
Century From Year in Java
January 10, 2021
The challenge The first century spans from the year 1 up to and including the year 100, The second – from the year 101 up to and including the year 200, etc. Task : Given a year, return the century it is in. Input, Output Examples centuryFromYear(1705) returns (18) centuryFromYear(1900) returns (19) centuryFromYear(1601) returns (17) centuryFromYear(2000) returns (20) The solution in Java code Option 1: public class Solution { public static int century(int number) { return (number + 99) / 100; } } Option 2:
Read More
Find the Smallest Number in Java
January 9, 2021
The challenge You have a positive number n consisting of digits. You can do at most one operation: Choosing the index of a digit in the number, remove this digit at that index and insert it back to another or at the same place in the number in order to find the smallest number you can get. #Task: Return an array or a tuple or a string depending on the language (see “Sample Tests”) with
Read More
Convert Array to Tree in Java
January 8, 2021
The challenge You are given a non-null array of integers. Implement the method arrayToTree which creates a binary tree from its values in accordance to their order, while creating nodes by depth from left to right. For example, given the array [17, 0, -4, 3, 15] you should create the following tree: 17 / \ 0 -4 / \ 3 15 The class TreeNode is available for you: class TreeNode { TreeNode left; TreeNode right; int value; TreeNode(int value, TreeNode left, TreeNode right) { this.
Read More
Common Denominators in Java
January 7, 2021
The challenge You will have a list of rationals in the form { {numer_1, denom_1} , ... {numer_n, denom_n} } or [ [numer_1, denom_1] , ... [numer_n, denom_n] ] or [ (numer_1, denom_1) , ... (numer_n, denom_n) ] where all numbers are positive ints. You have to produce a result in the form: (N_1, D) ... (N_n, D) or [ [N_1, D] ... [N_n, D] ] or [ (N_1', D) , .
Read More
Primes in Numbers in Java
January 6, 2021
The challenge Given a positive number n > 1 find the prime factor decomposition of n. The result will be a string with the following form : "(p1**n1)(p2**n2)...(pk**nk)" where a ** b means a to the power of b with the p(i) in increasing order and n(i) empty if n(i) is 1. Example: n = 86240 should return "(2**5)(5)(7**2)(11)" The solution in Java code Option 1: public class PrimeDecomp { public static String factors(int lst) { String result = ""; for (int fac = 2; fac <= lst; ++fac) { int count; for (count = 0; lst % fac == 0; ++count) { lst /= fac; } if (count > 0) { result += "(" + fac + (count > 1 ?
Read More
Maximum subarray sum in Java
January 5, 2021
The challenge The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: Max.sequence(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}); // should be 6: {4, -1, 2, 1} Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Read More
Validate Credit Card Number in Java
January 4, 2021
The challenge Let’s implement the Luhn Algorithm, which is used to help validate credit card numbers. Given a positive integer of up to 16 digits, return true if it is a valid credit card number, and false if it is not. Here is the algorithm: Double every other digit, scanning from right to left, starting from the second digit (from the right).Another way to think about it is: if there are an even number of digits, double every other digit starting with the first; if there are an odd number of digits, double every other digit starting with the second:1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4] 12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5] 891 ==> [8, 9*, 1] ==> [8, 18, 1] If a resulting number is greater than 9, replace it with the sum of its own digits (which is the same as subtracting 9 from it):[8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1] or: [8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1] Sum all of the final digits:[8, 9, 1] ==> 8 + 9 + 1 = 18 Finally, take that sum and divide it by 10.
Read More
Find the unique number using Java
January 3, 2021
The challenge There is an array with some numbers. All numbers are equal except for one. Try to find it! Solution.findUniq(new double[]{ 1, 1, 1, 2, 1, 1 }); // => 2 Solution.findUniq(new double[]{ 0, 0, 0.55, 0, 0 }); // => 0.55 It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. The solution in Java code Option 1:
Read More
Find The Parity Outlier in Java
January 2, 2021
The challenge You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this “outlier” N. Examples [2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number) [160, 3, 1719, 19, 11, 13, -21] Should return: 160 (the only even number) The solution in Java Option 1:
Read More
Find the missing letter using Java
January 1, 2021
The challenge Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2. The array will always contain letters in only one case. Example: [‘a’,‘b’,‘c’,’d’,‘f’] -> ‘e’ [‘O’,‘Q’,‘R’,‘S’] -> ‘P’ ["a","b","c","d","f"] -> "e" ["O","Q","R","S"] -> "P" (Use the English alphabet with 26 letters!
Read More
Determine the order of braces is valid using Java
December 31, 2020
The challenge Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it’s invalid. All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}. What is considered Valid? A string of braces is considered valid if all braces are matched with the correct brace.
Read More
[Solved] PKIX path building failed: unable to find valid certification path to requested target
December 30, 2020
The problem It may happen to you that when you try and pull some Java dependencies, you will get the annoying PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target error. It may look something like this: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.4.0 from/to tpvr-ibm (https://nexus-***.***.***.***:8081/nexus/content/repositories/tpvr-ibm): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target The solution (recommended) Go to URL in your browser: firefox – click on HTTPS certificate chain (the lock icon right next to URL address).
Read More
How to Find the odd int in Java
December 29, 2020
The challenge Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times. The solution in Java code Option 1 (using streams): import static java.util.Arrays.stream; public class FindOdd { public static int findIt(int[] arr) { return stream(arr).reduce(0, (x, y) -> x ^ y); } } Option 2 (using xor): public class FindOdd { public static int findIt(int[] A) { int odd = 0; for (int i : A) { odd ^= i; } return odd; } } Option 3 (using a TreeSet):
Read More
Count the number of Duplicates in Java
December 28, 2020
The challenge Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example “abcde” -> 0 # no characters repeats more than once “aabbcde” -> 2 # 'a' and 'b' “aabBcde” -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
Read More
Calculating Simple Max Digit Sum in Java
December 27, 2020
The challenge In this challenge, you will be given an integer n and your task will be to return the largest integer that is <= n and has the highest digit sum. For example: solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum. solve(10) = 9 solve(48) = 48. Note that 39 is also an option, but 48 is larger.
Read More
The String Combat Challenge in Java
December 26, 2020
The challenge After a long conflict, the rulers of Nek and Glo have decided that a final duel should decide the fate of their countries. Each ruler will select their best knights and send them into battle, one after another. The last standing team will win the crown. But the knights don’t want to die for nothing, so they ask you, the wise technomagican, to derive which team will win. Can you help them?
Read More
Solving Single Word Pig Latin in Java
December 25, 2020
The challenge Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this challenge is to write a function that encodes a single word string to pig latin. The rules themselves are rather easy: The word starts with a vowel(a,e,i,o,u) -> return the original string plus “way”. The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus “ay”.
Read More
Count the Days in Java
December 24, 2020
The challenge Little Annie is very excited for upcoming events. She want’s to know how many days she have to wait for a specific event. Your job is to help her out. Task: Write a function which returns the number of days from today till the given date. The function will take a Date object as parameter. You have to round the amount of days. If the event is in the past, return “The day is in the past!
Read More
Java HashMap Create or Increment Value
December 23, 2020
If you are using a HashMap to keep a running total of a series of elements, then you often need to increment a HashMap item, but if it doesn’t exist in the map yet, then you need to rather create it. There are a number of ways to do this, let’s explore some of these. Using Merge and Sum in Java 8 My absolute favourite is to use Java 8’s ability to do the below:
Read More
Get the Strongest even number in an interval in Java
December 22, 2020
The challenge A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n. For example, if n = 12, then 12 / 2 = 6 6 / 2 = 3 So we divided successively 2 times and we reached 3, so the strongness of 12 is 2. If n = 16 then
Read More
What time is it? in Java
December 21, 2020
The challenge How many times have we been asked this simple question in our daily lives by family, friends and strangers alike? In this challenge you take a look at your watch and answer this question in proper English. Sometimes you have your watch in 24h format and others in 12h. The AM/PM part of the time is always disregarded as the asker knows whether it’s morning or afternoon. Requirements: Mind the punctuation for the full hours; o’clock is written as one word.
Read More
Building a String Pyramid in Java
December 20, 2020
The challenge You have to build a pyramid. This pyramid should be built from characters from a given string. You have to create the code for these four methods: public static String watchPyramidFromTheSide(String characters) public static String watchPyramidFromAbove(String characters) public static int countVisibleCharactersOfThePyramid(String characters) public static int countAllCharactersOfThePyramid(String characters) The first method (“FromTheSide”) shows the pyramid as you would see from the side. The second method (“FromAbove”) shows the pyramid as you would see from above.
Read More
Cartesian coordinates from degree angle in Java
December 19, 2020
The challenge Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rounded to 10 places). For example: coordinates(90,1) => (0.0, 1.0) coordinates(45, 1) => (0.7071067812, 0.7071067812) The solution in Java code Option 1: import java.awt.geom.Point2D; class CoordinatesInspector { Point2D.Double coordinates(Double degrees, Double radius) { return new Point2D.Double( Math.round(radius * Math.cos(Math.toRadians(degrees)) * 10e9) / 10e9, Math.round(radius * Math.sin(Math.toRadians(degrees)) * 10e9) / 10e9); } } Option 2:
Read More
Sort array by sorting its smallest sub-array in Java
December 18, 2020
The challenge Given an array of integers, arr, find out 2 indices m, n(0<=m<=arr.length-1, 0<=n<=arr.length-1, m<=n), so that as long as all elements in the subarray(from index m to n, indices m and n inclusive) are sorted properly, with this sorted subarray relacing original subarray, the whole array is sorted (no matter ascendingly or descendingly). The subarray should include the least number of elements, means (n-m) must be of the smallest value, and n should also be the smallest one.
Read More
Excessively Abundant Numbers in Java
December 17, 2020
The challenge An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12). Derive function abundantNumber(num)/abundant_number(num) which returns true/True/.true. if num is abundant, false/False/.false. if not. The solution in Java code Option 1 (using IntStream):
Read More
Unique Substring From Joined Strings in Java
December 16, 2020
The challenge Write a function that takes two strings, A and B, and returns the length of the longest possible substring that can be formed from the concatenation of either A + B or B + A containing only characters that do not appear in both A and B. Example: Given the strings “piquancy” and “refocusing”: A = “piquancy” B = “refocusing” A + B = “piquancyrefocusing” B + A = “refocusingpiquancy”
Read More
Converting from Base 10 to 16 (Decimal to Hex) in Java
December 15, 2020
The challenge Convert an integer which is base 10, to a hexadecimal base 16 string. Java provides various built-in options such as Integer.toString(a, 16), or String.format("0x%X", a), or Integer.toHexString(a) The solution in Java code Option 1: public class Hexadecimal{ public static String convertToHex(int a){ return "0x"+Integer.toHexString(a).toUpperCase(); } } Option 2: public class Hexadecimal{ private static final String hexDigits = "0123456789ABCDEF"; public static String convertToHex(int a) { String hexadecimal = ""; while (a > 0) { int digit = a % 16; hexadecimal = hexDigits.
Read More
How to Format Numbers by Prepending 0 to single-digit numbers in Javascript
December 14, 2020
If you have a single-digit number, and you need to format it to always have at-least two digits, then you can use the below function to solve your problem: function toAtleastTwoPlaces(n){ return n > 9 ? "" + n: "0" + n; } When testing the above method, you could do the following: toAtleastTwoPlaces(9); //Returns "09" toAtleastTwoPlaces(10); //Returns "10" toAtleastTwoPlaces(999); //Returns "999" This is especially useful where you need to format dates:
Read More
String polynomial converter in Java
December 13, 2020
The challenge Your task is to programe: String convertToString(int[] pol) {....} The method returns given by a parameter, (integer array) which represents a polynomial, the representation of the polynomial in String format. NOTE: array{a, b, c, d, e,...., z} 0 1 2 3 4 .... n The numbers indicate the grade of the polynomial, where n is a positive integer always. Some examples: array{0,1,-2,0,5} -> convertToString(array) -> "5x^4-2x^2+x" array{1,1,-2,0,0} -> convertToString(array) -> "-2x^2+x+1" array{} -> convertToString(array) -> "" array{0,0,7,0,0} -> convertToString(array) -> "7x^2" array{1,0,0,0,0} -> convertToString(array) -> "1" array{0,1,-1,0,5,0,0,1} -> convertToString(array) -> "x^7+5x^4-x^2+x" The solution in Java code Option 1:
Read More
How to Remove all Exclamation Marks from a String in Java
December 12, 2020
The challenge Write function RemoveExclamationMarks which removes all exclamation marks from a given string. The solution in Java code Option 1: class Solution { static String removeExclamationMarks(String s) { return s.replaceAll("!", ""); } } Option 2: class Solution { static String removeExclamationMarks(String s) { return s.replace("!", ""); } } Test cases to validate our solution in Java import org.junit.Test; import java.util.Random; import java.util.stream.*; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void testSimpleString1() { assertEquals("Hello World", Solution.
Read More
How to Convert a Number to a String in Java
December 11, 2020
The challenge We need a function that can transform a number into a string. What ways of achieving this do you know? Examples: Solution.numberToString(123); // returns "123"; Solution.numberToString(999); // returns "999"; The solution in Java code The easiest way to do this is to use the String.valueOf method to take an integer and return a string: class Solution { public static String numberToString(int num) { return String.valueOf(num); } } This can also be done the other way around, using the Integer.
Read More
How to Remove Spaces in a String in Java
December 10, 2020
The challenge Simple, remove the spaces from the string, then return the resultant string. The solution in Java code class Solution { static String noSpace(final String x) { return x.replace(" ", ""); } } An alternative: class Solution { static String noSpace(final String x) { return x.replaceAll("\\s+",""); } } Test cases to validate our Java solution import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void testSomething() { assertEquals("8j8mBliB8gimjB8B8jlB", Solution.
Read More
How many stairs will Suzuki climb in 20 years? in Java
December 9, 2020
The challenge Suzuki is a monk who climbs a large staircase to the monastery as part of a ritual. Some days he climbs more stairs than others depending on the number of students he must train in the morning. He is curious how many stairs might be climbed over the next 20 years and has spent a year marking down his daily progress. The sum of all the stairs logged in a year will be used for estimating the number he might climb in 20.
Read More
Determine if N is divisible by X and Y in Java
December 8, 2020
The challenge Create a function that checks if a number n is divisible by two numbers x AND y. All inputs are positive, non-zero digits. Examples 1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3 2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6 3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3 4) n = 12, x = 7, y = 5 => false because 12 is neither divisible by 7 nor 5 The solution in Java code Option 1:
Read More
How to Sum a Mixed Array in Java
December 7, 2020
The challenge Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. Return your answer as a number. The solution in Java code Option 1 (using stream): import java.util.List; public class MixedSum { public int sum(List<?> mixed) { return mixed.stream().mapToInt(o -> Integer.parseInt(o.toString())).sum(); } } Option 2 (the harder way): import java.util.List; public class MixedSum { public int sum(List<?> mixed) { int sum = 0; for (Object element : mixed) { if (element instanceof Integer) { sum += (Integer) element; } else if (element instanceof String) { sum += Integer.
Read More
Calculate the Volume of a Cuboid in Java
December 6, 2020
A Cuboid is a geometric object that is more or less cubic in shape. It is a solid which has six rectangular faces at right angles to each other. The formula to calculate a cuboid is pretty simple, just multiple the length by the width by the height to get the total volume. We want to calculate volume of cuboid. Additionally, the volume of cuboid test case below validates the Java code solution.
Read More
Find the first non-consecutive number in Java
December 5, 2020
The challenge Your task is to find the first element of an array that is not consecutive. By not consecutive we mean not exactly 1 larger than the previous element of the array. E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that’s the first non-consecutive number. If the whole array is consecutive then return null.
Read More
Alternating String Casing in Java
December 4, 2020
The challenge altERnaTIng cAsE <=> ALTerNAtiNG CaSe Define String.prototype.toAlternatingCase (or a similar function/method such as to_alternating_case/toAlternatingCase/ToAlternatingCase in your selected language; see the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example: StringUtils.toAlternativeString("hello world") == "HELLO WORLD" StringUtils.toAlternativeString("HELLO WORLD") == "hello world" StringUtils.toAlternativeString("hello WORLD") == "HELLO world" StringUtils.toAlternativeString("HeLLo WoRLD") == "hEllO wOrld" StringUtils.toAlternativeString("12345") == "12345" // Non-alphabetical characters are unaffected StringUtils.toAlternativeString("1a2b3c4d5e") == "1A2B3C4D5E" StringUtils.
Read More
Solving the Pythagorean Triple in Java
December 3, 2020
The challenge Given an array of 3 integers a, b and c, determine if they form a pythagorean triple. A pythagorean triple is formed when: c2 = a2 + b2 where c is the largest value of a, b, c. For example: a = 3, b = 4, c = 5 forms a pythagorean triple, because 52 = 32 + 42 Return Values 1 if a, b and c form a pythagorean triple `` if a, b and c do not form a pythagorean triple For Python: return True or False The solution in Java code Option 1:
Read More
How to Correct the Mistakes of the Character Recognition Software in Java
December 2, 2020
The challenge Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer. When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes. Your task is correct the errors in the digitised text. You only have to handle the following mistakes: S is misinterpreted as 5 O is misinterpreted as `` I is misinterpreted as 1 The test cases contain numbers only by mistake.
Read More
Solving “Duck Duck Goose” in Java
December 1, 2020
The challenge The objective of Duck, duck, goose is to walk in a circle, tapping on each player’s head until one is chosen. Task: Given an array of Player objects (an array of associative arrays in PHP) and an index (1-based), return the name of the chosen Player(name is a property of Player objects, e.g Player.name) Example: duck_duck_goose([a, b, c, d], 1) should return a.name duck_duck_goose([a, b, c, d], 5) should return a.
Read More
Calculate averages from an int array in Java
November 30, 2020
The challenge Write function avg which calculates average of numbers in given list. The solution in Java code Option 1 (working through the problem): public class Solution { public static double find_average(int[] array){ double sum = 0; for(int i=0; i<array.length; i++) { sum+=array[i]; } return sum/array.length; } } Option 2 (using streams): import java.util.Arrays; public class Solution { public static double find_average(int[] array){ return Arrays.stream(array).average().orElse(0); } } Option 3 (using an IntStream):
Read More
How to Rotate a String in Java
November 29, 2020
Rotating a String in Java is a common interview question, and albeit it quite a simple one, it tests many fundamental concepts. Did I mention that it can also be done fairly quickly too! Rotating a String in Java public class Rotater { public static void main(String...args) { Rotater r = new Rotater(); System.out.println(r.rotateLeft("test", 1)); System.out.println(r.rotateRight("test", 1)); } private String rotateLeft(String value, int n) { return value.substring(n) + value.substring(0, n); } private String rotateRight(String value, int n) { return rotateLeft(value, value.
Read More
Calculate the Sum without highest and lowest number in Java
November 28, 2020
The challenge Sum all the numbers of the array except the highest and the lowest element (the value, not the index!). (The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!) Example: { 6, 2, 1, 8, 10 } => 16 { 1, 1, 11, 2, 3 } => 6 If array is empty, null or None, or if only 1 Element exists, return 0.
Read More
How to Convert a String to an Array in Java
November 27, 2020
Java makes it easy to convert a string to an array by providing the built-in .split() method on the String object. The challenge Write a function to split a string and convert it into an array of words. For example: "Robin Singh" ==> ["Robin", "Singh"] "I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"] The solution in Java code This is a really simple one, you just split the string with the space character:
Read More
How to Loop and Combine Three Strings in Java
November 26, 2020
The challenge Create a function that will return a string that combines all of the letters of the three inputed strings in groups. Taking the first letter of all of the inputs and grouping them next to each other. Do this for every letter, see example below! E.g. Input: “aa”, “bb” , “cc” => Output: “abcabc” Note: You can expect all of the inputs to be the same length. The solution in Java code Option 1:
Read More
How to Localize The Barycenter of a Triangle in Java
November 25, 2020
The challenge The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or centroid. The function bar_triang() or barTriang or bar-triang, receives the coordinates of the three vertices A, B and C as three different arguments and outputs the coordinates of the barycenter O in an array [xO, yO]
Read More
How to Calculate a Valid Square in Java
November 24, 2020
The challenge Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. The coordinate of a point p<sub>i</sub> is represented as [x<sub>i</sub>, y<sub>i</sub>]. The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). Example 1: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: true Example 2:
Read More
How to Calculate Age Range Compatibility as an Equation in Java
November 23, 2020
The challenge Everybody knows the classic “half your age plus seven” dating rule that a lot of people follow (including myself). It’s the ‘recommended’ age range in which to date someone. minimum age <= your age <= maximum age Given an integer (1 <= n <= 100) representing a person’s age, return their minimum and maximum age range. This equation doesn’t work when the age <= 14, so use this equation instead:
Read More
How to Find the Longest Mountain in Array in Java
November 22, 2020
The challenge Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i&nbsp;< B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array A of integers, return the length of the longest mountain.
Read More
How to tell what the CHMOD value of a file/directory is
November 21, 2020
chmod alters the permissions for a file or directory, you could allow full read/write access to a file or directory by running the following command: chmod 777 myfile.ext You could do the same on a directory recursively: chmod -R 777 mydirectory But if we look at the directory listing of this path now, we can’t tell what integer value this affected: $ ls -lash 0 -rwxrwxrwx 1 ao staff 0B 18 Nov 13:29 myfile.
Read More
How to Solve the “Decode a String” Challenge in Java
November 20, 2020
The challenge Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k.
Read More
How to cleanup a /var/log/journal in Linux
November 19, 2020
You may find your /var/log/journal directory taking up a lot of disk-space. How do you go about removing, or deleting all these files under var log journal without the system complaining and falling over? How to tell how much space is being taken? You can ask the journalctl command directly, using the --disk-usage argument: journalctl --disk-usage It will report something like this: Journals take up 3.9G on disk. Fix: Option 1 (not ideal): Go and adjust its config under /etc/systemd/journald.
Read More
How to Find the Maximum Difference Between Node and Ancestor in Java
November 18, 2020
The challenge Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B. Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Read More
How to Find the Integral using Java
November 17, 2020
The challenge Create a function that finds the integral of the expression passed. In order to find the integral all you need to do is add one to the exponent (the second argument), and divide the coefficient (the first argument) by that new number. For example for 3x^2, the integral would be 1x^3: we added 1 to the exponent, and divided the coefficient by that new number). Notes: The output should be a string.
Read More
How to Build Strings from a Size in Java
November 16, 2020
The challenge Write a function stringy that takes a size and returns a string of alternating '1s' and '0s'. The string should start with a 1. A string with size 6 should return :'101010'. With size 4 should return : '1010'. With size 12 should return : '101010101010'. The size will always be positive and will only use whole numbers. The solution in Java code public class Solution { public static String stringy(int size) { int last = 1; StringBuilder sb = new StringBuilder(); for (int i=0; i<size; i++) { sb.
Read More
Best Time to Buy and Sell Stock in Java
November 15, 2020
The challenge Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Read More
How to Solve the “To square(root) or not to square(root)” Challenge in Java
November 14, 2020
The challenge Write a method, that will get an integer array as parameter and will process every number from this array. Return a new array with processing every number of the input-array like this: If the number has an integer square root, take this, otherwise square the number. [4,3,9,7,2,1] -> [2,9,3,49,4,1] The input array will always contain only positive numbers and will never be empty or null. Test cases import org.
Read More
Solving the Rule of Divisibility by 13 in Java
November 13, 2020
The challenge "A divisibility rule is a shorthand way of determining whether a given integer is divisible by a fixed divisor without performing the division, usually by examining its digits." wikipedia.com When you divide the successive powers of 10 by 13 you get the following remainders of the integer divisions: 1, 10, 9, 12, 3, 4 because: (For “mod” you can see: https://en.wikipedia.org/wiki/Modulo_operation ) Then the whole pattern repeats. Hence the following method:
Read More
How to Calculate Buddy Strings in Java
November 12, 2020
The challenge Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices `` and 2 in "abcd" results in "cbad". Example 1:
Read More
How to Flip a Binary Matrix in Java
November 11, 2020
The challenge Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each &nbsp;is replaced by&nbsp;`1`, and each&nbsp;`1`&nbsp;is replaced by&nbsp;. For example, inverting [0, 1, 1] results in [1, 0, 0].
Read More
How to Tilt a Binary Tree in Java
November 10, 2020
The challenge Given the root of a binary tree, return the sum of every tree node’s tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as ``. The rule is similar if there the node does not have a right child.
Read More
How to solve the House Robber Challenge in Java
November 9, 2020
The challenge You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Read More
How to Solve the Bag of Tokens Challenge in Java
November 8, 2020
The challenge You have an initial power of P, an initial score of ``, and a bag of tokens where tokens[i] is the value of the i<sup>th</sup> token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: If your current power is at least tokens[i], you may play the i<sup>th</sup> token face up, losing tokens[i] power and gaining 1 score. If your current score is at least 1, you may play the i<sup>th</sup> token face down, gaining tokens[i] power and losing 1 score.
Read More
How to Find the Smallest Divisor Given a Threshold in Java
November 7, 2020
The challenge Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
Read More
How to Sort and Star a String Array in Java
November 6, 2020
The challenge You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value. The returned value must be a string, and have "***" between each of its letters. You should not remove or add elements from/to the array. The solution in Java code At first we could approach the problem by using the built-in Arrays.
Read More
How to Count Consecutive Characters in Java
November 5, 2020
The challenge Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string. Example 1: Input: s = "meetme" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only Example 2: Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Read More
How to Abbreviate a Two Word Name in Java
November 4, 2020
The challenge Write a function to convert a name into initials. This challenge strictly takes two words with one space in between them. The output should be two capital letters with a dot separating them. It should look like this: Sam Harris => S.H Patrick Feeney => P.F The solution in Java This is a really easy one, basically what we will do is the following: Convert our name toUpperCase so that we can just pull out the characters we want.
Read More
How to Sort a Linked List using Insertion Sort in Java
November 3, 2020
The challenge Sort a linked list using insertion sort. A graphical example of insertion sort. The partially sorted list (black) initially contains only the first element in the list. With each iteration, one element (red) is removed from the input data and inserted in-place into the sorted list Algorithm of Insertion Sort: Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
Read More
How to Remove First and Last Character in a String in Java
November 2, 2020
The challenge The goal is to create a function that removes the first and last characters of a string. You don’t have to worry with strings with less than two characters. The solution in Java code public class RemoveChars { public static String remove(String str) { return str.substring(1, str.length()-1); } } Test cases to validate our Java solution import org.junit.Test; import static org.junit.Assert.assertEquals; public class RemoveCharsTest { @Test public void testRemoval() { assertEquals("loquen", RemoveChars.
Read More
How to Distribute Halloween Candies by Rating Value in Java
November 1, 2020
The challenge There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Read More
How to Distribute Halloween Candies in Java
October 31, 2020
The challenge You have n candies, the i<sup>th</sup> candy is of type candies[i]. You want to distribute the candies equally between a sister and a brother so that each of them gets n / 2 candies (n is even). The sister loves to collect different types of candies, so you want to give her the maximum number of different types of candies. Return the maximum number of different types of candies you can give to the sister.
Read More
How to Solve the Maximize Distance to Closest Person Challenge in Java
October 30, 2020
The challenge You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the i<sup>th</sup> seat, and seats[i] = 0 represents that the i<sup>th</sup> seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person.
Read More
How to Get Character from ASCII Value in Java
October 29, 2020
The challenge Write a function which takes a number and returns the corresponding ASCII char for that value. Example: Ascii.getChar(65) // => 'A' For ASCII table, you can refer to http://www.asciitable.com/ The solution in Java public class Ascii { public static char getChar(int c) { return (char) c; } } Test cases to validate our solution import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testChar() { assertEquals('7', Ascii.
Read More
Finding a Needle in a Haystack in Java
October 28, 2020
The challenge Can you find the needle in the haystack? Write a function findNeedle() that takes an array full of junk but containing one "needle" After your function finds the needle it should return a message (as a string) that says: "found the needle at position " plus the index it found the needle, so: findNeedle(new Object[] {"hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"}) should return "found the needle at position 5"
Read More
How to Solve the Champagne Tower in Java
October 27, 2020
The challenge We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup (250ml) of champagne. Then, some champagne is poured in the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.
Read More
How to Solve the 132 Pattern in Java
October 26, 2020
The challenge Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise, return false. **Follow up: **The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution? Example 1: Input: nums = [1,2,3,4] Output: false Explanation: There is no 132 pattern in the sequence.
Read More
How to Replace all Vowels in a String in Java
October 25, 2020
The challenge Replace all vowel to exclamation mark in the sentence. aeiouAEIOU is vowel. Examples replace("Hi!") === "H!!" replace("!Hi! Hi!") === "!H!! H!!" replace("aeiou") === "!!!!!" replace("ABCDE") === "!BCD!" The solution in Java code We could use a StringBuilder and a switch case as a first attempt: public class Solution { public static String replace(final String s) { StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { switch(Character.toLowerCase(s.charAt(i))) { case 'a': case 'e': case 'i': case 'o': case 'u': sb.
Read More
How to Get the N-th Power in Java
October 24, 2020
The challenge You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don’t forget that the first element has the index 0. Let’s look at a few examples: array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9; array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.
Read More
How to Count the Minimum Depth of a Binary Tree in Java
October 23, 2020
The challenge Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5 Constraints: The number of nodes in the tree is in the range [0, 10<sup>5</sup>].
Read More
How to Solve the House Robber II Challenge in Java
October 22, 2020
The challenge You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
Read More
How to Clone a Graph in Java
October 21, 2020
The challenge Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Effectively a graph copy. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on.
Read More
How to Return Random Values in Java
October 20, 2020
The challenge Ghost objects are instantiated without any arguments. Ghost objects are given a random color attribute of white" or “yellow” or “purple” or “red” when instantiated Ghost ghost = new Ghost(); ghost.getColor(); //=> "white" or "yellow" or "purple" or "red" All this challenge is really asking us to do is to create a class method that can return random colour strings when called. The solution in Java We make use of the java.
Read More
How to Compare Version Numbers in Java
October 19, 2020
The challenge Compare two version numbers version1 and version2. If <em>version1</em>&nbsp;>&nbsp;<em>version2</em> return 1; if <em>version1</em>&nbsp;<&nbsp;<em>version2</em> return -1;otherwise return ``. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.
Read More
How to Return the First N Elements in Java
October 18, 2020
The challenge Create a method take that accepts a list/array and a number n, and returns a list/array array of the first n elements from the list/array. If you need help, here’s a reference: https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int) Test cases import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; import java.util.*; public class SolutionTest { @Test public void basicTests() { assertArrayEquals("should return the first 3 items", new int[]{0, 1, 2}, ZywOo.take(new int[]{0, 1, 2, 3, 5, 8, 13}, 3)); assertArrayEquals("should return 0 items", new int[0], ZywOo.
Read More
How to Search a 2d Matrix/Array in Java
October 17, 2020
The challenge Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 3 Output: true Example 2: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 13 Output: false Example 3:
Read More
Calculate the Surface Area and Volume of a Box with Java
October 16, 2020
The challenge Write a function that returns the total surface area and volume of a box as an array: [area, volume] The solution in Java We know that the formula to calculate the area of a box is as follows: 2(h × W) + 2(h × L) + 2(W × L) We also know that the formula to calculate the volume of a box is as follows: W x h x H
Read More
Find Numbers which are Divisible by given Number in Java
October 15, 2020
The challenge Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of numbers and the second is the divisor. Example divisibleBy([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6] The solution in Java Option 1 (using streams): import java.util.stream.*; import java.util.Arrays; public class EvenNumbers { public static int[] divisibleBy(int[] numbers, int divider) { return Arrays.
Read More
How to Split a Subdirectory to a New Git Repository and Keep the History
October 14, 2020
There comes a time when you need to split out a subdirectory into it’s own git repo. This is a very simple task if you don’t care about persisting the git history for any changes that were made in that subdirectory. However, if you would like to keep all the history of the subdirectory only, and not of the overall entire repository itself, then you can perform the following bunch of steps:
Read More
Get the Maximum XOR of Two Numbers in an Array in Java
October 13, 2020
The challenge Given a non-empty array of numbers, a, a1, a2, … , an-1, where 0 ≤ ai < 231. Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. Could you do this in O(n) runtime? Example: Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28. The solution in Java We can very quickly resolve this challenge by performing a double loop and comparing our resultant:
Read More
How to Get the Opposite of a Number in Java
October 12, 2020
The challenge Given a number, find its opposite. Examples: 1: -1 14: -14 -34: 34 The solution in Java We return the number itself multiplied by a negative 1. public class Solution { public static int opposite(int number) { return number *= -1; } } This can be simplified further as: public class Solution { public static int opposite(int number) { return -number; } } There is also a built in method to help with this if you prefer, called Math.
Read More
How to Find the Area or Perimeter of a 4-sided Polygon using Java
October 11, 2020
The challenge You are given the length and width of a 4-sided polygon. The polygon can either be a rectangle or a square. If it is a square, return its area. If it is a rectangle, return its perimeter. area_or_perimeter(6, 10) --> 32 area_or_perimeter(4, 4) --> 16 Note: for the purposes of this challenge you will assume that it is a square if its length and width are equal, otherwise, it is a rectangle. The solution in Java Given that we know that:
Read More
How to Parse Int from Char in Java
October 10, 2020
The challenge We take in a String where the first place contains a number, write a function that takes in this String and returns an int containing it. For correct answer program should return int from 0 to 9. Assume test input string always valid and may look like “1 year old” or “5 years old”, etc.. The first char is number only. The solution in Java We take in a String, and get the first character, which is done by using charAt(0).
Read More
How to Search a Binary Tree in Java
October 9, 2020
The challenge Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Note:
Read More
How to Rotate a Singly Linked List in Java
October 8, 2020
The challenge Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL ``` ## The solution in Java code The definition for our singly-linked lists ``` public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.
Read More
How to Insert into a Binary Search Tree using Java
October 7, 2020
The challenge You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Read More
Find the Complement of Base 10 Integer in Java
October 6, 2020
The challenge Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changing every 1 to a &nbsp;and&nbsp; to a 1. For example, the complement of "101" in binary is "010" in binary.
Read More
Solve the Number of Recent Calls Challenge in Java
October 5, 2020
The challenge You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
Read More
How to Calculate the Summation of a Number in Java
October 4, 2020
The challenge Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. For example: summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 The solution in Java public class Solution { public static int summation(int n) { int runningTotal = 0; for (int i=1; i<=n; i++) runningTotal += i; return runningTotal; } } A simpler alternative is to do the following:
Read More
How to Calculate all Unique Combinations of a Target using Backtracking in Java
October 3, 2020
The challenge Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. Example 1:
Read More
Who is going to pay for the wall? in Python
October 2, 2020
The challenge Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names.
Read More
Calculate the Total Amount of Points using Java
October 1, 2020
The challenge Our football team finished the championship. The result of each match look like “x:y”. Results of all matches are recorded in the collection. For example: ["3:1", "2:2", "0:1", ...] Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match: if x>y – 3 points if x<y – 0 point if x=y – 1 point Notes:
Read More
Calculate the biggest of 3 numbers using Java
September 30, 2020
The challenge Task Given three integers a ,b ,c, return the largest number obtained after inserting the following operators and brackets: +, *, () In other words , try every combination of a,b,c with [*+()] , and return the Maximum Obtained Consider an Example : With the numbers are 1, 2 and 3 , here are some ways of placing signs and brackets: 1 * (2 + 3) = 5 1 * 2 * 3 = 6 1 + 2 * 3 = 7 (1 + 2) * 3 = 9 So the maximum value that you can obtain is 9.
Read More
Find the missing element between two arrays in Python
September 29, 2020
The challenge Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element. Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution. find_missing([1, 2, 2, 3], [1, 2, 3]) => 2 find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8 The first array will always have at least one element.
Read More
How to Count an Array of Boolean Values in Java
September 28, 2020
The challenge Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present). For example, [true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, true] The correct answer would be 17. Hint: Don’t forget to check for bad values like null/undefined
Read More
How to Solve the Car Pooling Challenge in Java
September 27, 2020
The challenge You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.) Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.
Read More
How to Repeat a String in Java
September 26, 2020
The challenge Write a function called repeat_str which repeats the given string src exactly count times. repeatStr(6, "I") // "IIIIII" repeatStr(5, "Hello") // "HelloHelloHelloHelloHello" The solution in Java Java comes with a built-in on the String class. Called repeat, which allows you to very easily repeat that string n number of times. "Hello".repeat(2); // "HelloHello" Using String::repeat() Therefore, we could solve our above problem as follows: class Solution { static String repeatStr(int repeat, String string) { return string.
Read More
How to Find the Smallest Integer in the Array in Java
September 25, 2020
The challenge Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this challenge, that the supplied array will not be empty. The solution in Java Option 1 (using Arrays.sort): import java.util.Arrays; public class SmallestIntegerFinder { public static int findSmallestInt(int[] args) { Arrays.
Read More
How to Count Odd Numbers Below N using Java
September 24, 2020
The challenge Given a number n, return the number of positive odd numbers below n, EASY! oddCount(7) //=> 3, i.e [1, 3, 5] oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13] Expect large Inputs! Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void fixedTests() { assertEquals(7, OddNumbers.oddCount(15)); assertEquals(7511, OddNumbers.oddCount(15023)); } } The solution in Java At first we would approach this in a programming type of way:
Read More
How to get the Length of the Last Word in a String using Java
September 23, 2020
The challenge Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word is defined as a maximal substring consisting of non-space characters only. Example: Input: "Hello World" Output: 5 The solution in Java class Solution { public int lengthOfLastWord(String s) { // catch edge case of blank input if (s.
Read More
How to Convert a Number to Reversed Array of Digits in Java
September 22, 2020
The challenge Given a random non-negative number, you have to return the digits of this number within an array in reverse order. Test cases import org.junit.Test; import static org.junit.Assert.assertArrayEquals; public class DigitizeExampleTests { @Test public void tests() { assertArrayEquals(new int[] {1, 3, 2, 5, 3}, ConvertAndReverse.digitize(35231)); } } Solution in Java Option 1 (using Streams and StringBuilder): import java.util.*; public class ConvertAndReverse { public static int[] digitize(long n) { StringBuilder sb = new StringBuilder(Long.
Read More
How to Solve Unique Paths III in Java
September 21, 2020
The challenge On a 2-dimensional grid, there are 4 types of squares: 1 represents the starting square. There is exactly one starting square. 2 represents the ending square. There is exactly one ending square. `` represents empty squares we can walk over. -1 represents obstacles that we cannot walk over. Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Read More
How to Find the Mean/Average of a List of Numbers in Java
September 20, 2020
The challenge Find the mean (average) of a list of numbers in an array. To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list. For an example list of 1, 3, 5, 7 1. Add all of the numbers 1+3+5+7 = 16 2. Divide by the number of values in the list. In this example there are 4 numbers in the list.
Read More
How to Calculate BMI in Java
September 19, 2020
The challenge BMI stands for Body Mass Index and is a value derived from the mass and height of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed in units of kg/m², resulting from mass in kilograms and height in metres. Wikipedia Write function BMI that calculates body mass index (bmi = weight / height ^ 2).
Read More
How to Solve the Robot Bounded In Circle Challenge in Java
September 18, 2020
The challenge On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Read More
How to Convert a String to a Number in Java
September 17, 2020
The challenge We need a function that can transform a string into a number. What ways of achieving this do you know? Note: Don’t worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number. Examples stringToNumber("1234") == 1234 stringToNumber("605" ) == 605 stringToNumber("1405") == 1405 stringToNumber("-7" ) == -7 Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; public class StringToNumberTest { @Test public void test1(){ assertEquals("stringToNumber(1234)", 1234 , StringToNumber.
Read More
How to Convert an Integer to Binary using Java
September 16, 2020
The challenge Given a non-negative integer n, write a function toBinary/ToBinary which returns that number in a binary format. to_binary(1) /* should return 1 */ to_binary(5) /* should return 101 */ to_binary(11) /* should return 1011 */ Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class ConvertTest { @Test public void testToBinary() { assertEquals(1, BinaryConvert.toBinary(1)); assertEquals(10, BinaryConvert.toBinary(2)); assertEquals(11, BinaryConvert.toBinary(3)); assertEquals(101, BinaryConvert.toBinary(5)); } } The solution in Java public class BinaryConvert { public static int toBinary(int n) { // Use the `toBinaryString` method of the Integer class // convert it back to an `int` using the `parseInt` method of the Integer class // return the result return Integer.
Read More
How to create a Logical Operator in Java
September 15, 2020
Exclusive “or” (xor) Logical Operator In some scripting languages like PHP, there exists a logical operator (e.g. &&, ||, and, or, etc.) called the “Exclusive Or”. The exclusive or evaluates two booleans. It then returns true if exactly one of the two expressions are true, false otherwise. For example: // since both are false false xor false == false // exactly one of the two expressions are true true xor false == true // exactly one of the two expressions are true false xor true == true // Both are true.
Read More
How to merge sorted integer arrays (without duplicates) in Java
September 14, 2020
The challenge Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate. Test cases import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.Function; import java.util.stream.IntStream; public class SolutionTest { @Test public void fixedTest() { assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 6 }, Merger.mergeArrays(new int[] { 1, 3, 5 }, new int[] { 2, 4, 6 })); assertArrayEquals(new int[] { 2, 4, 6, 8 }, Merger.
Read More
Find the Force of Gravity Between Two Objects with Java
September 13, 2020
The challenge Your job is to find the gravitational force between two spherical objects (obj1 , obj2). Two arrays are give : arr_val (value array), consists of 3 elements 1st element : mass of obj 1 2nd element : mass of obj 2 3rd element : distance between their centers arr_unit (unit array), consists of 3 elements 1st element : unit for mass of obj 1 2nd element : unit for mass of obj 2 3rd element : unit for distance between their centers Mass units are : kilogram (kg) gram (g) milligram (mg) microgram (μg) pound (lb) Distance units are : meter (m) centimeter (cm) millimeter (mm) micrometer (μm) feet (ft) Additional notes value of G = 6.
Read More
How to zoom text by mouse wheel in IntelliJ Idea
September 12, 2020
It’s a common requirement to be able to zoom in or out while working in the code editor in IntelliJ Idea. This is achieved on Windows with CTRL+Mouse Wheel, or on Mac with CMD+Mouse Wheel. This feature is not enabled by default, but luckily it’s very simple to enable this. How to enable mouse wheel zoom in IntelliJ Open the Settings, or Preferences window. On Windows you can press CTRL+ALT+S, and on Mac you can press CMD+,
Read More
Playing the Bulls and Cows Game in Java
September 11, 2020
The challenge You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”).
Read More
Calculate the Sum of Root To Leaf Binary Numbers in Java
September 10, 2020
The challenge Given a binary tree, each node has value `` or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Read More
Remove an Exclamation Mark from the End of String using Python
September 9, 2020
The challenge Remove a exclamation mark from the end of string. You can assume that the input data is always a string, no need to verify it. Examples remove("Hi!") === "Hi" remove("Hi!!!") === "Hi!!" remove("!Hi") === "!Hi" remove("!Hi!") === "!Hi" remove("Hi! Hi!") === "Hi! Hi" remove("Hi") === "Hi" Test cases test.describe("Basic Tests") tests = [ #[input, [expected]], ["Hi!", "Hi"], ["Hi!!!","Hi!!"], ["!Hi", "!Hi"], ["!Hi!", "!Hi"], ["Hi! Hi!", "Hi! Hi"], ["Hi", "Hi"], ] for inp, exp in tests: test.
Read More
How to “Rock Paper Scissors” in Java
September 8, 2020
The challenge Let’s play Rock Paper Scissors! You have to return which player won! In case of a draw return Draw!. Examples: rps('scissors','paper') // Player 1 won! rps('scissors','rock') // Player 2 won! rps('paper','paper') // Draw! The rules of the game Rock Paper Scissors The rules of the game Rock Paper Scissors is quite simple. Rock beats scissors, scissors beats paper, and paper beats rock. Below is an illustration showing the cyclical routes.
Read More
Compare within Margin using Python
September 7, 2020
The challenge Create a function close_compare that accepts 3 parameters: a, b, and an optional margin. The function should return whether a is lower than, close to, or higher than b. a is “close to” b if margin is higher than or equal to the difference between a and b. When a is lower than b, return -1. When a is higher than b, return 1. When a is close to b, return ``.
Read More
Get the mean of an array in Java
September 6, 2020
The challenge It’s the academic year’s end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script. Return the average of the given array rounded down to its nearest integer. The array will never be empty. Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void simpleTest() { assertEquals(2,School.
Read More
Remove the time challenge in Python
September 5, 2020
The challenge You’re re-designing a blog and the blog’s posts have the following format for showing the date and time a post was made: Weekday Month Day, time e.g., Friday May 2, 7pm You’re running out of screen real estate, and on some pages you want to display a shorter format, Weekday Month Day that omits the time. Write a function, shortenToDate, that takes the Website date/time in its original string format, and returns the shortened format.
Read More
How to Convert Hex to Decimal in Java
September 4, 2020
The challenge Write a function that converts an input string contains a hex value, and return a decimal. Test cases import org.junit.Test; import static org.junit.Assert.*; public class ExampleTests { @Test public void examples() { // assertEquals("expected", "actual"); assertEquals(1, ConvertHexToDec.hexToDec("1")); assertEquals(10, ConvertHexToDec.hexToDec("a")); assertEquals(16, ConvertHexToDec.hexToDec("10")); assertEquals(255, ConvertHexToDec.hexToDec("FF")); assertEquals(-12, ConvertHexToDec.hexToDec("-C")); } } The solution in Java In Java, it is really easy to convert Hex to Decimal. You simply use the Integer class and call the parseInt method, making sure to also provide the base that you want to convert from.
Read More
Character with Longest Consecutive Repetition in Java
September 3, 2020
The challenge For a given string s find the character c (or C) with longest consecutive repetition and return: Object[]{c, l}; where l (or L) is the length of the repetition. If there are two or more characters with the same l return the first in order of appearance. For empty string return: Object[]{"", 0} Test cases import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void exampleTests() { assertArrayEquals(new Object[]{"a", 4}, Solution.
Read More
Check if List contains Item in Python
September 2, 2020
The challenge Create a method that accepts a list and an item, and returns true if the item belongs to the list, otherwise false. Test cases list = [0,1,2,3,5,8,13,2,2,2,11]; Test.assert_equals(include(list, 100), False, "list does not include 100") Test.assert_equals(include(list, 2), True, "list includes 2 multiple times") Test.assert_equals(include(list, 11), True, "list includes 11") Test.assert_equals(include(list, "2"), False, "list includes 2 (integer), not ''2'' (string)") Test.assert_equals(include([], 0), False, "empty list doesn't include anything") Test.assert_equals(include(list, 0), True, "list includes 0") The solution in Python def include(arr,item): return item in arr
Read More
How To Create a User and Grant Permissions in MySQL
September 1, 2020
How to create a user CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword'; How to delete a user DROP USER 'myuser'@'localhost'; How to grant permissions GRANT ALL PRIVILEGES ON * . * TO 'myuser'@'localhost'; How to apply those permissions FLUSH PRIVILEGES; Going a bit deeper Different types of Grants ALL PRIVILEGES : Full access to everything, globally unless restricted to a database CREATE : Create databases and tables DROP : Delete databases and tables
Read More
How to Remove Vowels with Python
August 31, 2020
The challenge Create a function called shortcut to remove all the lowercase vowels in a given string. Examples shortcut("codewars") # --> cdwrs shortcut("goodbye") # --> gdby Don’t worry about uppercase vowels. Test cases import random Test.describe("Easy") for t in [ ["hello","hll"], ["hellooooo","hll"], ["how are you today?","hw r y tdy?"], ["complain","cmpln"], ["never","nvr"] ]: ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp) Test.describe("Not so easy") for t in [ ["a e i o u, borriquito como tu"," , brrqt cm t","Isolated vowels let spaces between them"], ["Explicit is better than implicit", "Explct s bttr thn mplct","Should remove only lowercase vowel"], ["Beautiful is better than Ugly", "Btfl s bttr thn Ugly","Should remove only lowercase vowel"] ]: ans,exp = shortcut(t[0]), t[1] Test.
Read More
How to find all files in a directory with extension
August 30, 2020
I needed to find all files in a directory on Linux that ended with the file extension .php. How to find all files in a directory with extension You can do this as follows: cd <your directory path> find . -type f -name "*.php" How to find other file extensions in a directory Just swap out the .php value for another file extension that you would like to search for instead.
Read More
How to Sort a List in Python
August 29, 2020
In this tutorial, you will learn how to sort a list in Python, by following the below three steps: Options to sort a list in Python What is the difference between “sort” and “sorted” An example of using “sort” An example of using “sorted” How to Sort a List in Reverse Sort a list in Reverse using “sort” Sort a list in Reverse using “sorted” Sort with a Custom Function using Key 1.
Read More
Cryptanalysis Word Patterns in Java
August 28, 2020
The challenge In cryptanalysis, words patterns can be a useful tool in cracking simple ciphers. A word pattern is a description of the patterns of letters occurring in a word, where each letter is given an integer code in order of appearance. So the first letter is given the code 0, and second is then assigned 1 if it is different to the first letter or 0 otherwise, and so on.
Read More
How to divide a number in Python
August 27, 2020
The challenge Your task is to create functionisDivideBy (or is_divide_by) to check if an integer number is divisible by each out of two arguments. A few cases: (-12, 2, -6) -> true (-12, 2, -5) -> false (45, 1, 6) -> false (45, 5, 15) -> true (4, 1, 4) -> true (15, -5, 3) -> true Test cases Test.describe("Basic Tests") Test.it("should pass basic tests") Test.assert_equals(is_divide_by(-12, 2, -6), True) Test.assert_equals(is_divide_by(-12, 2, -5), False) Test.
Read More
How to Read Kubernetes Secrets
August 26, 2020
Kubernetes secrets is a great way to store secret values that only Kubernetes can access in your hosted applications. There are times when you might need to view these secrets in plain-text. This is probably because you want to validate the value or use it manually elsewhere. In this tutorial we will go through how to achieve this and read Kubernetes secrets using kubectl for the command-line. tl;dr kubectl get secret <SECRET_NAME> -o jsonpath="{.
Read More
Backspaces in String Challenge using Java
August 25, 2020
The challenge Assume "#" is like a backspace in string. This means that string "a#bc#d" actually is "bd" Your task is to process a string with "#" symbols. Examples "abc#d##c" ==> "ac" "abc##d######" ==> "" "#######" ==> "" "" ==> "" Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testCleanString() { final BackspacesInString bis = new BackspacesInString(); assertEquals("ac", bis.cleanString("abc#d##c")); assertEquals("", bis.cleanString("abc####d##c#")); } } The solution in Java Option 1:
Read More
How many times to Kaprekar’s constant using Python
August 24, 2020
Introduction 6174 is known as Kaprekar’s constant after the Indian mathematician D. R. Kaprekar. This number is notable for the following rule: Take any four-digit number, using at least two different digits (leading zeros are allowed). Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary. Subtract the smaller number from the bigger number. Go back to step 2 and repeat.
Read More
How to check if a String is a Number in Python
August 23, 2020
The challenge Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not. Valid examples, should return true: isDigit("3") isDigit(" 3 ") isDigit("-3.23") should return false: isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero") Test cases test.assert_equals(isDigit("s2324"), False) test.assert_equals(isDigit("-234.4"), True) The solution in Python Option 1(with try/except): # create a function def isDigit(string): # use a `try/except` block try: # True if can convert to a float float(string) return True except: # otherwise return False return False Option 2(with regex/Regular expression):
Read More
How to Write a Custom Comparator in Python
August 22, 2020
Generally, you want to use the built-in sorted() function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed. How the custom comparator works When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks): return a negative value (< 0) when the left item should be sorted before the right item return a positive value (> 0) when the left item should be sorted after the right item return `` when both the left and the right item have the same weight and should be ordered “equally” without precedence The challenge Write a comparator for a list of phonetic words for the letters of the greek alphabet.
Read More
How to delete an AWS WAF – Web ACL
August 21, 2020
Usually, it’s quite easy to delete an AWS WAF, or Web ACL. But sometimes you may come across the following error when attempting to delete the actual WAF: AWS WAF couldn’t perform the operation because your resource is being used by another resource or it’s associated with another resource. What this means When you get this error, it means that there is something attached to the WAF that is currently using it.
Read More
How to Sort an Integer in Python
August 20, 2020
Let’s say that you have an integer with value of 9271 and you want to sort it either ascending(1279) or descending(9721). How would you do this in Python? How would you sort an integer in either ascending or descending order? Sorting our integer Let’s set our integer to n: n = 9271 Now let’s sort it: sorted([i for i in str(n)]) # This will give us a list in ascending order # ['1', '2', '7', '9'] We can as easily do it the other way:
Read More
How to Upgrade PIP
August 19, 2020
In this tutorial, you will learn how to upgrade PIP. You will also learn how to check the current version of PIP, as well as downgrade to a previous version of PIP if you really need to. TLDR; How to Upgrade PIP The most obvious way, if python is mapped to the version you want pip to be upgraded on: python -m pip install --upgrade pip or if you are running python3 from the python3 command itself:
Read More
How to Copy a File in Python
August 18, 2020
In this tutorial, you will learn how to copy a file using Python from a directory to another directory, or if you’re on Windows, then from a Folder to another Folder. shutil.copyfile is a tool that is often used to copy a file in Python, below is an example of it’s usage, you can read more about it on the Python docs: import shutil # the source file original = '/path/to/the/file.
Read More
Conway’s Game of Life – Unlimited Edition – in Python
August 17, 2020
What is this? Conways’s Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc.. geeksforgeeks.org How the game works Because the Game of Life is built on a grid of nine squares, every cell has eight neighboring cells,as shown in the given figure. A given cell (i, j) in the simulation is accessed on a grid [i][j], where i and j are the row and column indices, respectively.
Read More
Most frequently used words in a text with Python
August 16, 2020
The challenge Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences. Assumptions: A word is a string of letters (A to Z) optionally containing one or more apostrophes (‘) in ASCII. (No need to handle fancy punctuation.) Matches should be case-insensitive, and the words in the result should be lowercased.
Read More
The SongDecoder Dubstep Challenge with Java
August 15, 2020
The challenge Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let’s assume that a song consists of some number of words (that don’t contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words “WUB” before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including “WUB”, in one string and plays the song at the club.
Read More
Break camelCase Challenge in Java
August 14, 2020
The challenge Complete the solution so that the function will break up camel casing, using a space between words. Example solution("camelCasing") == "camel Casing" Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void tests() { assertEquals( "Incorrect", "camel Casing", Solution.camelCase("camelCasing")); assertEquals( "Incorrect", "camel Casing Test", Solution.camelCase("camelCasingTest")); assertEquals( "Incorrect", "camelcasingtest", Solution.camelCase("camelcasingtest")); } } The solution in Java class Solution { public static String camelCase(String input) { String out = ""; for (int i=0; i<input.
Read More
Sort Binary Tree by Levels using Python
August 13, 2020
The challenge You are given a binary tree: class Node: def __init__(self, L, R, n): self.left = L self.right = R self.value = n Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on. Return empty list if root is None. Example 1 – following tree:
Read More
How to Split a String with Python
August 12, 2020
Splitting a string in Python is really easy. You simply take a string and apply the split() method. "Your String".split() See some examples of the Python Split String method: A Python Split String – Example # Your string a_string = "This is our string" # Split into a list a_list = a_string.split() # Print the list print(a_list) Python Split String – Syntax string.split(separator, maxsplit) Parameter Values Parameter Description separator Optional – What to split the string on.
Read More
How to fix the Terraform stuck on “Refreshing state…” problem
August 11, 2020
Terraform is a fantastic tool to help automate your infrastructure as code. Quite a few times however, I have noticed a few strange issues, one of them is when Terraform gets stuck while refreshing the state. This can happen when running terraform plan or in-fact, when running a range of other commands that require the state-file to be refreshed and used. The problem Terraform gets stuck on this message: Refreshing Terraform state in-memory prior to plan…
Read More
The “Split Strings” Challenge using Java
August 10, 2020
The challenge Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (‘_’). Examples: StringSplit.solution("abc") // should return {"ab", "c_"} StringSplit.solution("abcdef") // should return {"ab", "cd", "ef"} Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.util.Arrays; public class SampleTest { @Test public void testEvenString() { String s = "abcdef"; String s1 = "HelloWorld"; assertEquals("Should handle even string","[ab, cd, ef]", Arrays.
Read More
Converting to PigLatin with Python
August 9, 2020
The challenge Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched. Examples pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway ! Test cases Test.assert_equals(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay') Test.assert_equals(pig_it('This is my string'),'hisTay siay ymay tringsay') How to write the code in Python def pig_it(text): words = text.
Read More
Solving the “Double Cola” Challenge using Java
August 8, 2020
The challenge Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a “Double Cola” drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.
Read More
Convert Seconds to Human Readable Time (HH:MM:SS) using Java
August 7, 2020
The challenge Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS) HH = hours, padded to 2 digits, range: 00 – 99 MM = minutes, padded to 2 digits, range: 00 – 59 SS = seconds, padded to 2 digits, range: 00 – 59 The maximum time never exceeds 359999 (99:59:59) Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; public class ExampleTest { @Test public void Tests() { assertEquals("makeReadable(0)", "00:00:00", HumanReadableTime.
Read More
Solving the “Mexican Wave” Challenge using Java
August 6, 2020
The challenge Task Your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up. Rules 1. The input string will always be lowercase but may be empty. 2. If the character in the string is whitespace then pass over it as if it was an empty seat.
Read More
Multiples of 3 and 5 with Python
August 5, 2020
The challenge This multiples of 3 and multiples of 5 challenge is a variation of the common FizzBuzz question. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Read More
Solving the “Catching Car Mileage Numbers” Challenge using Python
August 4, 2020
The challenge "7777…8?!??!", exclaimed Bob, "I missed it again! Argh!" Every time there's an interesting number coming up, he notices and then promptly forgets. Who doesn't like catching those one-off interesting mileage numbers? Let’s make it so Bob never misses another interesting number. We’ve hacked into his car’s computer, and we have a box hooked up that reads mileage numbers. We’ve got a box glued to his dash that lights up yellow or green depending on whether it receives a 1 or a 2 (respectively).
Read More
Counting smiley faces with Python
August 3, 2020
The challenge Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Rules for a smiling face: Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ; A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~ Every smiling face must have a smiling mouth that should be marked with either ) or D No additional characters are allowed except for those mentioned.
Read More
Convert String to Camel Case using Java
August 2, 2020
The challenge Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). Examples toCamelCase("the-stealth-warrior"); // returns "theStealthWarrior" toCamelCase("The_Stealth_Warrior"); // returns "TheStealthWarrior" Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomeUnderscoreLowerStart() { String input = "the_Stealth_Warrior"; System.
Read More
How to Setup an SSH Server on AWS
August 1, 2020
Basic instructions on how to set up an SSH server on an Ubuntu 16.04/18.04 EC2 instance. Step 1 – Create a New User sudo adduser testuser Step 2 – Create a Directory for File Transfers sudo mkdir -p /var/sftp/uploads sudo chown root:root /var/sftp sudo chmod 755 /var/sftp sudo chown testuser:testuser /var/sftp/uploads Step 3 – Restrict Access to One Directory Open the SSH server configuration file sudo nano /etc/ssh/sshd_config Add the following to the bottom of the file:
Read More
How to Convert Numeric Words into Numbers using Python
July 31, 2020
Challenge Using Python, we want to convert words into numbers. In this challenge, we will explore how to convert a string into an integer. The strings simply represent the numbers in words. Let’s convert these words into numbers. Examples: “one” => 1 “twenty” => 20 “two hundred forty-six” => 246 “seven hundred eighty-three thousand nine hundred and nineteen” => 783919 Additional Notes: The minimum number is “zero” (inclusively) The maximum number, which must be supported is 1 million (inclusively) The “and” in e.
Read More
Solve The Triangle of Odd Numbers using Python
July 30, 2020
The challenge Given the triangle of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 + 5 = 8 Test cases Test.assert_equals(row_sum_odd_numbers(1), 1) Test.assert_equals(row_sum_odd_numbers(2), 8) Test.assert_equals(row_sum_odd_numbers(13), 2197) Test.assert_equals(row_sum_odd_numbers(19), 6859) Test.assert_equals(row_sum_odd_numbers(41), 68921) The solution in code While there are many ways to achieve this, the absolute most simple is to realise that the solution is just a n^3.
Read More
“Who likes it” code Challenge in Python
July 29, 2020
The Challenge You probably know the “like” system from Facebook and other pages. People can “like” blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:
Read More
Python 4 New Features Planned
July 28, 2020
It took the Python community a long time to move from Python 2 to Python 3. Now as we approach the possible end of Python 3 version history, we are approaching a potential Python 4. What to expect in Python 4 Other than Python version 4 being mentioned in the PEP documentation, there is currently no formal writeup of the Python 4 feature-set. Therefore we have to either believe that it will be the next version after 3.
Read More
Custom RGB To Hex Conversion with Python
July 27, 2020
The challenge The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 – 255. Any values that fall out of that range must be rounded to the closest valid value. Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here. The following are examples of expected output values:
Read More
Sort a Java Integer in Descending Order
July 26, 2020
The challenge Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. Examples: Input: 42145 Output: 54421 Input: 145263 Output: 654321 Input: 123456789 Output: 987654321 Test cases import org.junit.Test; import static org.junit.Assert.assertEquals; public class DescendingOrderTest { @Test public void test_01() { assertEquals(0, DescendingOrder.sortDesc(0)); } @Test public void test_02() { assertEquals(51, DescendingOrder.
Read More
Get the Sum of Digits / Digital Root using Java
July 25, 2020
The challenge Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. Examples 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2 Tests cases import org.
Read More
How to write a Chain Adding Function in Python
July 24, 2020
The challenge We want to create a function that will add numbers together when called in succession. add(1)(2); # returns 3 We also want to be able to continue to add numbers to our chain. add(1)(2)(3) # 6 add(1)(2)(3)(4) # 10 add(1)(2)(3)(4)(5) # 15 and so on. A single call should return the number passed in. add(1); # 1 We should be able to store the returned values and reuse them.
Read More
Get the next biggest number with the same digits using Python
July 23, 2020
The challenge Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example: 12 ==> 21 513 ==> 531 2017 ==> 2071 nextBigger(num: 12) # returns 21 nextBigger(num: 513) # returns 531 nextBigger(num: 2017) # returns 2071 If the digits can’t be rearranged to form a bigger number, return -1 (or nil in Swift): 9 ==> -1 111 ==> -1 531 ==> -1 nextBigger(num: 9) # returns nil nextBigger(num: 111) # returns nil nextBigger(num: 531) # returns nil Test cases Test.
Read More
Solving Tribonacci Sequence with Python
July 22, 2020
The challenge As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence: [1, 1 ,1, 3, 5, 9, 17, 31, ...] But what if we started with [0, 0, 1] as a signature?
Read More
The Casino Chips Problem Solved with Python
July 21, 2020
The challenge You are given three piles of casino chips: white, green and black chips: the first pile contains only white chips the second pile contains only green chips the third pile contains only black chips Each day you take exactly two chips of different colors and head to the casino. You can chose any color, but you are not allowed to take two chips of the same color in a day.
Read More
Check if Isogram using Python
July 20, 2020
The challenge An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. is_isogram("Dermatoglyphics" ) == true is_isogram("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter case Test cases Test.assert_equals(is_isogram("Dermatoglyphics"), True ) Test.assert_equals(is_isogram("isogram"), True ) Test.assert_equals(is_isogram("aba"), False, "same chars may not be adjacent" ) Test.
Read More
Find the Longest Common Prefix using Python
July 19, 2020
The challenge Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. The solution in Python def longestCommonPrefix(self, strs: List[str]) -> str: # the return string prefix = '' # break words into groups using `zip` and `*` # ["flower","flow","flight"] becomes: # (('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')) for group in zip(*strs): # if the characters don't match, then break if not all(char==group[0] for char in group): break # otherwise, grow the prefix prefix += group[0] # return the prefix return prefix
Read More
Count and Say with Python
July 18, 2020
The challenge he count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Read More
The Plus One problem solved with Python
July 17, 2020
The challenge Given a non-empty array of digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Read More
Solving the Single Number problem in Python
July 16, 2020
The challenge Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 The solution in Python def singleNumber(nums): # create a dictionary/hashmap found = {} # loop through the nums for i in nums: # add to map if not found if i not in found: found[i] = i else: # otherwise remove it del found[i] # loop through the found map and return the first item for i in found: return i
Read More
Rotate a Matrix List in Python
July 15, 2020
The challenge You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2:
Read More
Check if Valid Sudoku Blocks in Java
July 14, 2020
The challenge of solving valid Sudoku blocks Determine if a 9×9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. (A partially filled sudoku which is valid.) The Sudoku board could be partially filled, where empty cells are filled with the character '.
Read More
Find the Intersection of Two Arrays in Python
July 13, 2020
The challenge Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. The solution in Python code def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: # create an `answer` list answer = [] # loop through the first list for i in nums1: # check if the item is in the next list if i in nums2: # remove from the nums2 list nums2.
Read More
Rotate an Array K Times in Python
July 12, 2020
The challenge Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Constraints:
Read More
FizzBuzz in Java
July 11, 2020
The challenge Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Example: n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ] The solution in Java class Solution { public List<String> fizzBuzz(int n) { List<String> l = new ArrayList<>(); for (int i=1; i<=n; i++) { if (i%3==0 && i%5==0) { l.
Read More
Python Splices reimplemented in Java
July 10, 2020
Python has a fantastic feature called slices. It allows you to work with a list, set or string by it’s index items. E.g.: string_sample = "hello world" string_sample[:-1] >>> "hello worl" string_sample[-1] >>> "d" string_sample[3] >>> "l" You can also do things like: string_sample[3:5] >>> 'lo' Or even in reverse! string_sample[::-1] >>> 'dlrow olleh' A possible Java implementation public String slice_start(String s, int startIndex) { if (startIndex < 0) startIndex = s.
Read More
Solving Two Sum in Python
July 9, 2020
The challenge Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[] + nums[1] = 2 + 7 = 9, return [, 1]. The solution in Python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # keep a hashmap of items found seen = {} # loop through the nums, with int and value for i, v in enumerate(nums): # set remaining to the target minus the value remaining = target - v # check if the new value is in the hashmap if remaining in seen: # return it and the index return [seen[remaining], i] # otherwise, put it on the map instead seen[v] = i # nothing found, return an empty list return []
Read More
Get the Next Small Integer in Python
July 8, 2020
The challenge Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions:
Read More
Is a Valid Palindrome with Java
July 7, 2020
The challenge Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false Constraints: s consists only of printable ASCII characters. The solution in Java class Solution { // take in a String public boolean isPalindrome(String s) { // remove all non-alphanumeric characters and lowercase everything s = s.
Read More
Is a Valid Anagram with Java
July 6, 2020
The challenge Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Read More
How to ReImplement strStr() in Java
July 5, 2020
What we want to achieve Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 How to code this class Solution { public int strStr(String haystack, String needle) { // If needle is an empty string if (needle.isEmpty()) return 0; // If the needle is not within the haystack if (!
Read More
Third Maximum Number with Java
July 4, 2020
The challenge Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead. Example 3: Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number.
Read More
How to Quickly Hide all Icons on a Mac’s Desktop
July 3, 2020
Why the need to hide icons? Perhaps you have a screen-share session coming up and you want a nice clean desktop to show everyone. Also, nobody will see all your funny files and folders as they wait for you. Just open the Terminal and enter the following to hide all icons: If you’re not familiar with the Terminal; it is a Mac application that allows you to enter commands like the ones below, to enable and disable advanced features, among other things.
Read More
First Unique Character in a String using Java
July 2, 2020
The challenge Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1. Examples: s = "spacesuite" return 1. s = "simplespacesuite" return 2. Note: You may assume the string contains only lowercase English letters. The solution class Solution { // take in a String and return an int containing the index public int firstUniqChar(String s) { // create a HashMap to hold our counts HashMap<Character, Integer> h = new HashMap<>(); // get the string's length int len = s.
Read More
How to fix the Release Version 5 Not Supported error in IntelliJ
July 1, 2020
What do you do when you create a new Maven Java project, and when you run it, you get the following error: Error:java: error: release version 5 not supported Sometimes the error could also read as follows: java: Source option 5 is no longer supported. Use 6 or later. Luckily for us, the solution is exactly the same! Solution Open the project’s pom.xml file and add the following snippet: <properties> <maven.
Read More
Facebook’s custom IPv6 range
June 30, 2020
I noticed an interesting thing with a certain visitor after posting a blog post to Facebook. The IP address that the Facebook crawler uses to visit the site on callback to get meta-data has a custom IPv6 sub-range. IPv6: 2a03:2880:ff:1a::face:b00c Host: fwdproxy-prn-026.fbsv.net Notice 2a03:2880:ff:1a::<strong>face:b00c</strong> How this is done The IPv4 addresses could only use regular integers (decimal); numbers between 0 and 9. However, IPv6 can use any and all hexadecimal; 0-9 and a-f.
Read More
How to Reverse an Integer in Java
June 29, 2020
The challenge Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Read More
Reverse a String in-place using Java
June 28, 2020
The challenge Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] The solution The goal here is to not create a new array, or string, but to rather make the change in-place using the single character array.
Read More
Check if a Java array Contains Duplicates
June 27, 2020
The challenge Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true The solution class Solution { // return a boolean from the primitive int array input public boolean containsDuplicate(int[] nums) { // create a HashMap to hold our values HashMap<Integer, Integer> hm = new HashMap<>(); // loop through the input array for (int i=0; i<nums.
Read More
Find All Numbers Disappeared in an Array using Python
June 26, 2020
The challenge Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] The solution class Solution: # our method def findDisappearedNumbers(self, nums: List[int]) -> List[int]: # get the length / amount of items l=len(nums) # create a `set` to remove duplicates nums=set(nums) # create a new array to return d=[] # loop through the amount of items in the input array for i in range(1,l+1): # if the item is not in the input list if i not in nums: # add it to the return list d.
Read More
The Array Height Checker Problem in Java
June 25, 2020
The challenge Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats. Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: Current array : [1,1,4,2,1,3] Target array : [1,1,1,2,3,4] On index 2 (0-based) we have 4 vs 1 so we have to move this student.
Read More
Find the Squares of a Sorted Array in Java
June 24, 2020
The challenge Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. The solution class Solution { // return the sorted array squared public int[] sortedSquares(int[] A) { // create a new primitive int array int[] res = new int[A.
Read More
Sorting a Java Array by Parity
June 23, 2020
The challenge Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Note: 1 <= A.length <= 5000 0 <= A[i] <= 5000 The solution class Solution { // return a sorted primitive int array public int[] sortArrayByParity(int[] A) { // keep track of place int lastIndex = 0; // loop through input array for (int i=0; i<A.
Read More
Remove Duplicates from Sorted Array in Java
June 22, 2020
Say you have an array of primitive integers and you want to remove all duplicates. You can find out how many non-duplicate integers are in the array with this method: class Solution { public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } } Because we pass the nums array in as a reference, and modify the variable in-place with no additional space, you could just continue using it as is.
Read More
Replace Elements with Greatest Element on Right Side using Java
June 21, 2020
The challenge Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Constraints: 1 <= arr.length <= 10^4 1 <= arr[i] <= 10^5 The solution class Solution { public int[] replaceElements(int[] arr) { // loop through all array items for (int i=0; i<arr.
Read More
The Valid Mountain Array Problem using Java
June 20, 2020
Introducing the problem Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A is a mountain array if and only if: A.length >= 3 There exists some i with 0 < i&nbsp;< A.length - 1 such that: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1] The constraints Example 1: Input: [2,1] Output: false Example 2:
Read More
HashMaps (aka: Dictionaries) in Python
June 19, 2020
Introduction Java has a built-in called HashMap. It allows you to store and very quickly retrieve key value pairs. In Python, this is called a dictionary and appears very similar to a JSON Object for those familiar with Javascript and similar languages. Dictionaries as HashMaps An example of a dictionary in Python is as follows: ages = {"Bob":25, "James":54, "Darren":44} The same can be created using the dict keyword: ages = dict({"Bob":25, "James":54, "Darren":44}) A third way to create and populate this:
Read More
Find Numbers with Even Number of Digits using Java
June 18, 2020
The challenge Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits.
Read More
The Relational Database Model
June 17, 2020
Relational databases first made an appearance in the mid-1970s, between the years 1974 and 1977 with the creation of Ingres and System R which led to the creation of MS SQL Server, Sybase, Wang?s PACE and Britton-Lee to name a few (Quickbase, n.d.). It was only until the 1980s that SQL (Structured Query Language) became the standard query language used by relational databases. Basic features of the relational data model:
Read More
How to use a Java HashSet by example
June 16, 2020
What is a HashSet A HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1) Learn with a Programming Question Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister.
Read More
Get The Shortest Path in Binary Matrix using Python
June 15, 2020
The challenge In an N by N square grid, each cell is either empty (0) or blocked (1). A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that: Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner) C_1 is at location (0, 0) (ie. has value grid[0][0]) C_k is at location (N-1, N-1) (ie.
Read More
Palindrome Partitioning in Python
June 14, 2020
The problem Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] The solution def partition(self, s: str) -> List[List[str]]: ret = [] def isPal(s): return s == s[::-1] def fn(s, l): if not s: ret.append(l) return for i in range(1, len(s)+1): if isPal(s[:i]): fn(s[i:], l+[s[:i]]) fn(s, []) return ret
Read More
Faster alternative to MySQL Delete Table Contents / Truncate
June 13, 2020
From time to time you might have some rather big tables that you want to delete all the data quickly and start afresh. You have a few options at this point. The first you?ll probably look at is: DELETE FROM `table_name` The benefit of doing this is DELETE provides the ability to Rollback if all hell breaks loose, but it also means that it will take longer because it requires more memory to store all this additional data
Read More
Best Time to Buy and Sell Stock with Python
June 12, 2020
The problem Say you have an array prices for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Read More
IPv4 CIDR Chart
June 11, 2020
CIDR stands for Classless Inter-Domain Routing and is a method for allocating IP addresses as well as for IP routing. It was introduced in 1993 by the Internet Engineering Task Force to replace the previous classful network addressing architecture on the internet. When choosing a CIDR range for your network, the following chart will show you how many maximum IP’s you can have on that network. For example, /32 will give you 1 usable IP, /24 will give you 256 usable IPs, while /3 will give you 512 million usable IPs.
Read More
Recursively Delete Files and Folders and all Contents using PHP
June 10, 2020
Below is a quick and easy way to recursively delete all files and folders in a given path using PHP. function destroy_dir($dir) { if (!is_dir($dir) || is_link($dir)) return unlink($dir); foreach (scandir($dir) as $file) { if ($file == "." || $file == "..") continue; if (!destroy_dir($dir."/".$file)) { chmod($dir."/".$file, 0777); if (!destroy_dir($dir."/".$file)) return false; } } return rmdir($dir); } destroy_dir("/var/www/site/public_html/directory/");
Read More
Product Update: ADD becomes Serengeti
June 9, 2020
As a product update; The “Autonomous Distributed Database”, otherwise known as simply ADD has been renamed to Serengeti. The Serengeti is a vast ecosystem in east-central Africa. It spans 12,000 square miles (30,000 square kilometers), according to NASA, giving rise to its name, which is derived from the Maasai language and means “endless plains.” This region of Africa is located in north Tanzania and extends to southwestern Kenya. Much the same, the Serengeti database project is a truly autonomous distributed system that has no visible ending nor capacity.
Read More
SQL to Append all Fields if Shorter than a set Length
June 8, 2020
This came in very handy for me at one point because I needed to have a certain field in each row 14 characters long, but half of them were only 12 characters long. In MySQL: update `table` set `field` = CONCAT(`field`, '1') where LEN(`field`) = 13; In MSSQL: update `table` set `field` = CONCAT(`field`, '1') where LENGTH(`field`) = 13;
Read More
Validate Email Address in Javascript
June 7, 2020
Below is a nice little Javascript RegularExpression to validate email addresses. /^\w.+@[a-zA-Z_.]+?\.[a-zA-Z.]{2,3}$/ ..and to use it.. if (/^\w.+@[a-zA-Z_.]+?\.[a-zA-Z.]{2,3}$/.test(email)) alert("Success"); else alert("Fail");
Read More
Remove hash from window.location in Javascript
June 6, 2020
E.g. URL:<br>http://example.com/?option=1&task=2&listing_id=36&layout=4&table=5#some_hash_value_here So how would you get the current URL using Javascript? That is really easy, you can use window.location.href or just simply window.location. But how do you replace the #hash at the end if it exists? That too is quite easy, you can just do something like this: window.location.href.split("#")[0] or window.location.href.substr(0, window.location.href.indexOf("#")) So now that we have the value of the current URL how do we refresh the page with it?
Read More
The Benefits and Dangers of Artificial Intelligence
June 5, 2020
Artificial Intelligence (AI) is usually defined as the science of making computers do things that require intelligence when done by humans. (Jack Copeland, 2000) Current Benefits of AI Replicate the decisions and actions of humans without human shortcomings. Computers don’t get fatigued and tired. Computers are not biased by emotions. Tasks are scalable and can be done very quickly and effectively. Current Dangers of AI Some decisions require a level of grey area.
Read More
The Decoded String at Index using Java
June 4, 2020
The Challenge An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total. Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.
Read More
Timing Issues in Real-time systems
June 3, 2020
What are Real-time Systems? If you look up the term “real-time” in a dictionary, it will tell you that it is the actual time during which a process takes place or an event occurs (Dictionary.com, n.d.). In computing, it is more often than not due to when an event is created and specific data service is able to respond with the newly updated event in its index. What is a Timing issue?
Read More
Find the Minimum Absolute Difference in BST using Java
June 2, 2020
The question Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. Example: Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). Note: There are at least two nodes in this BST. The solution We will start with a stub to build out:
Read More
Get the Second Highest Salary in MySQL
June 1, 2020
The problem Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ The solution SELECT DISTINCT Salary AS SecondHighestSalary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 The output {"headers": ["SecondHighestSalary"], "values": [[200]]}
Read More
Find Maximum Subarrays using Java
May 31, 2020
The problem Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. The code // This method takes an array of `ints` and returns an `int` public int maxSubArray(int[] nums) { // Set some `max` variables, // ..firstly the minimum `Integer` value // ..secondly `0` int max = Integer.
Read More
Finding Number Complements using Java
May 30, 2020
The problem Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0.
Read More
Forensic Analysis on Linux (Unix)
May 29, 2020
Operating Systems come in a few competing choices, of which the major players are Apple’s MacOS, Microsoft’s Windows and then the various flavours of Linux, of which most are open-sourced while the remainder are proprietary to their vendors. Of the three, Windows is the most dissimilar, with MacOS and Linux sharing a similar BSD/Unix platform running behind the scenes. This gives MacOS and Linux similar traits when it comes to logging, analysing and tracing system event-logs.
Read More
Self Dividing Numbers using Python
May 28, 2020
Introduction A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
Read More
RuntimeError: thread.__init__() not called (Python)
May 27, 2020
Today I got a really dumb error from Python. RuntimeError: thread.init() not called But luckily it’s really easy to fix! Below is the code before (with the error): class SomeThread(Thread): def __init__(self, myVar): self.sMyVar = str(myVar) def run(self): self.sMyVar = "bla.." + self.sMyVar And now for the code that resolved the problem: class SomeThread(Thread): def __init__(self, myVar): Thread.__init__(self) self.sMyVar = str(myVar) def run(self): self.sMyVar = "bla.." + self.sMyVar If you have really bad eye-sight and can’t spot the difference between the 2 code block above 😛
Read More
All About Distributed Databases
May 26, 2020
A database “is a structured collection of data. Card indices, printed catalogues of archaeological artefacts and telephone directories are all examples of databases”. We are going to examine databases that are prevalent in computer systems and go through the core differences between Local and Distributed Databases. Local A local database is an isolated database that is stored on a single computer and does not share its data outside of itself or its direct access network.
Read More
Communications and The Software Development Process
May 24, 2020
Software Engineering or the Software Development Process is broken down into the following phases. Requirements Design Implementation Verification Maintenance Communication can often breakdown in the system analysis phases. As a knock on effect, the requirements and design can end up not being correctly implemented during the mid to latter stages of software development. Without correct communication, a software system can end up not meeting the requirements initially laid out by the end client – or whomever requested the system in the first place.
Read More
Get the total size of all the files in a directory
May 23, 2020
It’s amazing how many times I’ve need to find out the total size of all the files in a directory on one of our servers. I have grown to love the simplicity of the `du` command. du -sh du = Display disk Usage statistics s tells us to display an entry for each specified file, while h is for “human-readable” output. This will use the unit suffixes of Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte.
Read More
Structured and Object-Oriented Programming
May 22, 2020
Software development has really come a long way over the past few decades. Programming used to always be about doing things in a very procedural way, this means that each line of code is executed in the order that it is written (or placed) in a source code document – we refer to a file where programming code is stored as “source code”. This is still very much a core basis when writing code, except as software applications have gotten infinitely more expansive and complex, there has been more of a need to reuse sections of code and make it more “modular”.
Read More
Moving a MySQL Database without downtime
May 21, 2020
At Statvoo Analytics we found ourselves in the position where we needed to move our master MySQL database without ANY downtime and for anyone who’s tried to do this, you will know how hard this can be if it is not done exactly right. Below I will run through the steps to get the job done efficiently and with no downtime (unless you mess it up that is). First, you need to configure the master’s /etc/mysql/my.
Read More
How to use Google Analytics in AngularJS
May 20, 2020
It seems to be quite a popular question with not as many answers to hold the weight. Google Analytics has always been more of a pageviews type tracking use case and up until a few years ago that was all anyone ever really did anyways. However, the web has gotten a lot more complicated with the introduction of javascript and heavy ajax based sites and web applications. This has caused quite a change in how Analytics Tools are used and how they are expected to gather statistics.
Read More
Converting from Legacy to Client-Server or Distributed Systems
May 19, 2020
What is a legacy system? A legacy system is a computing system that has been around for a very long period of time, tends to be difficult to maintain, is prone to issues such as lack of scalability and feature additions, usually centralised in operation and is still heavily utilised in a particular organisation. What is a client-server / distributed system? A distributed system is a decentralised networked cluster of computers (servers) that are able to scale according to peaks and troughs in usage (Manoj A.
Read More
Conceptual Architectural Views, with a focus on the Development View
May 18, 2020
What is Conceptual Architectural Views? Architectural views are abstractions, or simplifications, of the entire design, in which important characteristics are made more visible by leaving details aside. (Eclipse, n.d.) They are divided into four main sub-categories as illustrated below when using the 4+1 modelling system: Each of the above segments paints a different perspective view on the architecture of a complex system, allowing for a simplified look into the inner workings and how everything works together.
Read More
Assessing Reusable Parts in a Software Architecture
May 17, 2020
During the Software Development Life Cycle (SDLC) the development team will come to realise that parts of any application have already been created before and there is the potential for those parts to be reused time and again going forward. In the last few years, the culture of software development has moved towards Q&A sites such as StackOverflow to answer common daily problems that developers face. This has also led to many “Accepted Answers” being associated with these common issues and many developers have become quite indolent and simply copy/paste the code snippets directly from these types of websites straight into their application code they plan to ship.
Read More
An Introduction to 2-Tier and 3-Tier Client-Server Systems
May 16, 2020
All software systems can be grouped in either a 2-tier or a 3-tier formation. The former is essentially where all clients contain application and business logic code to read from a datastore themselves (STC, n.d.) and the latter by comparison relies on a thin client that talks to an application layer server that contains business logic which in turn communicates with the datastore. 2-Tier Architecture The two-tiered (2 tier architecture) approach to application modelling is to run a fat client – one which contains all business logic code – and communicate directly with a database server itself.
Read More
Remove the Outermost Parentheses using Python
May 15, 2020
The Question A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.
Read More
The Pros and Cons of Agile in Software Development
May 14, 2020
What is Agile in Software Engineering? Agile approaches help teams respond to unpredictability through incremental, iterative work cadences and empirical feedback. (AgileMethodology.org, 2008) Advantages of Agile Flexibility Potentially the main advantage to Agile is the ability to be more ?flexible? or ?agile? in terms of evolving a project as it develops as opposed to taking on a mammoth list of project requirements and only being able to show the customer the end result at project completion.
Read More
Contemporary and beneficial uses of Big-Data Systems
May 13, 2020
Big data is a term applied to datasets whose size or type is beyond the ability of traditional relational databases to capture, manage, and process the data with low-latency. (IBM, 2018) The V’s of Big Data They share at least one or more of the common V’s; known as Volume, Velocity and Variety. Additionally, Veracity, Variability, Visualisation and Value are often seen to be added to the core list as drivers towards a more rounded architecture.
Read More
Distributed Database Systems Observations
May 12, 2020
Traditional database systems were a centralised powerful database server that housed all operations pertaining to the database. There are countless reasons that this is unsustainable when larger databases are employed, specifically for globally distributed companies and popular applications as already known today. A single database server may suit many database’s requirements, but at some point, there may be a need to scale up to support higher demand or for global capacity requirements of sorts (Shalom, 2017).
Read More
Functions of an Operating System
May 11, 2020
I am in a bit of an unusual situation where “I use” a combination of three different laptops, which each run different platforms. Namely; MacOS primarily at work with a combination of Linux servers and then Windows as well as Ubuntu on two separate home laptops that I switch between on my desk all the time between tasks. A bit on Windows Windows is good as a general consumer OS and there are many applications that are created to run on it.
Read More
ORDER BY RAND() – Faster Alternative
May 10, 2020
MySQL’s ORDER BY RAND() function can be so useful for returning random items from a table, in fact, we have used it a million times over the years. The problem comes when your database tables start getting really big. We found a very nice alternative to using it and thought it useful to post here for everyone else to use and/or provide feedback on. Say you have a SQL query as follows: (slow on big tables)
Read More
Top-down vs Bottom-up Database Design
May 9, 2020
There are essentially two different approaches one can take when designing databases; these, from a high-level analytic point of view, narrow down to what is typically called “Top-down” and “Bottom-up” philosophies or methods. While these methodologies can appear profoundly unique, they share the shared objective of joining a system by portraying the greater part of the association between the procedures. Top-down What is top-down approach to database design Top-down design, is characterized by an extensive planning and research phase that leads into the development of the database (Maxey, 2012).
Read More
How to keep your web server or blog up when you get a traffic spike
May 8, 2020
So you’re about to be featured on some very high ranking website. You’re worried that when all the visitors come rushing towards you, your web server?is going to crash and burn.?Well, you’re probably right! Did you know that 95% of all websites on the internet are not able to handle more than 30 concurrent visitors the way they are setup? Even worse still, most websites run off of either Shared hosting or un-tweaked VPS configurations that are not meant to handle many visitors in the first place.
Read More
How to get the UTC Timestamp in Python
May 7, 2020
All dates in your server applications should be stored in the UTC timezone. This is because you always want to store time without the offset of the timezone you may be working in. Clients of your application may be in many different timezones around the world. However, storing all data in the UTC or GMT (same thing) timezone, is ideal as it gives your application the ability to present times and dates back in the same methodology.
Read More
How to setup the AWS CLI for multiple profiles
May 6, 2020
The AWS CLI provides the ability to use the wide range of Amazon Web Services tools and services straight from the command-line. However, sometimes it’s useful to be able to login to multiple AWS accounts. Luckily, this is possible by adding an additional profile to your local configuration and then specifying it when making calls to respective services. Update your local credentials Step 1. ~/.aws/credentials [default] aws_access_key_id = "<MY_FIRST_AWS_KEY_ID> aws_secret_access_key = "<MY_FIRST_AWS_SCRET_ACCESS_KEY>" [andrew] aws_access_key_id = "<MY_SECOND_AWS_KEY_ID> aws_secret_access_key = "<MY_SECOND_AWS_SCRET_ACCESS_KEY>" Fill in your own details for the second grouping, mine is called andrew.
Read More
How to get the size of an AWS S3 bucket
May 5, 2020
If you need to get the size of an AWS S3 folder, or even an entire bucket, you can do so with the following command: aws s3api --profile list-objects --bucket --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk 'NR!=2 {print $0;next} NR==2 {print $0/1024/1024/1024" GB"}' If you don’t use aws cli profiles, then you can leave out the profile part like this: aws s3api list-objects --bucket --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk 'NR!
Read More
Comparing Java and Javascript
May 4, 2020
Perhaps the first thing that most people ask when they hear the names of these two programming languages are. “Why do they have the same name?” and “Are they the same thing?”. There is a general misconception that because Java and Javascript share a similar name to one another, that they are indeed one and the same; but in reality, they are very different languages, which each address different types of problems and only share the smallest of traits.
Read More
An Introduction to Data Structures
May 3, 2020
When bringing up the topic of “Data Structures”, it is first important to understand what they are. TechTarget states that “a data structure is a specialized format for organizing and storing data”. This provides a high-level definition to get you started; so let’s explore it a little deeper. Below are a few examples of common data structures: Primitive types: Boolean, Integer, Double, Character, String Composite/Non-primitive types: Array, Record, Union Abstract types: List, Associate Array, Stack, Queue, Tree
Read More
Relational Database Proprietary Extensions
May 2, 2020
Standard Query Language – or SQL for short – is a language designed for relational databases that allows end users such as developers and database administrators (DBAs) to manipulate data. Whether that be INSERT-ing, UPDATE-ing, DELETE-ing, SELECT-ing or otherwise ALTER-ing almost any amount of data; SQL provides an effective way of utilising the database system/engine by providing standardised language to do so. The American National Standards Institute (ANSI) SQL became the standard in 1986 when the specification described the official features of the SQL language (Karmin, 2015).
Read More
Locks used in Database Management Systems
May 1, 2020
Database Management Systems (DBMS?) are designed to store any amount of data that can then be retrieved or manipulated at a later date. In order to make sure that the data can be concurrently utilised in parallel by numerous processes or users, it is important to have some form of Locking enforced so that if a particular record is being modified or created, then another process is not allowed to simultaneously adjust the same record.
Read More
Tail and Grep: display all output but highlight search matches
April 30, 2020
I tail logs quite a lot. An example would be to tail the Apache2 access logs. This is simple to do: tail -f /var/log/apache2/access.log This will show a trail of all access log entries as they come in. What if we only wanted to see when Googlebot accessed the site? Highlight entries We could filter only these results: tail -f /var/log/apache2/access.log | grep -i googlebot This will tail all logs, and grep will only shows results for case-insensitive instances of googlebot entries.
Read More
Convert URL String into a Javascript Object
April 29, 2020
Sometimes you find yourself with a String, something like and you want to repeatably access elements of it correctly. Let’s say that you want to only get the origin of a URL, or maybe the host, or even protocol, how would you do this? The URL object Javascript brings you the URL object, which allows you to instantiate it with a string, and optionally a base to work from. new URL(url, [base]) By using this object, you can achieve all of this very easily.
Read More
How to make an HTTP Request in AWS Lambda using Python
April 28, 2020
The requests module for Python is very useful in helping simplify HTTP/s requests from Python, but how would you use it in an AWS Lambda script? Option 1 – Use requests import The requests library is very popular among Python enthusiasts. You will need to create a custom lambda layer and include requests This will allow you to use import requests in your code. Download the folder package pip install requests -t .
Read More
How to fix a Javascript Uncaught ReferenceError
April 27, 2020
Sometimes you may get an error that looks something like this: Uncaught ReferenceError: <some_variable_or_function> is not defined At first this can be quite the pain, but it usually just means that that variable, or function has either not been defined, or it isn’t ready for use yet. It’s good practice to wrap this bit of code into a conditional check. The original code if (variable_or_function) { //console.log(variable_or_function); } The improved code if (typeof variable_or_function !
Read More
Resolving InsufficientPrivilege Errors in Redshift
April 26, 2020
If you are getting the mysterious error: [ERROR] InsufficientPrivilege: permission denied for schema errors Then you can easily resolve this by running the following SQL: GRANT USAGE ON SCHEMA <schema_name> TO <redshift_user>; Another common error that often follows this, is: [ERROR] InsufficientPrivilege: permission denied for relation <table> Luckily, this too can be resolved by running the following SQL: GRANT USAGE ON SCHEMA <schema_name> TO <redshift_user>; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema_name> TO <redshift_user>;
Read More
How to increase column size in Redshift database tables
April 25, 2020
It is only possible to alter VARCHAR columns, and only under the following circumstances: You can not alter a column with compression encodings BYTEDICT, RUNLENGTH, TEXT255, or TEXT32K. You can not decrease the size less than the maximum size of existing data. You can not alter columns with default values. You can not alter columns with UNIQUE, PRIMARY KEY, or FOREIGN KEY. You can not alter columns inside a multi-statement block (BEGIN.
Read More
[Solved] The provided execution role does not have permissions to call CreateNetworkInterface on EC2
April 24, 2020
If you are trying to get an AWS Lambda added attached to a VPC, but get the error message: The provided execution role does not have permissions to call CreateNetworkInterface on EC2 There are 3 ways to solve this problem Below we will look at 3 different options when it comes to solving this problem: Fix the problem in Terraform Fix the problem in CloudFormation / SAM Fix the problem Manually in the AWS Console How to fix the problem in Terraform resource "aws_iam_role_policy_attachment" "AWSLambdaVPCAccessExecutionRole" { role = aws_iam_role.
Read More
Entity and Referential Integrity in Relational Databases
April 23, 2020
Data integrity is the overall completeness, accuracy and consistency of data (Techopedia, n.d.). In order to achieve data integrity, it is important to analyse Entity and Referential integrity constraints. Entity Integrity Focuses on Primary keys. Each table should have a primary key and each record must be unique and not null. This makes sure that records in a table are not duplicated and remain intact during insert, update and retrieval.
Read More
Data Warehouses vs Data Marts
April 22, 2020
Although the terms “data warehouse” and “data mart” sound similar, they are quite different. It is important to first understand how they differ in order to define some characteristics and practical applications for each. Serra (2012) has a great explanation of data warehouses as being “a single organizational repository of enterprise-wide data across many or all subject areas”; while Inmon classifies the data mart as “a logical view or a physical extract of a larger data warehouse, usually isolated for the need to have a special data model or schema” (n.
Read More
Amazon’s custom Whois date entry
April 21, 2020
Whois is an online service that let’s you know registration information about a website or IP address. For the most part, Whois aggregations are not that standard, however, per gTLD (.com, .net, .yourkitchsink) they try their best to apply the same overall guidance and regulatory patterns. Most individuals, as well as businesses will go about registering their domain name through a service such as GoDaddy, Namecheap, or some other common domain registrar.
Read More
Graph Databases and their Properties
April 20, 2020
The concept of a graph in mathematics is simply a collection of elements which are typically called Nodes and are joined together by Edges. Each Node represents a piece of information in the graph and each Edge represents some relationship or connection between any of the two Nodes (Cox, 2017). A graph database is simply a database that models itself on the connections that Nodes represent in a mathematical graph structure.
Read More
How to add SSH keys to GitHub
April 19, 2020
When working with GitHub, you will need to identify yourself. The default way is using your username and password. However, you can also create an SSH key-pair that can be used instead. By using this technique, you can generate a password and not have to use it each and every time. You can also reuse your machine’s generated key-pair for other SSH services. A private and public key is created locally on your machine, and the private key always stays on your own machine.
Read More
Get the Maximum Length of a Concatenated String with Unique Characters in Python
April 18, 2020
The problem Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters. Return the maximum possible length of s. Example test-cases Example 1: Input: arr = ["un","iq","ue"] Output: 4 Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique". Maximum length is 4. Example 2: Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible solutions are "chaers" and "acters". Example 3: Input: arr = ["
Read More
Apache Kafka’s Role in Big Data Streaming Analytics
April 17, 2020
The world of Big Data started out as a way of storing and querying obscene amounts of information by comparison to what yesteryears were able to achieve. However, most value in said data is primarily found in the real time or streaming information that is presented as it first enters the system. As data gets old, it also gets stale and less useful to many business systems. Streaming analytics platforms have come a long way with numerous open source projects offering advanced products such as Flink, Spark Streaming, Samza and Storm; which are all at the forefront of the arena in their respective strengths.
Read More
Mitigating Risks with Software Development Outsourcing
April 16, 2020
In the Oxford Dictionary, the term “outsourcing” is simply defined as obtaining goods or services by contract from an outside supplier (OxfordDictionaries.com, n.d.). When it comes to software development, the same is true, with many companies opting to use economically cheaper labour to extend or swap out their workforce in order to enhance their endeavours and reduce costs across the board. Countries such as India, Russia, China and Mexico have a lower Cost of Living (Numbeo.
Read More
The Primary Data Types in Java
April 15, 2020
In Java there are eight basic data types; which are: byte, short, int, long, float, double, boolean and char. It could realistically be said that a Java developer’s time is primarily spent using these particular variable types to store, retrieve and manipulate data to complete most programming tasks. However, there are many times that these primitive variables don’t quite suffice and additional data types need to be explored and used instead.
Read More
Comparing Objects in Java
April 14, 2020
TLDR; When to use == in Java When comparing two operands. It is used to check whether two operands are equal or not. It’s best to only use it when working with primitive data types, such as int, float, char or sometimes even Booleans When to use equals() in Java This method is best used when comparing String types. When to use compareTo() in Java It is good to use compareTo when you need to compare two String literals.
Read More
Overloading Operators in Java
April 13, 2020
As with many programming languages such as C, C++ and C# (known commonly as the C family), it is possible to “overload methods” (sometimes called functions if not used in classes, such as C) in order to take a different amount of parameters so that they can be used in multiple scenarios with similar internals. As Java is derived from the C style of languages (C family), it too can perform Method Overloading.
Read More
uncaught typeerror: $ is not a function
April 12, 2020
The dollar-sign ($) in Javascript has for many years now been associated with jQuery. When you see this error: “uncaught typeerror: $ is not a function ” It almost always means that a jQuery piece of code is being run before the jQuery library has been initialised and loaded. Oftentimes, your code will wait for jQuery to load before continuing any processing, this is almost always done as follows: $(document).ready(function(){ // jQuery code is in here }); However, it’s not uncommon to get an “TypeError: $ is not a function ” error in response.
Read More
How to get the last element of a list in Python
April 11, 2020
Let’s say that you have a Python list with the following 5 foods: foods = ["pizza", "pasta", "steak", "chicken", "olives"] How do we go about getting the last item? Option 1 It’s actually really easy, you can select the index item by it’s total length minus one. last_item = foods[len(foods)-1] # "olives" Option 2 Python has some really fantastic functionality around making your life easier. One of those such things is the ability to use slices.
Read More
How to embed a web server in your Python3 app
April 10, 2020
This is not the first time that I created a Python3 application that spat out some output and required access to it via an HTTP server. While there are numerous ways to achieve this, a really simple way is to embed an HTTP server directly in your Python3 application, and have it serve your output directly when called. A sample web server in Python from http.server import HTTPServer, BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.
Read More
How to get the Range Sum of Binary Search Tree using Java
April 9, 2020
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Examples Example1: Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32 Example2: Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23 Our solution in Java /** * Definition for a binary tree node.
Read More
How to duplicate zeros in place using Python
April 8, 2020
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function. Examples Example1: Input: [1,0,2,3,0,4,5,0] Output: null Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] Example2: Input: [1,2,3] Output: null Explanation: After calling your function, the input array is modified to: [1,2,3] Writing the code # declare our function def duplicateZeros(arr): # create our incrementor i = 0 # loop through all dynamic elements while i < len(arr)-1: # if the character is a zero if arr[i]==0: # remove the last item from the array arr.
Read More
A Quick Introduction to Asyncio in Python3
April 7, 2020
Python has never been the best at doing multiple things at the same time. While there are ways to mostly resolve this, such as using the Multiprocessing library , it always seems a bit make-shift to me. So many other languages have fantastic ways of resolving these types of issues, and Python now has an Async way too! Introducing Asyncio Asyncio is a library to write concurrent code using the async/await syntax.
Read More
How to replace newlines with commas in CLI
April 6, 2020
If you need to replace all newline characters with a comma, or perhaps some other delimiter, then using the build-in tr utility will work very well for you. Possible use-cases for this is if you need to transport a configuration file with multiple lines into a single input field, or store the file’s contents within an environment variable. My personal use-case was to store an ~/.aws/credentials file in an environment variable.
Read More
How to make a disk cache using PHP
April 5, 2020
If you have a busy PHP driven website and don’t want to make constant queries to the database for each user that will see the same data, then you can easily resolve this problem by letting the first of these visitors generate a cache for the consecutive visitors. Letting this cache last for a few minutes allows your database to not get overloaded and allows for a much faster website experience as well as a much cheaper hosting bill for you at the end of the month.
Read More
How to remove files without a certain extension?
April 4, 2020
You have a directory with a lot of files, and you want to delete only the files that don’t match a specific extension. This is a simple task when using the find command-line utility. Delete a single extension You can delete all files that do not have the following *.txt extension: find . -type f ! -name "*.txt" -exec rm {} \; Delete multiple extensions You can delete all files that do not have the following *.
Read More
How to debug an Apache 404 error
April 3, 2020
So you are getting an error 404 or perhaps even worse, a 500! The error in your Apache2 logs looks something like this: ***.162.245.*** - - [03/Apr/2020:12:49:50 +0000] "GET /robots.txt HTTP/1.1" 404 89670 "-" "Mozilla/5.0 (compatible; SomeUserAgent/2.1; +https://example.com)" In a perfect world, you’d only have a single site/domain on this host, so will know that the robots.txt file would reside in the Apache root serving directory. However, I just happen to (as you?
Read More
How to Reorder Data in Log Files using Python
April 2, 2020
Let’s say that you have an array or a list, or logs. Each of these logs is a space-delimited string of words. For example: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] The task is to reorder these logs and return them in the following acceptance criteria: The first entry (identifier) of each log is ignored but still returned The letter-logs are returned before the digit-logs The identifier is only used to sort these there is a tie How to analyse the problem At first glance, this appears to be something that could be easily solved by looping through each log entry and if the second part of the entry is a string type, then adding it to a tempA list, otherwise adding it to a tempB list.
Read More
Another WTF Javascript Moment
April 1, 2020
Javascript is a powerful language, but sometimes it doesn’t always do what you expect it to. Take the following expression for example. It’s a simple if statement that checks to see if true and then runs the code within the block. Running the code results in the block being executed, however, when we directly compare the statement’s comparison against a false value, we can see that it is in fact, not actually true.
Read More
How to Bring Back GROUP BY in MySQL
March 31, 2020
If you are suddenly not able to perform GROUP BY statements as you used to after a MySQL/MariaDB version update, then you will have noticed the change forced upon you. You can re-enable the previous GROUP BY behaviour by editing your /etc/mysql/my.cnf and adding in the following line below the [mysqld] section: [mysqld] sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" This will allow you to GROUP BY without having to return all those specific columns as well.
Read More
How to implement a Queue using Stacks in Python
March 30, 2020
A common programming interview question, and for a change, one that you will actually be able to use in the job, is that of implementing a Queue by means of using Stacks in Python. The 5 common operations of a Queue Instantiation push(val) pop() peek() empty() What each operation does Instantiation is the Queue’s storage object that will be used. class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.
Read More
Find positions of largest groups of characters in a String with Python
March 29, 2020
The question Take a string S of lowercase letters. These letters form consecutive groupings of like characters. Find groups with 3 or more like characters and return a list of lists of starting and ending index for each character group. Elaboration and examples If we show an example, we could say S = "abbcccdeffffy". This string has 2 groups, c and f who’s consecutive characters are of 3 or more.
Read More
How to make Git “forget” about a file that was tracked but is now in .gitignore?
March 28, 2020
You can ignore certain files and folders from being committed to Git by means of including a .gitignore file. Unfortunately, you may have forgotten to include certain entries and now find that there are files and/or folders that git will want to commit. To start with, you should make sure that the relative path to the file or folder is included in your .gitignore file. Then run one of the below commands.
Read More
How to Purge the BinLog for MySQL and MariaDB
March 27, 2020
If you see lots of disk space quickly disappearing on your MySQL or MariaDB server, then you may want to look into the BinLog directory, it is located at /var/log/mysql/. In my case I saw this: usr@server-1:/var/log/mysql# ll total 5571044 drwxr-s--- 2 x x 4096 Mar 25 18:18 ./ drwxrwxr-x 12 x x 4096 Mar 25 05:25 ../ -rw-rw---- 1 x x 104857748 Mar 23 09:29 mariadb-bin.000301 -rw-rw---- 1 x x 104859422 Mar 23 10:07 mariadb-bin.
Read More
How to Measure Execution Time in Google Colab
March 26, 2020
Google Colab is a fantastic environment to write Python code using Jupyter Notebooks, hosted for free by Google. If you’ve ever used Jupyter Notebooks before, it is the same principle, you write Python code in a cell and you are able to execute each cell as you require. Measure Execution Time But how would you measure the time each cell takes to execute? Luckily, within Google Colab, you are able to install additional Python Packages through pip by prepending the command with an exclamation mark !
Read More
How to fake a User Agent in Python
March 25, 2020
A User-Agent is a bunch of text that is sent with every HTTP and HTTPS request. The server processing this request is able to determine what type of device and browser has made the request. Often times servers use this parameter to restrict access to the resource. However, it’s easy to fake a User-Agent when using Python to make HTTP and HTTPS requests. Using Requests Library import requests user_agent = 'Mozilla/5.
Read More
How to Delete from a Table where rows match in Another Table – MySQL
March 24, 2020
So you have a table where you want to delete a bunch of rows, based on a particular column being matched in another table. This is easily achievable with MySQL. DELETE FROM TABLE1 WHERE domain IN ( SELECT domain FROM TABLE2 ) The above SQL will delete all rows in TABLE1 that are found in TABLE2. But what if we need to limit which records are returned from TABLE2? That’s simple too.
Read More
REPLACE INTO instead of INSERT INTO – MySQL
March 23, 2020
There are many occasions where you need to INSERT a record into a MySQL database table, but the record already exists. INSERT INTO queue_domains (domain) VALUES('statvoo.com') This will result in a Duplicate entry 'statvoo.com' for key 'domain' error A nice and simple way to resolve this is to use REPLACE INTO instead. This will look to see if the item already exists and will simply replace it. This is faster than doing a SELECT followed by an INSERT.
Read More
Read the bottom n lines of a file in Python
March 22, 2020
Using Operating System Commands in Python Use the Linux/Mac tail command to provide the data: line = subprocess.check_output(['tail', '-1', somefile.txt]) Creating a Python Only Script Read the whole file into memory and only print out the last line/s: with open('somefile.txt', 'r') as f: lines = f.read().splitlines() last_line = lines[-1] print(last_line)
Read More
How to Format a Number as a Currency in Javascript
March 21, 2020
There are quite a few ways to format a number as a currency value in Javascript. Doing it yourself The easiest of which is that of using the built-in toFixed() method. Often times you will either have a string, integer or floating-point number (/double) and will need to output a value that looks like a currency. So this: 12345.67120398 should become this: 12,345.67. Let’s take the following example: var yourBalance = 2489.
Read More
How to Change the Timezone on Ubuntu Server
March 20, 2020
If you’ve ever typed date into your Ubuntu Server and seen a different time or timezone appear than you expected, then it probably means that this tutorial is for you. Check current timezone Start by checking what data is returned using the following command: timedatectl In my case, I wanted to make sure my server’s time was in UTC, London. However, it was reported as being in Berlin. $ timedatectl Local time: Fri 2020-03-20 11:08:41 CET Universal time: Fri 2020-03-20 10:08:41 UTC RTC time: Fri 2020-03-20 10:08:42 Time zone: Europe/Berlin (CET, +0100) System clock synchronized: yes systemd-timesyncd.
Read More
How to make a Python script Pip-installable
March 19, 2020
As Python developers, we’ve all used pip to install applications, but speaking to other Python developers, it’s not always clear how to make your own application/script pip-installable. If you want to automatically publish your Python to PyPi, check out makepip automation tip Steps involved Create a python script, or application Add and configure a setup file Build your new Pip Package Locally Upload them both to the Python Package Index (PyPi) So let’s run through these 4 steps to get you going.
Read More
How to Host an AngularJS site on AWS S3
March 18, 2020
AngularJS is a Javascript Framework that allows you to create dynamic front-end web applications easily. I have traditionally packaged these applications through NodeJS, and Grunt (or Gulp) in particular. Once it needs to be hosted for the whole world to see, I always used to push the static folder up to an Apache2 or Nginx Linux web server. There’s really not a massive need for this though, as it’s easily possible to AngularJS applications completely serverless using a combination of AWS S3 and Cloudflare.
Read More
How to send emails using Python and AWS SES SMTP
March 17, 2020
Sending emails using Python and AWS’ SES service is really easy. They provide an SMTP server that you can authenticate against and send email programmatically from your python scripts. There is a wonderfully simple Python package called emails I like to use for this purpose. If you’re not running a Python Virtual Environment , then start by getting started here . Otherwise, continue reading! Getting AWS SES SMTP Setup In order to start sending emails using AWS SES, and the SMTP server in particular, you will need to:
Read More
Generate a random number between two numbers in JavaScript
March 16, 2020
If you need to generate a random number between two numbers in JavaScript, then you are in the right place! Here you will learn javascript random number generation. We can easily do this by using a combination of built-in Math functions. Javascript Random Number from Math.random() Let’s start by using Math.random() to generate a random number. Now we will take that and multiply it by max - min + 1.
Read More
Read the top n lines of a file in Python
March 14, 2020
Sometimes you may need to read the top n lines of a file using Python. We start by opening the file for reading and then using a list comprehension we iterate through the range of lines we want to return: N = 10 filename = "file.txt" with open(filename) as myfile: head = [next(myfile) for x in range(N)] print(head) Another way you can do this is by looping through each line individually:
Read More
How Fast is your Website?
March 13, 2020
I operate a bunch of different sites and have done for many years now. Some of them get quite a lot of traffic and require a high level of uptime. To monitor the uptime of these sites, I use various tools to alert me when a site is unreachable, when a specific resource is returning an unexpected status code, or if one of the database heavy pages starts taking a while to respond to requests.
Read More
How to Git Reset a Single File
March 12, 2020
It’s very easy to reset files that have not yet been committed to git. Reset a single file git reset <filename> You can also specify the filename as the path to the file, like so: git reset ./the/actual/relatvive/path/with/filename.ext This will checkout the file from HEAD. It is important to note that should you have a file that is the same name as a branch, you will need to rather run the following command:
Read More
Introducing Variables in Golang
March 11, 2020
Golang comes with a decent offering around variables that you can use to store, retrieve and manipulate information. A variable is defined with the var keyword followed by the name of the variable, the type and then the assignment itself. How to name a variable in Golang Variable names must: Start with a letter May contain letters, numbers or the underscore _ character. Variable names that start with numbers or special characters are not allowed.
Read More
Golang cannot convert (type string) to type int
March 10, 2020
Every language has it’s ways of converting data types. One of the most common data types to convert between is that of strings (string) and integers (int). If you’ve ever tried to do this in Golang, you would know that’s it isn’t all that simple at first. The easiest way to convert between String and Integers in Golang is as follows: String to Integer My go-to option to resolve this problem would be with the strconv module.
Read More
Learn Golang as a Python Developer
March 9, 2020
Learning Go or Golang as a Python developer, programmer or software engineer is easier than you think. While there are quite a lot of things to learn and get familiar with, there are many benefits and many common characteristics. Why learn Go as a Python developer I find Python to be a very powerful and useful programming language, having used it on a wide range of projects for an even wider range of tasks.
Read More
Remove Special Characters in a String using Bash
March 8, 2020
Programming languages provide the ability to remove special characters from a string quite easily. Sometimes you need to also do this from your command-line using Bash. Let’s say we have a bash variable called USER_EMAIL and we want to remove any periods, underscores, dashes and the @ symbol, how would we go about this? We could pipe our variable to a useful command called tr (which is the translate or delete characters tool) and strip these specifics before pushing the output back to a new bash variable.
Read More
Get the Amount of Days Between Two Dates in Python
March 7, 2020
Let’s say that you have two dates: "2019-01-29" "2019-06-30" How would you create a function that would return the number of days between these two dates? Introducing the Datetime Package Python comes with a built-in library called datetime. We start by importing the date module. from datetime import date With this date module, we have access to an object format of the date type. Writing our Function Next, we should write our function that takes in two dates and returns the number of days between them.
Read More
How to Always run Python 3 from Bash
March 6, 2020
Given a directory that contains: | |- app.py |- requirements.txt |- ... |- <- other-files -> |- ... We can create a runme.sh file to always make sure we are running python 3. Create a shell script Create a file called runme.sh and put the following code in: python -c 'import sys; exit(1) if sys.version_info.major < 3 else exit(0)' if [[ $? == 0 ]]; then [ ! -d "venv" ] && virtualenv -p python venv .
Read More
How to Run the Kubernetes Dashboard Locally
March 5, 2020
Kubernetes comes with a pretty nice dashboard to view clusters, worker groups, nodes and pods. As well as a ton of other useful things. This tutorial presumes that you already have a Kubernetes cluster setup and running and have access to it through kubectl in your command-line. Steps to run Kubernetes Dashboard Start by downloading the metrics-server and applying it to your kubectl config. DOWNLOAD_URL=$(curl -Ls "https://api.github.com/repos/kubernetes-sigs/metrics-server/releases/latest" | jq -r .
Read More
How to tell if a year is a Leap Year in Python
March 4, 2020
Given that we are in a leap year this year (2020), it would be nice to know how to programmatically calculate this. Luckily, this is a repeatable pattern that we can write some code for. So what is a leap year? A leap year is a year that has 29 days in the month of February. Astronomical years have a quarter of a day more than our calendar years that we follow, so to make sure this matches up continually, our calendar introduces an additional day every 4 years.
Read More
How to Reverse a Linked List in Python
March 3, 2020
It’s important to know about data types and one that comes up fairly regularly is that of Linked Lists. Let’s write the following base code to create a Linked List. # Defintion of a single Node class Node: # takes input data and next node def __init__(self, data = None, next=None): self.data = data self.next = next # Definition of a Linked List class LinkedList: def __init__(self): self.head = None # Insert a node into our Linked List def insert(self, data): newNode = Node(data) if(self.
Read More
The Docker Quickstart Guide for Developers
March 2, 2020
This Docker Quickstart Guide for Developers aims to get developers familiar with Docker as quickly as possible. Providing you with the knowledge to be able to use Docker in your personal and professional projects. What is Docker? Docker is a tool written in Golang that provides the ability to run applications within things called containers. It removes the age-old “works on my machine” problems that plagued many software developers and testers lives.
Read More
How to Follow Redirects with cURL for CLI or PHP
March 1, 2020
Let’s take a really common example. Say we want to follow redirects with cURL for google.com. It is common to curl follow redirect a URL. Follow Redirects with cURL in the CommandLine If you navigate directly to google in the command-line using curl, you will be taken to a 301 redirect URL. curl google.com #<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> #<TITLE>301 Moved</TITLE></HEAD><BODY> #<H1>301 Moved</H1> #The document has moved #<A HREF="http://www.google.com/">here</A>. #</BODY></HTML> This makes sure that you follow the proper canonical URL as set by the particular website in question.
Read More
How to tell if a String contains a Substring in Javascript
February 29, 2020
Javascript comes with some pretty good support for determining if a string contains a substring. There is the newer includes function which was introduced in ES2015 which allows you to tell if a string contains a substring. This function returns a boolean value of true or false. 'our example string'.includes('example') // returns true Alternatively, if you need to either: Have support for older versions of Javascript Need to not only know if a string contains a substring, but also it’s position within the string.
Read More
How to package a Python app (pip) for PyPi
February 28, 2020
In this tutorial, we will create a Python application that can be installed directly from pip that will show the 10 latest blog posts from this website (the one you are reading this on!). If you just want to avoid all of this hard work and publish a python script directly, you can always make use of my makepip package right from the command line. Learn more about Makepip here. Getting started Make sure you have registered at Pypy and have an account, we will need this to upload our package once we’re done.
Read More
MakePip – Automatically Publish Python to PyPi
February 27, 2020
Automatically Publish your Python applications to the Python Package Index (PyPI) for use through Pip. If you have ever needed to publish your python scripts to Pypi, you will know of all the work required to do so. Makepip takes all the effort away by providing a command-line tool to automatically do all the heavy lifting for you. How to install If you are running Python3, then all you need to do is pip install makepip If you are running Python2, then you will need to run Python3, you can do this by adding a virtual environment.
Read More
How to find the longest Palindrome in a String using Python
February 27, 2020
This occasionally comes up during coding interviews and is actually quite a decent way to test someone’s aptitude of moving back and forth on a string to determine if and where palindromes exist. If we simply said: “return a boolean if a string is a palindrome”, then threw a couple tests cases at the function, we would expect the developer to loop through the first half of a string while comparing the second half, if it matched all the way to the central pivot, then “yes, the string is a palindrome”.
Read More
How to write Anonymous Functions in Javascript
February 26, 2020
There is a lot of power in Javascript syntax. One of those powerful things is that of Javascript Anonymous Functions. But what is an Anonymous Function in Javascript? It is a function that does not have a name or one that has been hidden out of scope around its creation. A common use of a Javascript Anonymous Function is to guarantee that the same variable names or function names are not already used within the same document.
Read More
How to use Docker to test any Linux distribution locally
February 25, 2020
I often need to test a specific Linux binary or make sure something works as expected from yum install or apt install. To do this, it’s common to have a virtual machine lying around, or even a VPS that you can just quickly log into. Things are a bit easier and quicker if you use Docker. Let’s run two tests, the first one to get going with Ubuntu, and the second to get going with Centos.
Read More
How to get the Maximum Depth of a Binary Tree in Python
February 24, 2020
Let’s say that you have a binary tree and we needed to know it’s maximum depth. Binary tree input data [3,9,20,null,null,15,7] could be visualised as follows: 3 / \ 9 20 / \ 15 7 In the above example, the depth would be 3. As there are 3 levels. How would we write some Python code to work this out? As usual, a TreeNode is defined as follows: class TreeNode: def __init__(self, x): self.
Read More
What is Fizz Buzz?
February 23, 2020
Fizz buzz is a common programming interview question. The problem statement usually reads something like this: Write a short program that prints each number from 1 to 100 on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number. Hackerrank.
Read More
How to Deploy a Helm “Hello World” app onto Kubernetes
February 22, 2020
We will create a simple Hello World static HTTP Service using Helm, package it and release it to an AWS EKS Cluster. This tutorial expects you to have kubectl as well as helm installed on your computer. Build our Docker image Create a file called Dockerfile and place the below into it: FROM busybox ADD index.html /www/index.html EXPOSE 8008 CMD httpd -p 8008 -h /www; tail -f /dev/null Now we need to create our index.
Read More
How to write a Quicksort Algorithm in Python
February 21, 2020
While there are libraries available for all programming languages that offer abilities to sort list, arrays and collections, it is important to know how this is achieved. Learning how to write a quicksort algorithm yourself gives the ability to better understand the programming language of your choice and how to optimise code where possible. Today we will explore writing a quicksort algorithm in the Python programming language. Let’s start by defining a list of integers that are clearly not in order:
Read More
How to Reverse a String or List using Python
February 20, 2020
Python comes with the power of slicing. Let’s try it with a String: >>> example1 = 'hello world' >>> example1[::-1] 'dlrow olleh' Now let’s try the same with a List: >>> example2 = ['h','e','l','l','o',' ','w','o','r','l','d'] >>> example2[::-1] ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h'] As we can see by passing in the third argument to our slice of -1, we are able to reverse the return value.
Read More
How to get the IP address in Python
February 19, 2020
Python exposes a socket library that allows us to perform networking tasks such as getting the IP Address as well as getting the Hostname of our system. import socket try: host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print(f"Hostname: {host_name}") print(f"IP : {host_ip}") except: print("Could not get the IP Address or Hostname") The above code imports the socket library and then runs a safe block of code. We need to first get the hostname and then use that to get the IP Address.
Read More
How to Reverse a Binary Tree in Python
February 18, 2020
Reversing a Binary Tree is a common programming interview question. By learning how to Reverse a Binary Tree in Python, you are working towards fundamental data structure algorithms commonly found in Computer Science degrees and across the industry. If we take a look at the following Data Tree Image, we will notice a few common points. Firstly, a binary tree simply means a tree that contains between 1 and 2 child nodes.
Read More
[Solved] Unable to Detach AWS Network Interface
February 17, 2020
You do not have permission to access the specified resource. If you are seeing this error appears up when trying to delete or detach a Network Interface within AWS, then you need to read what the description column says, find that item and then delete that first. We can see in this instance, we need to first delete an ELB starting with ID a4e6efd6. Head over to the Load Balancers tab and search for that ELB:
Read More
How to delete a file in Python
February 16, 2020
A quick solution in Python import os os.remove("filename.txt") The above code will delete a file in Python, it will not however delete a directory, or a directory containing files. For this we will need to explore a bit more.. Check file exists before deleting First check if the file exists before deleting it: import os if os.path.exists("filename.txt"): os.remove("filename.txt") else: print("The file doesn't exist") Delete a directory/folder Sometimes you may want to delete an entire folder as well:
Read More
How to safely parse JSON in Javascript
February 15, 2020
JSON stands for Javascript Object Notation and has become wildly popular to transport and store data between application, databases and more. However, it is not always obvious that a piece of data your application is trying to use may be of type JSON, or be correctly sanitised. Let’s take a simple Javascript function as follows: function getNameFromJSONString(jsonString) { // Dangerous! json = JSON.parse(jsonString); // Dangerous again! return json.name; } What the above function does is take in a string which it believes is a stringified/serialised JSON (perhaps stored in a database), parse it back to a Javascript Object and then return an attribute called name.
Read More
Check if an HTML Checkbox is checked using Javascript
February 14, 2020
While processing forms in web development, it’s a common requirement to be able to tell if a checkbox has been checked or not. It’s not immediately obvious though. Let’s dispell this and provide some ways to check if a checkbox is checked using Javascript. First, we need an HTML checkbox to play around with. <input type="checkbox" class="myCheckbox" /> Using Javascript Using regular Javascript, we can tell if it is checked by using the following Javascript:
Read More
How to Push Docker Images to AWS ECR
February 13, 2020
Docker images are usually stored on Docker Hub, but AWS’s Elastic Container Registry can also be used. It’s a great solution and this post teaches you how to push Docker images to AWS’ Elastic Container Registry (ECR). Create a Repository Let’s start by using the aws-cli to create a repository. aws ecr create-repository --repository-name myname This command successfully creates a repository and outputs the following JSON: { "repository": { "repositoryArn": "arn:aws:ecr:eu-west-1:098765432123:repository/myname", "registryId": "098765432123", "repositoryName": "myname", "repositoryUri": "098765432123.
Read More
How to monitor Network Traffic on Linux
February 12, 2020
There is a fantastic tool to see and monitor Bandwidth and Network Traffic on Linux. It’s called bmon and it works out of the box. How to Setup and Use On Ubuntu apt-get install bmon, or in newer versions, you can also just say apt install bmon. On Centos yum install bmon. Once you have it installed, you can start the monitor by running bmon from the command-line. You will be presented with multiple network interfaces (NICs).
Read More
How to Merge Javascript Objects
February 11, 2020
A Javascript Object – now just called JSON – is a collection of values and properties stored as a map. How would you merge two or more Javascript objects together thought? In ECMAScript 2018, the Object Spread operator will do the trick for you in no time, let’s try it out. var jso1 = { "name": "John", "colour": "green", }; var jso2 = { "name": "Andrew", "symbol": "arrow", }; var merged = {.
Read More
When to use Pip3 instead of Pip in Python
February 10, 2020
If you have multiple versions of Python installed on a system, such as both Python 2.7 and Python 3.6+. Then pip will often refer to the Python2 bin, while pip3 will point to the Python3 bin. You can easily tell what your own setup is by running the following commands in a terminal window / command-line. $ which pip $ which pip3 /usr/local/bin/pip3 It is also useful to know what version of Python you have on your system and where it is, as Pip is always coupled with it.
Read More
How to use Screen on Linux
February 9, 2020
Screen on Linux is a popular command-line program that lets you multiplex between interactive shells. What that means is, you can use screen to save and restore running of commands. Screen in action The best way to test this out is to SSH into a server. sh user@150.xx.xxx.xx user@server:~# At this stage, you can execute man screen to learn all the commands available to you. You can issue a screen -list to show all screen sessions that may already be open.
Read More
Transfer a domain from Namecheap
February 8, 2020
Namecheap is a pretty good registrar. As its name says, yes, it is usually pretty cheap. I would also like to point out that I personally have nothing bad to say about Namecheap and that their service is overall pretty positive. But as with most things, there occasionally comes time to make a change. This change happens to be to transfer a domain hosted at Namecheap. Recently I have been moving most of my domains to Cloudflare, who don’t currently offer registrations but do offer to take the domains once registered.
Read More
How to Package a Python App using Nuitka
February 7, 2020
Learn how to package a Python app in this tutorial. For the most part, once you’ve written your Python code, you simply deploy it to a server, install the environment, grab the dependencies and you’re done. However, there are times when you may want to provide your app to someone else and don’t want the hassle of getting them setup with all the training around making sure they have Python on their machine and can run your app.
Read More
Introduction to NPM
February 6, 2020
What is NPM? NPM stands for Node Package Manager, and is the default way to extend your Node applications. There are an absolute ton of packages available to install and use immediately, making NPM wildly popular for software developers. What is Node? Node.js, or often simply just Node, is a Javascript runtime environment that allows Javascript code to be executed outside of the web browser. It first came about in 2009 when the creator (Ryan Dahl) took Google’s V8 Javascript Engine which powers its Chrome browser, and repurposed it.
Read More
How to create a Symbolic Link on Linux / Mac
February 5, 2020
A symbolic link – or often just sym-link – is a pointer or shortcut to where the actual file lives on a filesystem. What does it take to create a symbolic link? The ln command actually describes it pretty well: "Make links between files" The manual Why would I need a Symbolic Link? When should you create a symbolic link is a question I am often asked. While creating a symbolic link can be really useful, it’s not often understood when or why we even do this.
Read More
Non-interactive git clone (ssh fingerprint prompt)
February 4, 2020
If you have ever been in the annoying situation where you had to run git clone from a server that you did not have interactive access to, such as a continuous integration/deployment box or other. Then you may have run into the dreaded Are you sure you want to continue connecting (yes/no)? dialogue. Usually, at this stage, you would be stuck, as you need a way to tell it yes, but there’s no input!
Read More
When your Python code is much faster with PyPy
February 4, 2020
Python is a very powerful language, there are so many libraries available for it. However, many developers will complain about its speed by comparison to certain other languages, for example, C or C++. This is because Python is an interpreted language by design, as opposed to being compiled. Meaning that each time it executes, the instructions need to be converted right there on the spot, making for slower overall execution times.
Read More
What it takes to be a Platform Engineer in 2020
February 3, 2020
Platform Engineering is something that grew out of a mix of what software developers and sysadmins had been doing for years. The only real difference is that most software these days either lives somewhere in some cloud or various services that support it do. Meaning that someone needs to design it, scale it and support it. This is not traditionally within the scope of a software engineer’s day job and requires a range of specialisms oftentimes not found with a developer’s direct focus.
Read More
Introduction to PIP – Python Package Manager
February 2, 2020
Python comes with a fully equipped package manager called PIP – which stands for the Python Package Manager. PIP gives your python applications access to thousands of popular libraries, packages or modules for free. What does PIP mean? PIP is actually a recursive acronym which stands for: PIP Installs Python PIP Installs Packages Before Continuing As usual, it is recommended to do everything in a Python Virtual Environment . Making sure that you are running Python3 is also important, as Python2 has reached End of Life, and this is a welcome thing!
Read More
How to build a website quickly using PHP
February 1, 2020
PHP is a powerful scripting language created for the web. It has come a long way since it’s initial inception in 1994. It was originally created to build websites quickly and easily and has become a lot more than that. While many developers and companies use PHP along with extensive and oftentimes heavy frameworks, there is no reason that you have to do that; you can build websites quickly and very easily by making use of many standard PHP functions.
Read More
How to replace all occurrences of a string in Javascript
January 31, 2020
I have pretty much resigned myself to the fact that in Javascript, there are really only two ways to do a proper search and replace. Firstly, we need a base string to start manipulating, so let’s create our test subject: var ourString = "This is a great string and we love it"; So now the options are as follows, replace, regular expression replace and split/join. Javascript Replace ourString.replace(" ", "-") "This-is a great string and we love it" As we can see with this method, it only replaces single occurrences in the string, which may be what you are trying to achieve, but it certainly wasn’t for this case!
Read More
How to exit Vim
January 30, 2020
If only I had a dollar for every time I saw someone sitting at their computer, trying for the life of them to exit vim To save and exit; press : followed by x and then hit Enter to save and exit the file in vim. TLDR; Vim or sometimes just vi is a command-line (cli) application that lets you edit documents. It’s massively popular and my personal go-to editor when I’m on a Linux box.
Read More
How to Setup and Use the Python Virtual Environment
January 28, 2020
Python is a fantastic language that continues to help so many businesses and individuals. It offers readable syntax to get started, yet extensive amounts of control and flexibility to move into the more advanced areas of software engineering. Python the number one choice for many because it is packed with the power of unparalleled libraries, it recommended to run them through a python virtual environment . Conventionally, running a python script from the terminal is as simple as calling it and passing in the script needed to be executed.
Read More
Introducing the Hetzner Cloud
January 27, 2020
I could honestly not tell you how many hosting providers I’ve tried over the past 15 years. Probably more than 30, 40… Easily! Today I would like to introduce you to the Hetzner Cloud. No, I do not work for Hetzner, or have any affiliation to them whatsoever, this is purely a sharing exercise as I have noticed that when I speak of them in my professional capacity, most colleagues don’t know about them.
Read More
Multiprocessing in Python3
January 14, 2020
import multiprocessing def runner(k): print(k) processes = [] for i in range(10): p = multiprocessing.Process(target=runner, args=(i,)) processes.append(p) p.start() for j in range(len(processes)): processes[j].join() Now that you have the code; let’s explain: Import the multiprocessing library import multiprocessing Define the function that will run each time a process is executed def runner(k): print(k) Keep track of all the processes processes = [] How many processes do you want to run? for i in range(10): Send some arguments to the running function
Read More
How to Install MongoDB on Mac
January 4, 2020
You can use Homebrew to install MongoDB on a Mac. For ages you were able to simply do: brew install mongodb, but more recently, that has stopped working as it was removed from homebrew-core. Now, you need to do it as follows: brew services stop mongodb brew uninstall mongodb brew tap mongodb/brew brew install mongodb-community brew services start mongodb-community You can read more about it here if you’d like.
Read More
The Best Note Taking Apps
December 20, 2019
We’re all using a Note Taking App these days, they’re incredibly useful and come jam packed with loads of features. But which ones shine out from the rest and which should you use in 2019? Among the many tens to hundreds of possible candidates, I have chosen the seemingly obvious top 5 to explore in this post. These were initially chosen from my own experience having used many over the past few years to find the ultimate single Note Taking app to conquer all others.
Read More
How to Delete large amount of files in directory
December 9, 2019
So you have clearly got a very large amount of files! If you issue the conventional rm -rf * within the directory, you will get an error -bash: /bin/rm: Argument list too long. You can still easily remove these files, just make sure to use the find command instead! Solution: find . -type f -delete
Read More
How to Merge multiple files, removing duplicate values
November 25, 2019
If you have multiple files and you want to remove duplicate values from, while creating a single file. File1 (one.txt): 123 123 234 345 File2 (two.txt): 123 678 567 890 As you can see, the two files contain some duplicates. You can easily remove these using the following command: sort -u one.txt two.txt This will output: 123 234 345 567 678 890 You can as easily pipe this into a third file as follows:
Read More
Unable to delete an AWS Internet Gateway
November 22, 2019
So you need to delete an AWS Internet Gateway, sounds good. You navigate to the VPC (Virtual Private Cloud) dashboard and go to Internet Gateways. At this stage you select “Actions” and choose the “Detach VPC” option. In a perfect world, this would return a “success” and the IG would be deleted. But sometimes this isn’t the case and you have to do a little more. In this instance, you need to figure out what other services (network resources) are using this IG.
Read More
How Distributed Applications Work
July 29, 2019
Distributed Applications come in a wide range of sizes, usages and resource availabilities. What is a Distributed Application? A perfect example of a Distributed Application is a multiple node database application such as Cassandra, HBase or Serengeti . These applications make use of multiple instances of themselves to be able to address vast amounts of data are stored across many networked computer systems. This provides the ability for fault-tolerant issues to be resolved immediately as well as for massive amounts of data to be stored without reaching individual machine resource constraints.
Read More
Why Artificial Intelligence (AI) won’t necessarily take your job
July 9, 2019
Artificial Intelligence, or simply AI these days, is when computers are able to perform tasks that humans would otherwise do. While this is incredibly exciting for many, it can be absolutely terrifying for others. Specifically those in roles that AI tends to current target. After all, losing your bread and butter to a computer just seems wrong, but the reality of it is that some roles are already being swapped out for the lesser emotional, more rapidly replicable being of the twenty first century.
Read More
The difference between ‘git fetch’ and ‘git pull’
July 8, 2019
Git Pull vs Fetch Many of us take a look at git fetch and git pull and believe them to do the exact same thing! This is just not true. So what exactly is the difference and when should you use one over the other? The Difference Between Pull and Fetch Git Fetch <p class="schema-faq-answer"> The <code>fetch</code> command goes to the remote repository and gets the latest information about the branch, commits, references (tags) and all the file objects.
Read More
7 Ways to Make Money Online from Home
July 8, 2019
1. Create a website / blog There are numerous ways to make money when you create a website or blog. It’s really cheap and easy to do these days as well, with so many available options, some are even free. But how do you monetise your new online presence once you have created something? There are a few obvious ways, which include: Sell things on your website Advertising on your website These are probably the most common ways to make money online from home for almost free.
Read More
Keep that mouse moving!
June 2, 2019
Ever needed to keep your computer from going IDLE? Now it’s really simple using KTMM; It comes in 2 flavours that you can simply clone and run: Python application The origin Python version of KTMM Java application A version of KTMM written in Java Go application A version of KTMM written in Go Either way, just clone the git repo, build the application and run it!
Read More
Serengeti – The Autonomous Distributed Database
June 2, 2019
What is Serengeti? Serengeti is an Autonomous Distributed Database, and proves the theory of a distributed database that is truly autonomous, requires no custom configuration or human intervention. How does it work? Just run it on a networked node and leave it to operate at full fault tolerance and usability. Serengeti discovers other instances of itself running on the same network and immediately replicates to them. Where can I get it?
Read More
Run Javascript – Chrome Extension Help
October 10, 2018
Run Javascript is a Chrome Extension that allows you to run custom Javascript each time you visit a website. It is particularly useful to web developers and people who like to tamper with websites they frequent by injecting additional javascript to manipulate the DOM. If you don’t always have it, you can get it here: https://chrome.google.com/webstore/detail/run-javascript/lmilalhkkdhfieeienjbiicclobibjao Using “Run Javascript” You are initially presented with a window if you click the Run Javascript icon.
Read More
Investigation of insider attacks with computer forensics
October 7, 2018
Cyber-attacks do not always originate from outside of the target organisation. Veritably around twenty-five percent of all data breaches occur from the inside, from employees or trusted individuals within the organisation (TechBeacon, 2018). Employees that have access to internal records, intellectual property or intramural trade secrets need to be watched as closely as any external party or connection should be. Why employees are a risk Employees can trigger internal cyber-attacks, steal intellectual property or even publicly release internal affairs and private information for a number of reasons, which could include:
Read More
Squid Proxy behind a Load Balancer on AWS
October 4, 2018
Squid is a proxy software that allows a computer without internet access to proxy through another computer that does have internet access. Squid is very easy to get setup and the computer that needs internet just needs to specify environment variables called HTTP_PROXY and HTTPS_PROXY which have the value of http://squid.ip.address:3128/ The complication comes in where you need a Squid instance (sitting on an EC2) to sit behind an AWS load balancer.
Read More
How to install a Ruby Gem without Root on a Mac
October 1, 2018
Gems are little packaged Ruby applications that allow you to extend the ecosystem and reuse countless online sources. If you don’t have Root on your Mac (work at a large company?) but you still want to use a Gem or two, then you will usually get the following error when attempting to install: ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory. This is incredible annoying, but something you can’t avoid.
Read More
The dark truth behind Advertising on the internet
October 1, 2018
The story Steve has a website which sells carpets in London. Steve’s carpet business has been doing really well and Peter has recently noticed just how well. Peter decides to get into the same business and decides to build a website too. Peter’s website is soon complete and he has a little stock to get started.. but nobody visits his website. So he decides to take out some online ads.
Read More
International hosting governments and forensic email cases
September 30, 2018
Cyber forensics is hard, but it is even harder when servers are hosted in different geographical locations and an investigation needs all localities to cooperate and hand over every part of the data consistently. This is primarily due to privacy laws that each region may apply or carry out in differing ways. Multiple regions Even if a compilation can source multiple regions data; dealing with international governments could mean prolonged wait times, unfamiliar processes to follow or even citizens of those regions withholding data due to privacy rights within that region.
Read More
When to give up on your startup/product
September 28, 2018
One of the hardest things you can do after trying to get a startup or product off the ground is to simply give up and call it a day. After all, you’ve put an awful lot of blood, sweat and tears into it, and you have probably done this for months, if not even years! As a life-long software developer, I’ve always had side projects going, some from small ideas to others that I have truly invested a lot of time and money into.
Read More
Just SSH to my Jump Box!
September 26, 2018
I am a professional software engineer and do an absolute ton of devops work as well. I’ve actually never been hired into devops roles as I always go in as a programmer, but I also always end up doing devops as well for various reasons. What tasks? These usually include things like: I like to get my code running on infrastructure as soon as possible for Proof of Concepts (POCs) and the like.
Read More
Counting in Python using a list
September 25, 2018
So before we begin, let me just tell you that this is a pretty useless thing to do.. But I was playing around with it while waiting for a C++ project to finish compiling, so why not! The code (click here for the Gist): magic = 0x616f-0x414f numbers = [ (magic/0x186A0), (magic/0x3E8/8), (magic/0x3E8/4), (magic/0o1534-7), (magic/0x3E8/2), (magic/0o2534-1), (magic/0o2544), (magic/0o075/19), (magic/0o064/19), (magic/0o1654) ] i = c = numbers[0] while True: print('%d%d' % (c, round(numbers[int(i)]))) i += 1 if i>len(numbers)-1: i = 0 c += 1 If you ran it, it would look like this!
Read More
Show the desktop’s image name on a Mac
September 23, 2018
Sometimes you just need to know where that image shown on your desktop is stored! For this, there is a simple but effective line of text you can pop into your terminal. defaults write com.apple.dock desktop-picture-show-debug-text -bool TRUE;killall Dock This will render the image’s location pathname and image name over the desktop background image. When you’re complete and you want to disable that over render of the image name, then simply type:
Read More
Network Forensics Concerns around GDPR
September 23, 2018
In Cyber Forensic there are a vast array of tools that are used throughout most investigations, however, not all jurisdictions allow or even agree to the usage of some of them. This is mainly due to each specific geographical region’s view on their citizens right to privacy. Some of the tools and tactics to collecting evidence are therefore questionable and raise specific concerns in this matter. During the evidence collection process there are many things to consider when it comes to data being transferred over a network.
Read More
A look into Future Developments in Operating Systems from a Cyber Forensics Investigator
September 16, 2018
Operating systems (OS) really have come a long way since the very first one was created by General Motors in 1956 (WIHT, 2017) to run on an IBM mainframe. Since then, there have been countless attempts at popularising OS?s and a few companies have truly stood the test of time. Among these the Windows OS, MacOS and Linux OS are the most notable with the highest market share and global penetration.
Read More
Comparing Interface Types in Cyber Forensics
September 2, 2018
In digital and cyber forensics, there are three main types of categories when it comes to forensic tooling. They can be considered as: Graphical User Interfaces (GUI?s) Interactive Text-based Consoles Command-line interfaces (CLI?s) Of these, the main competitors are really just GUIs and CLIs as they certainly differentiate most from one another. They both have their strengths and reasons to be used, of which neither should be discounted. Many people like to use the GUI version of an application, as it allows them to focus on the task at hand that may extend between a range of activities and doesn?
Read More
Cyber Forensic Investigative Reports
August 26, 2018
Investigations are not proven in a jurisdiction until a detailed forensic report is created and presented to a judge or jury who can take it to the next level. Presenting digital evidence should be laid out that it is not overly technical in order for all parties to fully understand and interpret in its arrangement, yet still goes into absolute detail to express all the intricacies of an investigation and its extrication.
Read More
Altering Computer Evidence
August 19, 2018
Ever since it has been possible for humans to operate computers, some have used it to perform criminal activities. Part of a cybercriminal’s gameplay is to cover up or otherwise alter digital evidence in one form or another. There are many reasons why cybercriminals may try to alter computer evidence; these could be any of the following: Cover their traces The most obvious reason is to simply cover up that the fact that an attacker was around and where the attack came from.
Read More
Connection broken by ‘SSLError(SSLError(1, ‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)’
July 26, 2018
This happens when your machine does not have the correct certificate bundle to access the Pypi repository, or you are behind a corporate proxy that just loves to block everything! An easy way to get around this is to edit (or create) a local pip.conf file under your home directory: ~/.pip/pip.conf Put the following in: [global] index-url = http://mirrors.aliyun.com/pypi/simple/ trusted-host = mirrors.aliyun.com As you can see, we have changed the download location to a mirror that doesn’t use HTTPS, so there will be no certificate issues.
Read More
Can’t pull a Git branch because of merge conflicts?
June 27, 2018
Sometimes you need to pull a remote branch and want to accept all their commits (and history) and override your own repository. It’s quite simple if you do a pull, don’t care about unrelated histories and accept all their code when there’s a conflict. git pull upstream master --allow-unrelated-histories -s recursive -X theirs Then simply push to your own remote and you’re done!
Read More
Software development processes
May 13, 2018
Introduction to Software Development Processes Gabry defines the Software Development Methodology to be a set of related activities that lead to the production of the software (2017). While this is the simplest concept of the processes, there are many formalised industry best practises in operation today; some of these include Rational Unified Process (RUP), OPEN, eXtreme Programming, Scrum, RWSP, DSDM and more. A****?software development scenario**** Though I have worked under a range of these processes, I have found the Scrum methodology to be the best performing in most workplaces.
Read More
Approaches to software reuse
May 13, 2018
Introduction to Software Reuse Software reuse is the process of creating software from antecedent and extant components. There are a range of approaches that can be taken when following a reuse pattern, these can usually be grouped into one of the following abstractions: Class Libraries Reusable Components Application Frameworks Patterns / Service Oriented Architecture (SOA) There are many benefits in taking up software reuse (SelectBS, n.d.). These include increased software productivity, shorter development times, improved interoperability, recuded costs and usually higher output quality to name a few.
Read More
Get the output of an application logged in the terminal
April 16, 2018
Just a quick note: You are probably looking for a Linux command called `dtrace`. If you’re on a mac then you are probably looking for `dtruss`.
Read More
Agile as a Software Development Process
March 24, 2018
Waterfall and Agile are by far the most commonly used software development processes, however, within them, there are many different styles of software development used in the management of software development projects. While each has their own advantages and disadvantages, we will focus on Agile as it has rapidly grown in popularity over the past few years and is widely accepted throughout the software development discipline and across a wide range of industries of all sizes.
Read More
Big Data Security and Privacy Issues
March 2, 2018
Big Data shares what is commonly termed the V properties or characteristics such as Velocity, Volume and Variety which are amongst the most typical or frequently repeated. Taking into account security issues and privacy implications with such large datasets is a challenging ordeal that needs a repeatable framework to cover all areas. Volume is with little to no doubt the most highly targeted characteristic as the expression Big Data fundamentally factors a voluminous amount of information or data that needs to be processed (McCafferty, 2013).
Read More
How to delete/revert a Git commit
March 2, 2018
You’ve just pushed something to a Git repository and you immediately regret it! Run git log to see what the commit id was: git log Take the first 7 characters of the commit SHA id and do the following: git revert <commit_id> git push --force But if you’re like me and your problem was because of a merge conflict that you tried to resolve and clearly failed at, but still had the balls to push to the repo before wishing you hadn’t; you can still recover this terrible moment in your life by undoing the merge request itself.
Read More
[Solved] Pip: There was a problem confirming the ssl certificate
February 26, 2018
If you ever get the following error when trying to install a Pip module under Python: Could not fetch URL https://pypi.python.org/simple/****/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping Then an easy way to get around it is by adding the trusted-host flag to your commandline argument as follows: --trusted-host pypi.python.org So your final command may look something like this: pip install some_module --trusted-host pypi.
Read More
How to Learn Python Programming Quickly
February 22, 2018
So you want to learn to program in Python and you don’t have a lot of time? That’s okay! Once you grasp some of the key concepts and ways of thinking, it will all come to you. So let’s get going now, shall we? What is Python? Python is a high-level, interpreted, object-oriented programming language with dynamic semantics used for general-purpose programming. It was created by Guido van Rossum and first released in 1991.
Read More
NoSQL Pandas Dataframes
February 16, 2018
Pandas Dataframes are simply a table with some rows (McKinney, 2015) and many additional features built right in to make data scientists lives much easier. What are NoSQL Pandas dataframes? Pandas is an open source Python library that provides high performance yet easy to use data structures and data analysis tools (Pandas, 2018). Dataframes are two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes. They can be thought of as dictionary type containers for Series objects (PandasDocs, 2018); they are also the primary data structure used in Pandas.
Read More
Relational (SQL) vs NoSQL Database Models
February 4, 2018
The Relational (SQL) database has been a central piece to businesses since the 1970s when they first had their claim to fame. Experts say that the world?s data is doubling every two years (Gajani, 2017) and this is simply something that traditional relational databases cannot manage with their architectural inner workings and scalability concerns. Carlo Strozzi first used the term NoSQL in 1998 to name his then lightweight database to show distinctions between it?
Read More
Netflix Hadoop Big Data Marketing Use Case
January 28, 2018
Netflix is a video streaming service that has a wealth of information about their user base likes, dislikes, general consumer habits, retention lengths and much more. Netflix uses their big data to commission original programming content that it knows will succeed and be accepted in relevant published markets (O?Neill, 2016). They perform various A/B tests to determine which variant of similar things perform higher, for example, when showing cover images for series or movies, they will at random show alternative images to determine which proves more reactive from their user base.
Read More
Using Hadoop to manage Dark Data
January 19, 2018
Dark Data is the biggest piece of the pie (Datumize , n.d.) when it comes to Big Data and what lies beneath huge datasets of collected information. IBM has stated in a report that over 80 percent of all data is dark and unstructured, meaning that it is simply too much data to process, analyse or unlock valuable information from. This data is termed Dark Data and is mostly unstructured and oftentimes missing or incomplete, which leaves a lot of potential for solutions to be built around high volume analytics and processing.
Read More
An Introduction to Client-Server Systems
December 10, 2017
A client-server architecture/system is one where the server maintains all models of the backend datasets and business logic around taking and providing information to fulfill a service request from a client which in turn shows the representation thereof. The client/server model has quickly grown in popularity throughout the 1990s and today serves as a favoured choice for most organisations? (Subramanian, Lacity, 1997) operations. There is a statement which asserts that ?
Read More
When to use FLUSH PRIVILEGES in MySQL
December 6, 2017
So if you’ve ever created users and given them specific permissions from with SQL or the commandline, you will be familiar with a statement called FLUSH PRIVILEGES. It is said that if you create a new user, or alter than user, you should run FLUSH PRIVILEGES in order for the MySQL Engine’s Session to take the change into immediate effect. But what about if you GRANTed or REVOKEd a permission? Do you still need to use it?
Read More
MySQL Community Server MSI Installer Hangs on Windows 10
December 6, 2017
I was trying to install MySQL Community Server for Windows 10 using the standard .MSI installer provded from the MySQL website and the installer just hung, saying that there was 3 seconds remaining. About half an hour later, it still said “3 seconds remaining”. It turned out that you have to run cmd (commandline) as Administrator: Press Windows Key (Super), type “cmd”, right click on “Command Prompt” and select “Run as administrator”.
Read More
Android device supports x86, but APK only supports Arm
December 4, 2017
I get this error quite a lot when trying to deploy an Android APK to an emulator. “Device supports x86_64, x86, but APK only support , all, armeabi-v7a” The good thing is that it is actually a very easy thing to fix. While doing development you can simply change the Build Variant target. How do you do that? Click “View” -> “Tool Window” -> “Build Variants” Notice that ARM is currently selected and most of the time you will want x86 to be the build target if you are deploying to a emulator.
Read More
Weird Dialog Boxes
November 30, 2017
Adobe Setup setup? Got this one while using Chrome, it complains about Safari? What a load of bullshit! Really? Very handy tips screen! ERROR: NO ERROR!
Read More
A bit on SQL Standards
November 12, 2017
SQL (Structured Query Language) for relational databases was maintained and standardised by the American National Standards Institute (ANSI) and the International Organisation for Standardisation (ISO) which is affiliated with the International Electrotechnical Commission (IEC). When a new SQL standard is published by these organisations it is outlined on the ISO website and available for everyone to both reference and use as required. The current version used in most production instances is commonly ISO/IEC 9075-11:2011; however, in December of 2016 a new version was published and is described under ISO/IEC 9075-11:2016 which can be found here: https://www.
Read More
A Brief Talk on Databases
October 29, 2017
Databases have been around since ancient times, when elaborate database systems were deployed by governments, hospitals and organisations to keep track of vast amounts of information; but only until around the 1960s did computerised databases start to take shape and become cost effective for private organisations to start using (Quickbase, n.d.). I have used countless databases over my career to reliably store and retrieve many sizes of information, from a small collection of less than ten items of data to terabytes worth of hundred of billions of data points spread across clusters of machines around the world.
Read More
Cloud Computing – The Refute
September 24, 2017
Cloud is great, but when you know what you are doing, think about alternatives (Blippex, 2013). What is Cloud? “The cloud” is a term given to pay as you go – or pay monthly – off premises computing services that provide either hosting or storage to it?s user base. These services are created, maintained and wholly operated by a cloud computing provider. Instead of purchasing and managing your own infrastructure, many opt for a cloud based model where you simply pay for the amount of resources you require at a given time.
Read More
Auditing Organisational Information Systems – Security
September 17, 2017
Auditing an organisation?s information systems is a vital part of operating a business at any decent scale. Particularly from a security standpoint (Mohamed ElBorno, n.d.). Information systems have many different facets and each organisation operates slightly differently, so while auditing can be handled the same on general shared traits, more bespoke business units and organisational structures should be taken into account when designing a well thought out auditing system that fully guarantees the security of an organisation?
Read More
Biometric Technology
September 17, 2017
What is Biometric Technology? Biometric verification is any means by which a person can be uniquely identified by evaluating one or more distinguishing biological traits (Margaret Rouse, n.d.) Such recognition usually falls into one of the main categories such as: Facial recognition Hand geometry Earlobe geometry Signature comparison Voice waveform recognition Iris-pattern and Retina-pattern recognition Fingerprint recognition The above are the verification patterns which various technologies are built around in order to create working application use cases for larger security concerns.
Read More
Copyright Compensation in the Internet Age
September 9, 2017
The original conception of copyright in 1710 (Craig Joyce, n.d.) was that it usually covers only the expression of a particular idea and not the idea itself, but this was a very long time ago, before the challenges of a digital society. Since then, copyright has had to encompass a wide variety of extended property far removed from it?s original case studies that were available at the time. In the Internet Age, digital items such as music, video (films, series, etc.
Read More
Controlling employee digital access
September 3, 2017
Organisations of all sizes have taken to controlling what their employees can access in order to conserve computing resources, keep their employees focused 100 percent on the work they were hired to do and to make sure employees performance is high and as productive as possible (Cyberoam, n.d.). However, keeping employees motivated and productive is not as simple as simply restricting specific access to internet resources and computer controls. There are many advantages and disadvantages when it comes to controlling said access (CCM, 2017).
Read More
Electronic monitoring in the workplace
September 3, 2017
Electronic monitoring is not a new thing, nor one that only affects the workplace. From closed circuit television (CCTV) in stores and down many streets, to similar surveillance in offices everywhere, we are constantly being monitored in all aspects of our lives. Why and how employers are monitoring employees Many employers and organisations tend to perform similar tactics when it comes to monitoring (Emma Anderson, 2014), but I would like to focus on my current and previous employer in order to draw a common ground and paint a picture as to where and how we as employees are being electronically monitored.
Read More
The Therac-25 Case Study – What Actually Happened?
August 27, 2017
The Therac-25 was a computerised medical technology radiation therapy machine produced by Atomic Energy of Canada Limited (AECL) in 1982. Between 1985 and 1987, it was involved in at least six patients deaths due to incorrect radiation doses because of computer software related failure. When the error was first seen, it was thought to be a hardware problem with the microswitches. After further inspection and deeper technical analysis; the problem was due to a software bug where a Race-Condition – which is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time but the operations must be done in the proper sequence to be done correctly.
Read More
Your Responsibilities as an IT Professional
August 27, 2017
As an IT professional it is extremely important to make sure that you do not take advantage of your position on being able to introduce certain skewed characteristics into a computing system in order to gain unfair advantage to your company or client?s business. This is seen as unethical and in many cases can also be illegal. Your professional responsibilities are: Role The person assigned a task is considered the responsible one (Illinois Ideals, n.
Read More
New capabilities with technology
August 23, 2017
Computing technology has undoubtedly had some very prominent impact on society at large. Of the almost countless capabilities that it has brought us, the following five core capabilities are without a doubt at the top of any compiled list on the subject: Ever increasing speed Unlimited storage potential Lack of human error Global connectivity Auditability Being able to store an unlimited amount of data is one of the main capabilities that we will expand upon and explore in a bit more detail as it provides innumerable offsprings into technological advancements and data insights generally for a wide range of applications and technologies in almost all sub-industries.
Read More
The Printing Press – Technology’s impact on society
August 23, 2017
It’s important to first define what the term “technology” means. Technology is “the application of scientific knowledge for practical purposes, especially in industry.” (Oxford Dictionary, n.d.) The term is not reserved for computing systems, but for any field of engineering or applied sciences. The printing press has been one of the most important inventions in history and would definitely classify as being within the top few technological enhancements of all time.
Read More
Google Abuses Search Dominance in the European Union
August 23, 2017
The EU Commission found that Google has been favouring their very own shopping service while demoting those of their rivals as well as the placement of how they are seen in search results online. This is favoritism or preferential treatment which makes it unethical, regardless of sustainability thereof. This is a negative thing as a world-wide monopoly of this magnitude should not be allowed to occur at all. It means that a single organisation can and will continue to gain more power by pushing their own products and services above those of others.
Read More
Understanding the Risks of Commercial off-the-shelf software (COTS)
July 8, 2017
Commercial off-the-shelf (COTS) software can be an attractive buy in for many companies when it comes to: Purchasing an already made final software solution. Purchasing a solution that is tried, tested and trusted in the industry already. Not wanting to get a development team in to build a bespoke solution. Not wanting to manage a greenfields software development project. It can seem very attractive at first to jump into a COTS solution, but there are many things to take into account that can make it a less than ideal option.
Read More
Identifying Risks in Software Engineering
June 28, 2017
In Software Engineering it is absolutely paramount to identify all risks that may arise in a given project or grouping of tasks. Without doing the aforementioned, a project can quickly unravel and become disjointed and inherently fall apart. It is very important to be able to identify risks and act on them appropriately and in a timely manner (Pressman,1997). Among the many risks that are most common and obvious in Software Engineering, I have decided to showcase three in particular that I have found to be imperative in noticing and foreseeing the looming signs of project degradation and failure.
Read More
Software engineering challenges in the 21st century
June 4, 2017
Software Engineering covers not only the technical aspects of building software systems, but also management issues, such as directing programming teams, scheduling, and budgeting. (Webopedia, n.d.) The world of software has exploded since it’s humble beginnings in the mid 1940’s. Over the next 30 years the industry focused primarily on cost effective hardware manufacturing and software was undertaken as a second measure, but there were no real methodologies to creating robust, reusable software components.
Read More
Computer Memory – The Breakdown
December 26, 2016
Storage devices have come a long way in an extremely short amount of time; given how much they have changed from just my personal knowledge alone. I still remember using an IBM PC XT 286 with 640KB of RAM and a 64KB ROM to using services provided by companies over the past few years such as Backblaze who are building out 60 Drive 480TB Storage Servers accessible from anywhere. There are two primary types of storage topologies.
Read More
Current Trends in Computing
December 18, 2016
The American multinational technology company Yahoo, which has been around since the mid nineties has once again been hacked. This time it is more serious than ever before and a total of around one billion accounts have been identified in the biggest known breach in history as gleaned by The Guardian, Aljazeera, CNBC and numerous other sources. This particular event has contributed towards the overall security risks evident in storing your information on another corporation's network.
Read More
Academic integrity in a cultural context
December 11, 2016
In academia it is vitally important to backup your own thoughts and ideas by using previously written authoritative papers and articles in reference. This helps provide you more credibility as well as proof of what you’re saying actually makes sense and falls in line with previous extensive research that has been done on the subject. It also helps to build upon others so as to not have to “reinvent the wheel” each and every time.
Read More
How to get more traffic to your blog
September 3, 2015
If there’s only one thing that keeps website owners up at night, it’s thinking about the next wave of traffic that they aren’t yet getting. Without decent amounts of traffic your website isn’t really doing all that much – regardless of what fantastic theme or design you may think you have. and gain a more popular website bustling with loads of daily visitors** ** Social Networks The obvious method to get more visitors is to go to where everyone else on the internet is most of the time.
Read More
How big is Amazon S3 really?
September 1, 2015
Amazon’s Simple Storage Service, or simply S3 for short, is a product designed for storing objects (or files are most people know them) in their proprietary cloud hosting (AWS). Since S3 was first released on March 14th of 2006, it has gained amazing amounts of popularity online, particularly from web and software developers. It’s quite interesting to know what S3 really is under the hood and how large it has become.
Read More
3 Things you should be tracking with your analytics software
August 28, 2015
What should we be tracking? This is a question we get asked quite a often – mainly by new customers as well as people who aren’t certain if what they’re looking at adds any value to their daily business time usage. If you’ve ever used an analytics tool, you will identify with how addictive it can be to watch the traffic coming in, see where everyone visitor is from and what they are looking at as it happens in realtime.
Read More
11 of the Best Google Analytics Alternatives
July 29, 2015
So most webmasters know about Google Analytics and have probably used it to some degree, but did you know that there are some pretty good alternatives out there, some even better than the all-famous Google Analytics. We have decided to do a roundup and show off some of our favourites – obviously, we favour Statvoo as we created it, so it’s clearly better ;). Clicky Clicky focuses on keeping things simple and lets you see the stats that matter as they come in.
Read More
503 Service Unavailable: Back-end server is at capacity
July 28, 2015
The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. Some servers in this state may also simply refuse the socket connection, in which case a different error may be generated because the socket creation timed out. Fixing 503 errors
Read More
User Testing and Feedback?
May 7, 2015
So now you have a website, you use it and love it, but does everybody else? There are many tools out there that allow you to do User Acceptance Testing and provide Feedback from real users, but what are the options? Here are some options we have found that may be of interest. UserTesting.com UserTesting.com provides on-demand usability testing. Uxeria.com Your solution for rapid user testing. Users recording in 48 hours.
Read More
Date ranges are the key to a better index
January 14, 2015
Since AO Analytics originally went live in February 2013, we have been doing focused around individual time based reporting, it worked well and we were able to sort through indexes without doing full table scans. After much feedback from our users as well as data usage patterns we made the decision to move to date ranges. This replaced our entire retrieval algorithm and therefore copious amounts of work had to go into regression of backward compatibility while introducing the new way of moving forward with the overall system.
Read More
Track your Alexa Rank History
January 14, 2015
The Alexa Rank is a way of determining a website’s popularity. ?Alexa.com are in the game of Internet popularity ranking and for quite a long time now have been doing a very good job of it. They have a system where the most visited website on the planet is rated as #1 and the second is #2 and so on. If your site is within the top 100,000 alexa rank it is watched more closely and general usage statistics are calculated about it.
Read More
SSL Encryption – Update
January 14, 2015
We have just rolled out SSL encrytion on Statvoo which means: Event data is saved over a secure channel Authentication is done automatically All our user’s login information can not be cached over proxies Https sites can now use the service as well
Read More
Why Website Analytics Is So Important These Days
January 14, 2015
The web has come a long way since Tim Berners-Lee, a British scientist at CERN, “invented” the World Wide Web (WWW) in 1989. Above is the very first Web Server with the classic label on the front “This machine is a server, DO NOT POWER DOWN!!”. Which has become an object of many nerds interests as with it being the very first web server, it is quite an interesting machine to study – not that it is available to play around with, but just because of the nerd value it adds.
Read More
Create daterange array of missing dates
February 20, 2014
<?php //fromDate 2014 - 01 - 22 //toDate 2014 - 02 - 20 //$arr Array( [0] = & gt; Array( [ISO_DATE] = & gt; 2014 - 02 - 18[DAY_SUM_AMOUNT] = & gt; 3000[DAY_SUM_VOLUME] = & gt; 2[CONVERSION_PCT] = & gt; 100 ) [1] = & gt; Array( [ISO_DATE] = & gt; 2014 - 02 - 19[DAY_SUM_AMOUNT] = & gt; 4000[DAY_SUM_VOLUME] = & gt; 1[CONVERSION_PCT] = & gt; 100 ) ) //codetime function createDateRangeArray($strDateFrom, $strDateTo) { $aryRange = array(); $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2) , substr($strDateFrom, 8, 2) , substr($strDateFrom, 0, 4)); $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2) , substr($strDateTo, 8, 2) , substr($strDateTo, 0, 4)); if ($iDateTo & gt; = $iDateFrom) { array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry while ($iDateFrom & lt; $iDateTo) { $iDateFrom += 86400; // add 24 hours array_push($aryRange,date('Y-m-d',$iDateFrom)); } } return $aryRange; } function recursive_array_search($needle,$haystack) { foreach($haystack as $key=>$value) { $current_key = $key; if ($needle === $value or (is_array($value) & amp; & amp; recursive_array_search($needle, $value) !
Read More
Speedtest on Ubuntu Server (commandline)
February 19, 2014
Using the speedtest-cli is easy and very useful. You run it as follows: wget -O speedtest-cli https://raw.github.com/sivel/speedtest-cli/master/speedtest_cli.py chmod +x speedtest-cli ./speedtest-cli
Read More
URL GET vars to PHP Array
May 14, 2013
Sometimes you will need to retrieve the GET variables passed into the current page URI or you will have a URL string to work from which contains certain GET variables, the below method helps a lot to convert them into an array which you can easily manipulate later. $url = $_SERVER["REQUEST_URI"]; parse_str(parse_url($url, PHP_URL_QUERY), $array); $array is now an array of all the GET variables in the URL. Alternatively you can pass a URI string in place of the $_SERVER[“REQUEST_URI”] by replacing the $url variable with something else.
Read More
python "AttributeError: ZipFile instance has no attribute ‘__exit__"
May 8, 2013
This is actually a very easy error to fix, eventhough off the bat it seems a lot more involved. You probably have syntax something like this: with zipfile.ZipFile(wr_zip) as zipfd: extract(zipfd, wr_csv, wr_csv) So instead we will change it to this: zipfd = zipfile.ZipFile(wr_zip) extract(zipfd, wr_csv, wr_csv) The reason this fixes it is because at the moment (Python 2.6/2.7 I believe) the zipfile.ZipFile class has no __exit__ attribute, so it does not work with a `with statement` as other file objects do.
Read More
Remove specific HTML tags using PHP
March 21, 2013
There are times when you want to remove a specific HTML tag from an HTML block of text. This could be an anchor(<a/>) or an image(<img/>) perhaps. You can use preg_replace to do this quite quickly and efficiently. Remove an anchor: $content = "Sample text <a href="#">Our anchor</a>. Etc etc"; $content = preg_replace('/<\/?a[^>]*>/','',$content); //$content is now -> "Sample text. Etc etc"; Remove an image: $content = "Sample text <img src="our_image.jpg">. Etc etc"; $content = preg_replace('/<\/?
Read More
Keep Google Map v3 centered when browser is resized
March 8, 2013
Using Google Maps V3 Javascript API you can keep the map centered to the browser’s window by using the following trick when resizing the window. var mapOptions = { zoom: 2, center: new google.maps.LatLng(0,0), mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); // this is our gem google.maps.event.addDomListener(window, "resize", function() { var center = map.getCenter(); google.maps.event.trigger(map, "resize"); map.setCenter(center); });
Read More
Buy a Google Nexus 10 in the UK!
December 29, 2012
If you are looking to get a Google Nexus 10 inch tablet and are based in the UK you are in for a shocker! The only place to buy it is at the Google Play store and since about the middle of November 2012 they have been sold out. Some people say it’s due to delayed deliveries and orders and some say it’s just bad management on Google’s behalf. I think the latter is probably the thing that actually happened as no other tablet providers seem to ever have this problem.
Read More
Let Joomla and MySQL interact!
December 21, 2012
I often need a quick and easy few lines to retrieve some data from MySQL using Joomla without all the MVC nonsense that usually goes about this topic. So here is how I do it! $dbSEL = JFactory::getDbo(); $dbSEL->setQuery("SELECT MAX(`start_price`) FROM #__some_table"); $dbSEL->query(); echo $dbSEL->fetchRow(); As you can see above, we get the current database object and then run a query on it. You may notice the hash (#) in the SQL statement of this example, Joomla replaces that (as well as the underscores (__) with the database prefix which is configured, so on shared nodes you don’t have to type all that extra stuff that will need to be changed later.
Read More
Perform a Mysql Query using Joomla!
November 23, 2012
This is really actually meant for future reference for myself as lately I’ve been doing quite a lot of Joomla! mysql coding and have used the following code just short of 3million times. $db = JFactory::getDbo(); $querySelectId = "SELECT `id` FROM #__some_table WHERE `user_id`='$user_id'"; $db->setQuery($querySelectId); $db->query(); $data = $db->loadAssoc(); What we do in the above code snippet is select a user_id from some_table (#__) is short for whatever your database table’s prefix is (Joomla!
Read More
Refresh User Data in Joomla
October 21, 2012
I was busy with a custom component in Joomla, and it stored it’s own user_details based off of the main users table, but if the details were changed then I needed the system to update the session to reflect the changes. This is what I did: $user = JFactory::getUser(); $session = JFactory::getSession(); $session->set("user", new JUser($user->id)); $user = JFactory::getUser();
Read More
Extract email addresses from a string – PHP
October 9, 2012
Sometimes you need to extract multiple email addresses from a string and the following function will make all your dreams come true. function extract_emails_from($string){ preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches); return $matches[0]; } ..and this is how you use it: $text = "this is some text and here is an email address xxx@example.com, here's another xxx2@example.com, etc.."; $emails = extract_emails_from($text); Now let’s use the data: // as string print(implode("\n", $emails)); // loop as array foreach($emails as $email) { echo $email .
Read More
How to drive traffic to your website!
September 28, 2012
This is a very hot topic indeed. Definitely one that everyone with a website should know all about. To begin our journey we will look directly at the Traffic Generator Sites out there who – to be honest – are complete scams because all they really do is one of two things… 1.) Load your site into those annoying pop-under ad windows that users close immediately as they appear(not having opened them themselves)
Read More
jQuery limit fields to alphanumeric characters only
September 26, 2012
I was trying to restrict a form’s field from only allowing the user to enter alphanumeric characters into it. I looked all around and couldn’t find a nice way to do it without a plugin, so I wrote my own bind function that you can attach straight to an element. $("#yourFieldsElementId").bind("keypress", function (event) { if (event.charCode!=0) { var regex = new RegExp("^[a-zA-Z0-9]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!
Read More
Make a dynamic year dropdown using PHP
September 18, 2012
Ever wanted to have a dropdown that automatically showed the current year and the few years before it? This is a quick and easy way to do exactly that! <select name="year"> <?php for($i=date("Y")-5;$i<=date("Y");$i++) { $sel = ($i == date('Y')) ? 'selected' : ''; echo "<option value=".$i." ".$sel."-->".date("Y", mktime(0,0,0,0,1,$i)).""; } ?> </select>
Read More
Pad a string with zeros using PHP
September 17, 2012
Recently I had to create a code/username maker to fit into a certain type of pattern so that all “broker codes” (as they were called) followed the same path. An example one looked like so: HJTH0001 The number needed to increment and I wanted to use the auto-increment feature in the mysql database table that was driving this data to make it. This was easy but I ended up with a code that looked like this:
Read More
ImportError: No module named MySQLdb (Python)
July 23, 2012
Trying to use MySQL with Python and getting an ImportError? Traceback (most recent call last): File "some_file.py", line 4, in import MySQLdb as mdb ImportError: No module named MySQLdb This is likely because you have not installed it to the system. You can do this on Ubuntu Linux by running the following code: sudo apt-get install python-mysqldb Also, remember that there is no MySQLdb for python3.x and above. There is however, a fork of it on GitHub at: https://github.
Read More
Search for “arabic” is url request and change codepage – ASP
July 12, 2012
If you are using Classic ASP (yuck) to create an arabic section of a website you can search for the arabic string in your Request URI and then change the session’s codepage as follows: if instr(1, request.ServerVariables("PATH_INFO"), "arabic") then session.codepage = 1252 end if
Read More
Windows 7 is better than Ubuntu 12.04 on desktop!
June 28, 2012
Today we have finalised for ourselves that Windows 7 is definitely a “better” operating system than Ubuntu 12.04 when it comes to desktop environments. Now, I say “better” in quotes because the word is quite hard to use as is and “convince” everybody while doing so. We started our journey on Windows 7 and after desperately needing a reinstall we decided to go for the latest version (at the time) of Ubuntu, which happened to be the brand spanking new Ubuntu 12.
Read More
Function split() is deprecated in PHP
June 12, 2012
You heard it right! split() is officially a deprecated function. That means that you can still use it if you are really brave and it will work correctly, but don’t expect to see it in later versions of PHP when they come out. Somewhere along the line it WILL not work at all. It has been marked as “deprecated” due to the fact that the explode() function has the exact same output!
Read More
Disable Cache in jQuery
May 24, 2012
I usually run into this problem when dealing with good ol’ Internet Explorer (..any version of IE actually). The problem is that IE tries to be smart and not tell you the new output of a file it fetches more than one time with the same filename, instead it shows you what it saw the first time it loaded that file. You can imagine this would be insanely dumb if you were using a realtime application data source where a script output a different resultset each time, e.
Read More
Where is Technology heading, perhaps we should focus more on Software?
May 21, 2012
I often wonder to myself where the technology industry is heading as I see new things come out almost daily. You look around and something you just bought is all of a sudden outdated. This can be quite irritating for the techno-geeks out there that always want the latest release of every gadget, as it makes it somewhat impossible to keep up with what’s in stores. The really nice thing about software over hardware is that one can just perform a localised update instead of having to purchase new hardware everytime something changes or is improved.
Read More
How to break out of an iframe
May 9, 2012
So someone’s trying to make their site better by opening a page on your site inside of their site using an iframe? They’re doing something like this: <iframe src="http://www.example.com/your_page.html" width="100%" height="100%"></iframe> Well how about you stop that from happening by pasting the following line in your website’s header! <script type="text/javascript"> if (top.location != self.location) { top.location = self.location.href; } </script> The above code basically does a check to see if the site is the same as what is said in the address bar, if not then it sets the parent’s frame (the other site) to change to your site’s location!
Read More
Edit hosts file on Windows 7
May 9, 2012
The hosts file is used to manually alter the hostname or IP address in place of it being served by a Nameserver, also known as via DNS. The hosts file is located here: C:\windows\system32\drivers\etc\ Or an easiler way to get to it incase of whatever is like this: %systemroot%\system32\drivers\etc\ This file cannot be editted by “normal users” and requires all changes to be done via an Administrator. This is really easy if you do it in the following way:
Read More
(EAI 2)Name or service not known: Could not resolve host name *.80 — ignoring!
May 8, 2012
You are no doubt trying to add a vhost and you get the following error when attempting to affect changes by restarting the http daemon (httpd): (EAI 2)Name or service not known: Could not resolve host name *.80 — ignoring! Not to worry! Add the following text to httpd.conf at the bottom (That’s at /etc/httpd/conf/httpd.conf): NameVirtualHost 12.34.56.78:80 ServerAdmin yourename@yourserver.com DocumentRoot /var/www/html/the_path/ ServerName the_path.example.com ErrorLog /logs/the_path.example.com-error_log CustomLog /logs/the_path.example.com-access_log common Now just restart the http daemon:
Read More
Virgin Media blocks torrent sites!
May 3, 2012
Virgin Media have done it again! They have gone and started a “downloaders war”, I’m sure of it. Basically what happened is that Virgin Media are claiming that they have had an order from the Courts to prevent access to a whole bunch of sites which lead to illegal downloading or copyright infringement downloading. Not only is it Virgin Media but all 5 major ISP’s in the UK that have received this Court order, that’s Sky, Everything Everywhere, TalkTalk, O2 and Virgin Media.
Read More
How to Comment out a line in a Crontab on Linux
May 3, 2012
Firstly let’s just note that crontabs are read in the following way: * * * * * command to be executed - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +------- month (1 - 12) | | +--------- day of month (1 - 31) | +----------- hour (0 - 23) +------------- min (0 - 59) Your current crontabs can be viewed on your linux setup by typing in the following command:
Read More
DateTime conversion function using PHP
May 1, 2012
It’s really very simple to convert times in different timezones using the following function. function dateTimeConversion($datetime, $timezone="Europe/London") { $date = new DateTime($datetime, new DateTimeZone("UTC")); $date->setTimezone($timezone); return $date->format("Y-m-d H:i:s"); } As you can see, it takes 2 arguments, $datetime which is a time string and a $timezone which is a timezone to convert to. A usage example would be: echo dateTimeConversion("2012-05-01 17:09:58");
Read More
Convert seconds to days, hours, minutes, seconds in PHP
May 1, 2012
With the following function you can easily convert an integer containing seconds to a nice days, hours, minutes, seconds string or array. function secondsToTime($seconds, $return_type="string") { // extract days $days = floor($seconds / 3600 / 24); // extract hours $hours = floor($seconds / 3600) - $days*24; // extract minutes $divisor_for_minutes = $seconds % 3600; $minutes = floor($divisor_for_minutes / 60); // extract the remaining seconds $divisor_for_seconds = $divisor_for_minutes % 60; $seconds = ceil($divisor_for_seconds); // return the final array $obj = array( "d" => (int) $days, "h" => (int) $hours, "m" => (int) $minutes, "s" => (int) $seconds ); $str = ""; if ($obj["d"]!
Read More
Remove dotted outline around anchors
April 30, 2012
This has become quite a common question asked by many website owners. “How do I remove that dotted outline around an anchor?” Lucky for you all, it’s a really easy one to resolve as well. You just have to take a look at CSS for a second and add one line as follows: a { outline:0; } This will disable the outlines around clicked links all around your site. Now that you know how to do it you may want to read about why you shouldn’t do this!
Read More
Get amount of hours between 2 hours
April 27, 2012
If you would like to get the amount of hours between 10:00 and 12:00 then use this! function timeDiff($firstTime,$lastTime) { $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); $timeDiff=$lastTime-$firstTime; return $timeDiff; } echo (timeDiff("10:00","12:00")/60)/60;
Read More
How to embed HTML5 video with fallback
April 27, 2012
A common question with the rise of HTML5 becoming more and more common and the whole iGeneration (iPhones/iPads/iEtc) is “how can I embed a video on my site without using a flash player?”. An option that really does work quite well is to use the JWPlayer and set it up to use HTML5. The benefit of going this route is you can also tell it to have a fallback to flash if the browser is not HTML5 compatible, or even fall all the way back to downloading the video if all else fails.
Read More
How to backup all mysql databases
April 26, 2012
In order to backup all mysql databases, you can run the following command in your linux command line: The example below is configured with username “theuser” and password “thepass”. mysqldump -utheuser -pthepass ?all-databases > all_dbs.sql
Read More
Invalid command 'RewriteEngine'
April 26, 2012
If you receive the following error message if means that mod_rewrite is not enabled in Apache: Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration. a2enmod rewrite Bear in mind this is done like this on Linux Ubuntu, not entirely sure if this works for other flavours too.
Read More
How to get the Hours Difference (in HH:MM format) in PHP
April 12, 2012
It’s very simple to get the difference in hours using PHP function timeDiff($firstTime,$lastTime) { $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); $timeDiff=$lastTime-$firstTime; return $timeDiff; } echo (timeDiff("10:00","12:00")/60)/60;
Read More
Warning: Invalid argument supplied for foreach()
February 28, 2012
A common error which occurs with foreach loops is the standard “Invalid argument supplied for foreach()” whch gets thrown up as a warning. This can easily be overcome by wrapping the foreach loop in a conditional if statement which checks to see if the argument supplied to the loop is an array or not. Below is an example of how to correct the problem: if (in_array($arrItem)) { foreach($arrItem as $arrItemi) { // use $arrItemi; } }
Read More
Unable to connect to any of the specified MySQL hosts.
February 19, 2012
If you get the following error while trying to connect to a MySQL database using a third party client such as TOAD or SQL Workbench, then you need to edit your mysql server’s my.cnf file. Error Message: Unable to connect to any of the specified MySQL hosts. So open the my.cnf file by running a similar command to the following one dependent on your server’s setup: vi /etc/mysql/my.cnf Then edit the bind-address from what is probably set as 127.
Read More
PHP nl2br on one line
February 18, 2012
I usually store data from a textarea directly to the database as is, then once I retrieve it back into HTML I use that lovely PHP function nl2br() to convert it to HTML tags. This works well for most cases until you are passing this data back into javascript where everything has to be on one line! nl2br() outputs as follows: Line one Line two And I want it to be as follows:
Read More
LEN in MySQL
February 1, 2012
In MySQL 5.1 LEN is called LENGTH, you use it exactly the same and pass in the link, so: LENGTH(link).
Read More
Remove all linebreaks in PHP
January 30, 2012
If you are having problems with a string that keeps adding a line break when output from PHP to HTML then the following code will work wonders for you! $string_with_line_break = "blabla\nbla\r"; $string_without_line_break = trim(preg_replace( "/\s+/","",$string_with_line_break));
Read More
IE9 adding empty table cells in large table
January 24, 2012
Well as usual, we are once again fighting the woes of the beloved Internet Explorer, and it appears that Microsoft’s latest greatest new and improved browser rival to the market IE9 still has a whole bunch of irritations and retardation to worry about (saw that one coming). Today I was busy loading a massive amount of data into the body of a table using ajax and in Firefox and even Internet Explorer 8 it worked quite well, but Internet Explorer 9 decided that it would like to add some empty table cells randomly around my “massive table”, now of course I began by kicking something and cried a few times….
Read More
SELECT Duplicate Items Using SQL
December 20, 2011
If you have a table which has duplicate items in then you can use the below statement to select them. SELECT * FROM tableName GROUP BY columnName HAVING ( COUNT( columnName) >1 )
Read More
MySQL Error: Can’t get hostname for your address
December 14, 2011
This error is thrown by MySQL because it tries to do a DNS lookup on the address connecting to the server and it fails due to the IP not being able to be resolved back to a name or some-other deeper DNS bust problem. The easiest way to fix this is to edit your my.ini or my.cnf (/etc/my.cnf) and in the [mysqld] section add the “skip-name-resolve” option. Near the top of the file this will look similar to the below:
Read More
Adobe drops flash for mobiles!
November 9, 2011
..and it’s official – so says Adobe’s blog (read it here). Adobe will be dropping support for Flash on future devices due to performance and a few other things, pushing the future more towards the HTML5 route, which isn’t neccessarily a bad thing, I just find it quite ironic and somewhat comical that they waited for Steve Jobs (Apple) to die before giving up their long time fight with Apple about Flash being or not being supported on mobile devices, namely the iPhone.
Read More
jQuery Colorbox not showing but background shows
November 8, 2011
I was using Colorbox for some lightbox type effects to show larger images when clicking on thumbnails, but for some reason the background was showing up but the pretty little box in the middle where the larger image is supposed to show never showed up, so this is how I made it finally appear after many failed attempts! $("document").ready(function(){ $(".theCssClass a[rel='forGroupingRelCodeGoesHere']").colorbox({ onLoad: function () { $("#colorbox").show(); } }); }); So the “real” code that fixed it was the:
Read More
Get Value of Checkbox using jQuery
October 25, 2011
This one is quite an easy one, but a good one to mention non-the-less as it does definitely come in really handy. If you would like to get a checkbox’s value to send to the backend using jQuery you can always do the following: Firstly let’s draw some HTML to illustrate our example. <input id="chkOurCheckbox" type="checkbox" /> Now we need some jQuery to do the real work. var ourCheckboxValue = ($("#chkOurCheckbox:checked").
Read More
Everybody’s a web host
September 28, 2011
To cut straight to the point, “we’re living in the age where everybody’s a web host”. Whether it be small and quite pathetic or just another reseller of a larger service trying to get their cut of things, everybody truly is spamming the world with more and more web hosting packages. Just a few short years ago this problem didn’t exist and getting web hosting was quite expensive, unless you went with free services such as the good ol’ “geocities” and co, but then larger companies started up their shared hosting and reseller hosting packages which immediately led to everybody thinking all it took to become a web host was to get themselves a reseller account and start trading.
Read More
CSS Background Default
September 15, 2011
If you would like to override an already attached class containing a background then you can use the following: background:transparent none 0 repeat !important;
Read More
Restrict PHPMyAdmin to IP Address
August 22, 2011
Would you like to restrict PHPMyAdmin from being accessible to the whole world? Firstly you need to SSH into your box if you are not on the local machine where PHPMyAdmin is installed along with Apache. cd /etc/phpmyadmin/ vi apache.conf You will need to look for the following text “<Directory /usr/share/phpmyadmin>” and add in the below code: Remember that you need to press “i” in order to start editting text if using VI.
Read More
2014 – Commands out of sync; you can’t run this command now
August 4, 2011
#2014 – Commands out of sync; you can’t run this command now Now that can be a really annoying error! It happens when querying stored procedures in phpMyAdmin as mysqli seems to return 2 sets of results opposed to the usual 1 that mysql returns. You cannot call anything else until you have “flushed” or “cleared” the second result. You can try using COMMIT to resolve this.
Read More
Image corrupt or truncated: “unknown”
July 13, 2011
What is “Image corrupt or truncated: ” and what does it mean? This can often be seen while using Firebug in Firefox, but it actually has nothing to do with either and is just the error being reprinted in in firebug in most cases. It comes from an image that has had it’s extension changed from say .gif to .png or .png to .ico. Eventhough .png and .ico file types are very similar, they are not the same, so an error occurs.
Read More
WordPress wp-admin use different language for user
July 7, 2011
I needed to do some work on a WordPress site a little while ago and all the admins were French – and I cannot speak French other than the popular swear words – so had no idea what was going on in the /wp-admin/ so needed some way of enabling my newly created user account to be in english while letting everybody else use french as they had been up til that point.
Read More
Replace all spaces in HTML with except in HTML tags using PHP
May 29, 2011
If you would like to replace all the spaces in an HTML string with so that you can render it out to the browser but you also want to retain current spaces in HTML tags you can use the below method: $inputString = '<span class="color:red">1</span> 2 3'; $outputString = preg_replace_callback("#>[^<]+<#","relSpaces",$inputString); function relSpaces($match){return str_replace(" ","'",$match[0]);} This will replace: <span>1</span> 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3 ..to look like this: <span>1</span> 2''''''' 3
Read More
Using PHP to validate an IP address
May 18, 2011
You can use the PHP code below to check if an IP address is valid or not. $ip = ""; //enter a valid or invalid ip address here if(filter_var($ip, FILTER_VALIDATE_IP)) { // The IP Address is valid } else { // The IP Address is not valid } Wasn’t that easy!?!
Read More
What is the difference between is_home() and is_front_page()
May 13, 2011
Call me ignorant, or call me an ignorant geek, but I used to think is_home() and is_front_page() was the same thing, until I experimented with them the other day and noticed they did quite different things. Let me break them down: is_home() This actually is the page where all your recent posts are shown. Which means if your “home” page is set to “static” then it will be false, otherwise it will be true.
Read More
..near 'option o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.o' at line 1
May 9, 2011
So you’ve just installed Opencart 1.5.0 and when attempting to edit a product or category or etc you get the following error: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘option o ON (po.option_id = o.option_id) LEFT JOIN option_description od ON (o.o’ at line 1 Error No: 1064 SELECT * FROM product_option po LEFT JOIN option o ON (po.
Read More
What is 1e100.net?
May 5, 2011
So you are probably reading this because you are not sure what 1e100.net is or why you are being redirected via it when performing Google searches or using products such as youtube etc. Perform a SiteWhois lookup 1e100.net is owned by Google and has been in use since October 2009, if you perform a whois on the domain you can see it’s registration details linked back to Google. Perform an SiteInfo lookup
Read More
Hide all error messages PHP
April 28, 2011
PHP Error messages showing up in your web applications are a dangerous thing. Not only does it look unprofessional, but it is also a serious security concern! Once you have completed debugging your website or web application you can place the following one liner at the beginning of your code, this will turn off error reporting and therefore make sure that no application details are spilled to your users. error_reporting(0); If a single line of code is causing the problems it is safer to use the at symbol (@) to suppress any errors it may cause.
Read More
What is xmlrpc.php?
February 22, 2011
It is a script which allows clients to make procedural calls over the net. As it says in the name, the encoding is XML and because it is used on websites we can make the fair assessment that it uses the HTTP protocol. If we break the name down we get: XML transmition via Remote Procedure Calls. So you are still not sure what this is all about? Read on..
Read More
Windows Genuine Advantage Notifications in a VM
February 11, 2011
Windows Genuine Advantage Notifications I am running a Windows XP SP3 VM used for testing multiple versions of InternetExplorer through Virtualbox. Running this wizard should be avoided if Windows is in a VirtualMachine.
Read More
Force HTTP using htaccess
December 4, 2010
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
Read More
Stop That Referrer in PHP!
November 1, 2010
Today I will show you a method to stop the traffic that a referrer site is sending your way, you may wonder why you would want to ignore traffic, after all, isn’t inbound traffic to your site fantastic no matter what? The simple answer is “NO!” Let me explain it in a real life situation so that you can better understand where to use this. Understanding where to use it
Read More
Viva la 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0!
October 26, 2010
You may see this around and not have a clue what the heck it is, weirdly enough, I did.. Why “weirdly” you ask, well, because, who would be looking for something like “09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0”. Let me elaborate.. The Urban Dictionary says it like this: “An alphanumeric string denoting a hack and insecurites in the HD-DVD coding.”
Read More
Ternary Operation
October 12, 2010
If you do not know what the Ternary operator is, or do not use it while you are coding, let me be the first to tell you how much you are missing out! The Ternary operator looks like this: “?”, that’s right, it’s a question mark! My favourite way of using it is to shorten Conditional If Statements, so let me show you what I’m on about. The long way:
Read More
Oops the system encountered a problem (#104)
October 11, 2010
If you get the following error while using Google’s Gmail Service (gmail.com): Oops? the system encountered a problem (#104) ..then you should try deleting your browser’s cache and everything will be resolved. This appears to be a local problem and not on the Google servers as data is pushed via cookies to the local machine using the web service. In order to delete your browser’s cache in Firefox click Tools->Clear Recent History then select “Everything” in the dropdown menu and then deselect everything except for “Cache” in the below list box.
Read More
How to Write Unmaintainable Code
September 22, 2010
I have come across the following article before and again came across it today, after a revised browse through, I thought I may as well add another link to it on the web for whoever ends up clicking on it! It really is a worthwhile (in a humor sort of way) read: http://www.freevbcode.com/ShowCode.Asp?ID=2547
Read More
Captcha Fail!
September 16, 2010
Hey, thought I’d just post this one incase anybody else sees it and thinks it’s funny. This is not really a very helpful post like most of the others on this site, but HEY! TOUGH! So feel free to smile if you like.. What do you know, a snippet of helpful-ness is about to appear-> This issue is usually caused by an invalid referrer! HA!
Read More
Test IE versions on any machine!
September 16, 2010
Do you do web development and are unable to test your software in old shitty versions of Internet Explorer? If so then you may want to read on a little bit. Microsoft has got a whole bunch of virtual images you can download for FREE(not a usual Microsoft word) over here: http://www.microsoft.com/downloads/en/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en They contain an operating system and an install of your favourite IE version! Hooray! They have IE6 on XP SP3, IE7 on Vista, IE8 on XP and Vista.
Read More
Error 500 php_value .htaccess
September 14, 2010
I noticed on some server setups I could not do the following inside a .htacess file: <br> php_value upload_max_filesize 250M<br> php_value post_max_size 250M<br> I was getting an error 500 Internal Server Error with the above code in the .htaccess file. What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead: <br> upload_max_filesize = "250M"<br> post_max_size = "250M"<br>
Read More
Windows Directory Tree Never Finishes Loading?
September 14, 2010
I am running Windows 7 64-bit and since yesterday whenever I open “My Computer”/“Windows Explorer” (-Windows+E) the initial “showing drives” screen is frozen, so I have to use the address bar to navigate to the path I need to go. As you can see in the picture to the left even after you have gotten to and are viewing the folder you want, the directory tree in the sidebar continues to “check” for “who knows what”!
Read More
CSS background image data: base64?
September 9, 2010
What the heck is all that Gobbledygook in the CSS? So you have noticed that bit of css that says something like this in the CSS source-code and you have no idea what it could be? url(“data:image/gif;base64,R0lGODlfMAMEAIABAKysrObm5iH5BAEAAAEALAAAAAAwAwQAAAJOhI+py30Bo5y02ouz3rz7D4biSJbmiabqyrbuC8fyTKPOjedHzff+DwwKh8Si8YhMKku6pvOxjEqn1Kr1is1qt7ynV8cNi8fksvmMTiMLAD4=”) no-repeat scroll 50% 0 transparent It is a technique called Data URLs and using PHP – or your favourite server-side script – you can generate these nifty little things. An example of how to generate it in PHP:
Read More
WordPress remove Subscribe to my RSS feed after posts
September 8, 2010
If you are running WordPress and have noticed a line under all your posts that says: If you enjoyed this post, make sure you subscribe to my RSS feed! ..and if this irritates you as much as it did me, you can remove it by deactivating a plugin called Subscribe Remind. Done! P.S. Sorry Trevor, not trying to piss you off 😛
Read More
And then there was Google Instant!
September 8, 2010
If you have visited the Google.co.uk homepage (Yes, that’s Google UK) recently – since about the 8th of September 2010 then you would have noticed a new search feature Google is pushing called Google Instant. Now what is so nice about Google Instant? It is an ajax type search application that now searches using keyword ghosting and searches and returns results as you type to populate the normal search results page that has been used up until now.
Read More
[Solved] PHP’s typeof – gettype()
September 6, 2010
Quite often you may need the ability to check what type of data type a variable is. In most programming languages this is possible to do and is usually called something like typeof(). So what is typeof in php, or typeof php you ask? In PHP there is a simple function called gettype() and it’s so easy to use. All you have to do is pass the variable in question to gettype() as the first argument and the type will be returned.
Read More
When to use SSL?
September 3, 2010
There has always been quite a lot of heated discussion around the question of when to use SSL and when to avoid it while building websites. I have been asked this question a few times myself and finally thought that it would be good for everybody if I just wrote an article on it explaining what the big huff was all about. Obviously if anyone has anything to add or if you disagree with me for whatever reason, then feel free to do so below at the end of this article.
Read More
IE6 PngFix in Javascript
September 2, 2010
As a web developer you will know just how much we all love hate Internet Explorer 6 – one of the most dreaded browsers and browser versions that still exists in the deep dark corners of the interwebs – and you will probably have figured out that it doesn’t play well with PNG images. So here is how you can resolve this problem. It’s not as nice as an actual browser that can render PNG images natively, but it does work.
Read More
MSSQL Select Not Null
September 2, 2010
I mainly use MySQL these days, so get screwed over for a few minutes when I have to do something in MSSQL that is slightly different when it comes to it’s custom syntax. If you want to show all entries in a specific column and where it is not Null then you can do the following: SELECT [columnNameHere] FROM [databaseNameHere].[dbo].[databaseTableNameHere] WHERE [columnNameHere] IS NOT NULL
Read More
What is __utma, __utmb, __utmc, __utmz ?
September 1, 2010
__utma, __utmb, __utmc and __utmz are 4 cookies created by Google Analytics, for a detailed and very informative read, go here and here.
Read More
How to Close Bandmix Account
August 31, 2010
If you want to close a Bandmix account, then: Login to bandmix.co.uk Go to Options – http://www.bandmix.co.uk/account/options/ Click Decline Service Then click the button called Decline Service at the bottom. Click “OK” to the verification popup. Account closed!
Read More
Google Redirect Virus Fix!
August 27, 2010
Now this is an annoying one. You go to any of google’s sites including any site that has google-analytics.com javascript included in it’s body and BOOM! ..either you get redirected to a bullshit search page you didn’t ask to go to or the browser shows a blank white screen while apparently analytics loads.. It turns out this is actually a virus that infects routers! There are “short-lived-ways” to solve this problem and the one I adopted was to add the following into a windows batch file and run it every bloody time just before doing a google search.
Read More
Chromium Operating System
August 23, 2010
As many of you may know, Chromium is an opensource project that is basically an Operating System built on Linux and is just like working in Google’s Chrome web browser. I decided to take a look at it today and went and downloaded the developer sneak release. It came all boxed up in a 764,994KB (764MB) VMDK Virtual Machine Harddisk file. When it finished downloading I was sadly quite excited as I love trying out new Operating Systems and goodies – being a geeky kind of guy like most guys out there – and after hardly any setup at all it started up.
Read More
Super Easy Email Validation AS2
August 20, 2010
I needed a quick and easy way to check for the basics of an email address. Does it contain “@” and “.” symbols. This is by no meals a foolproof method, so don’t use it for anything big, but if you want to just do a quick test then here you go: var email:String = "name@server.com"; if (email.indexOf("@")!=-1 &amp;&amp; email.indexOf(".")!=-1) trace("false"); else trace ("true");
Read More
VLC Cache Rant
August 17, 2010
The first time this ran it took for freakin’ ages! This should take less than a few minutes What the hell is that supposed to mean? Less than a few? 73 minutes perhaps? Rant over..
Read More
ODBC SQL Server Memory General Network Error
August 9, 2010
Microsoft OLE DB Provider for ODBC Drivers error ‘80004005’ [Microsoft][ODBC SQL Server Driver][Shared Memory]General network error. Check your network documentation. /site/path/to/script/aspfile.asp, line # ..and that’s what it throws you! At about this point you may want to scream, or just be a tad annoyed by that damn machine running your site. Basically your server is either one of two things, and those are: Overloaded Server is “Just Plain Shit” The error is caused because the script is struggeling to connect to the database server – may it even be in the same damn box with same IP and all – and sometimes fails, so shows you it’s overloaded groan.
Read More
XML cannot be the whole program
July 26, 2010
What the hell does that mean? You can get this error thrown up in your good old trusty Firebug console. It expects a script to be returned as an ajax type datatype. So all you have to do is change your datatype to output as XML.
Read More
Mocha Java Decompiler Download
June 25, 2010
Mocha is a Java Decompiler and is 100% FREE to use. The readme.txt file in the Mocha distribution offers the free usage license: The distribution archive (file “mocha-b1.zip”) may be distributed freely, provided its contents (“mocha.zip” and this file, “readme.txt”) are not tampered with in any way. I am pleased to be able to make the Mocha distribution available under those terms: mocha-b1.zip (121K) You can visit the alternative download location here.
Read More
EAI_NODATA
June 24, 2010
Error message: Connection attempt failed with “EAI_NODATA – No address associated with nodename”. The above error occured while using Filezilla (Ftp Client), it either means that you do not have an active internet connection, OR it means that you need to clear the private data because the connection to the server was lost while an active FTP connection was still present. Upon reconnection to the server (which is sometimes automatic) you will receive the EAI_NODATA error.
Read More
1180 Call to a possibly undefined method navigateToURL
June 18, 2010
1180 Call to a possibly undefined method navigateToURL If you get the above error when trying to run your flash actionscript 3 file, you are obviously trying to use the navigateToURL() function but have not imported the flash.net library code. The following code before everything will correct the problem. import flash.net.*; ..or a more of a direct unbloated method is as follows: import flash.net.navigateToURL;
Read More
Test Your Password Strength
June 10, 2010
I came across this site today and it’s quite an interesting one as it works out the approximate time it would take a desktop pc to crack the password. Check it out here.
Read More
How to use a Timer in Actionscript 3
June 10, 2010
It is really easy to create a Timer in Actionscript 3. Instantiate the Timer Class and pass a time in millions of 1000 to it to work in seconds. var myTimer:Timer = new Timer(1000); Setup an event listener to call a function. myTimer.addEventListener("timer", myTimerEventHandler); Start the Timer. myTimer.start(); Start the Timer. function myTimerEventHandler(event:TimerEvent):void { trace(myTimer.currentCount+" seconds have passed."); } So altogether we have this. var myTimer:Timer = new Timer(1000); myTimer.addEventListener("timer", myTimerEventHandler); myTimer.
Read More
Google Background Image
June 9, 2010
Google now allows you to add a background image to the google homepage to apparently make it more, like, home.. hmmmm Just by clicking the button at the bottom left hand corner it allows you to either upload an image or select an image from google. For indepth instructions as per Google, check this page out: http://www.google.com/support/websearch/bin/answer.py?answer=180720&hl=en
Read More
How to Hire a Hacker
June 9, 2010
I came across a very interesting and quite funny read, take a look here for How to Hire a Hacker: http://www.setec.org/hirehacker.html
Read More
If the program is already running, close it before attempting to run.
June 8, 2010
Launch Failed! If the program is already running, close it before attempting to run. I don’t know how many times I have gotten this error message while trying to Run a project in Adobe Flash Builder. For all of you stuck with this message and unable to ever get your projects going, there is quite a simple fix to this. All you need to do is open up Task Manager (Ctrl+Shift+Esc) and click on Processes, then “End Process” on any instances of “adl.
Read More
Random Number In ASP for no Flash Caching
June 4, 2010
This is an example of how to create a random number in Classic ASP in order to append to a swf file so that the browser does not cache the swf file. <% Dim SwfRndNum Randomize SwfRndNum = Rnd %> You can then add it to your swf embed code as follow, bear in mind that I am only showing the snippet around the swf file name and not the entire embed code.
Read More
Why we don’t choose MSSQL!
May 26, 2010
Everybody always raves how great Microsoft SQL Server is, and how much data it can hold, and how much bigger it’s “package” is than your own. But the truth is that I hate it with a passion! I use RDBMS‘ on a daily basis and never used to hate MSSQL so much until recently when I had to modify a very large site that was built in Classic ASP(yuck) and MSSQL.
Read More
How Do You Fire A Client?
May 20, 2010
How do you fire a client? Let’s face it, some clients can be a real nightmare. There are a whole bunch of tell-tail signs that a client is going to be a major problem for you shortly after or sometimes during your first interaction with them. This can be a phone call, a few emails or worst of all, a face to face meeting. Remember that you need to be selective when it comes to work you take on, as a bad client can cause more trouble than they’re worth.
Read More
How to get ‘how many days in February’ using Javascript?
May 19, 2010
It is quite handy to have a function that can tell you how many days there are in February due to the leap year shift of either 28 or 29 days. Below is a function created in Javascript to return the exact amount of days according to the year given: function daysInFebruary (year){ return (((year%4==0)&&((!(year%100==0))||(year%400==0)))?29:28); }
Read More
Weird Pagination on a Google Page
May 17, 2010
Not sure how long this one will last, but for now: Go to: http://www.google.co.za/search?q=MFI/06/ASA-778658&hl=en&start=0&sa=N If you scroll to the bottom, there are 4 pages (pagination), press Next, now there are only 2, WEIRD HUH!
Read More
Actionscript 2 – PHP Data Transfer
May 17, 2010
In the below example we will use Actionscript 2 to call a remote PHP file that will return data to it. It is a simple way of transferring data between the server and client. Actionscript 2 Code: callRemoteFile = function(ourVariable:String) { var result_lv:LoadVars = new LoadVars(); result_lv.onLoad = function(success:Boolean) { if (success) { if (result_lv.message=="success") trace("done! "+result_lv.returnValue); else trace(result_lv.message); } else { trace("Error connecting to server"); return false; } }; var send_lv:LoadVars = new LoadVars(); send_lv.
Read More
Unique Random Numbers in PHP
May 13, 2010
If you would like to show random numbers using PHP you can do this: <?php $min = 1; $max = 100; $total = 100; $arrItems = array(); while ( count($arrItems) < $total ) { $item = mt_rand($min,$max); if (!in_array($item,$arrItems)) { $arrItems[] = $item; echo $item."<br />"; } }
Read More
HTML mail() Sending as Plain Text
May 11, 2010
$to = "email@address.com"; $subject = "SUBJECT"; $message = "<b>MESSAGE</b>"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: Mailer ' . "\r\n"; mail($to, $subject, $message, $headers); The above code does not always send emails in HTML as it should, it turns out there is a PHP Bug (http://bugs.php.net/15841 ) that comes into play with QMAIL and carriage returns. If this is the case you should replace “\r\n” with a “\n” only.
Read More
Turbo C++ in DosBox for Windows 64bit
May 7, 2010
I had to compile a C++ application under a DOS environment and was running Windows 7 64bit. Firstly, Turbo C++ is a 32 bit x86 application and therefore will not run when initialised from an x64 environment. This can easily be solved by installing the DOS Emulator called DosBox. One can then mount the Turbo C++ folder as a drive and install it under a subdirectory. e.g. mount c c:\PathToMyTurboCppDirectory\ Once in there it’s quite easy to open and compile the source code, but good luck to anyone that tries to write anything from scratch, it’s really painful and half the keys are not mapped in the DosBox, eventhough you can press Ctrl+F1 to open the Keymapper.
Read More
Case Insensitivity with .htaccess files
May 5, 2010
If you have an .htaccess file to control the flow of URI’s on your site you may want to look at adding a nice little “case insensitive” feature to each line/item. So an example of a line of .htaccess without any case insensitive bells and whistles looks like this: RewriteRule ^AndrewOdendaal$ index.php?go=2964 We add our Case Insensitive feature by just adding a [NC] to the end of the line, like this:
Read More
Actionscript2: Split string by line length with & without word-wrap
May 5, 2010
Split string into sentences by max line length. This uses a character array but doesn’t use word-wrapping. var personalMessage: String = "You got this far so we reckon that you could be curious enough to learn a little more, we?ll contact you shortly to answer any questions you may have."; _root.myArray = new Array(); _root.myArray = personalMessage.split(""); _root.mySentences = new Array(); var currentCharCount: Number = 0; var currentCharItem: Number = 0; var currentCharString: String = ""; var maxLength: Number = 65; for (var i = 0; i & lt; _root.
Read More
Search and Replace Anchor Href using Javascript
April 29, 2010
I have a site that is under development and it was made really badly so I needed a quick way to replace all anchors on page to the relevant path. The problem is because it was a testsite that lived away from the public facing domain, the anchors had to be changed because they were all coded in as absolute paths. I included a JavascriptDebug file and put the following in there:
Read More
Error 29506 while installing SQL Server Management Studio Express
April 28, 2010
I was trying to install Microsoft SQL Server Management Studio Express (what a long name) on a machine and kept getting error 29506 right near the end with a Rollback action thereafter. To get this program installed you will need to run Command Prompt as Administrator and then run the MSI (installer) from there. Navigate to C:\Windows\System32\ then right click on cmd.exe and select Run as Administrator. Once the console has loaded, you can “cd” to the directory and then run the installer from there.
Read More
Swap HTML Elements Using Javascript
April 26, 2010
It is quite easy to use javascript to swap between divs or any other html dom elements. Using the function below you can pass the id of the element to show and to hide. function swapDivs(show, hide){ document.getElementById(show).style.display = "block"; document.getElementById(hide).style.display = "none"; }
Read More
A PHP Mail Class
April 26, 2010
Below is a Mail class I created in PHP, it requires 4 arguments on initiation of the class via the constructor and uses the method ->send() to send the created mail once complete. class Mail { var $to; var $subject; var $content; var $headers; function Mail($to, $subject, $content, $from){ $this->to = $to; $this->subject = $subject; $this->content = $content; $this->headers = "Content-type: text/html; charset=iso-8859-1\r\nFrom: $from"; $this->content = "".$content.""; } function send(){ return mail($this->to, $this->subject, stripslashes($this->content), $this->headers); } }
Read More
iTunes keeps maximizing!
April 26, 2010
Oh my goodness, this can be an annoying issue with iTunes. The problem is: iTunes will restore itself or maximize itself all the time every 20 or so seconds without being clicked on, it will also get main focus and whatever you were doing will have to wait! I solved this by right clicking on the iTunes program icon where I launch it from and selecting Properties, then selecting “Compatibility” then making sure “Run this program as an administrator” was checked.
Read More
Replace newline break in Excel
April 23, 2010
Ever needed to find & replace the newline character in a large excel document? In the Replace Dialog (Ctrl+F) Find: Hold down [alt] and type 010 on the numeric keypad. Replace: Replace with a space " " (without quotes)
Read More
PHPExcel Class Usage
April 23, 2010
I just finished adding an export xls (excel) export feature to a web application. I used the PHPExcel Class from CodePlex, its really great to work with – as far as the world of exporters go that is. In the example below the “exportCheckpoints” function requires an imploded string seperated as “|||||”. Hopefully it gives an example of how easy it “could” be to export something from mysql to excel using php.
Read More
unexpected T_IF
April 22, 2010
Getting “Parse error: syntax error, unexpected T_IF” ? Check if the preceeding line ends with a ;
Read More
Worst Websites of All Time
April 19, 2010
http://www.arngren.net/ http://www.lingscars.com/ http://www.theworstwebsite.com/ – beware, alert boxes coming! http://havenworks.com/ http://www.msy.com.au/ http://www.5safepoints.com/ http://www.pixyland.org/peterpan/ http://www.aiseikai.or.jp/ http://www.jfw.ie/ Think you’ve found the worst website of all time? Post it below!
Read More
Set line leading / line spacing in flash actionscript 2
April 16, 2010
This is how to add text leading using Actionscript 2 for Flash. var txtFormat:TextFormat = new TextFormat(); txtFormat.leading = 5; // change this to whatever you need it to be ttt.setTextFormat(txtFormat); ttt2.setTextFormat(txtFormat); There is also a GUI way of doing this: Select your textfield and and under the paragraph section, set the top/right hand icon (Line Spacing) to whatever you like.
Read More
MySQL Main Query Types used in PHP to select, insert, update and delete data
April 16, 2010
MySQL Main Query Types SELECT SELECT * FROM tablename INSERT INSERT INTO tablename (col1, col2, col3,..) VALUES (val1, val2, val3,...) UPDATE UPDATE tablename SET `col1`=`val1`, `col2`=`val2`, `col3`=`val3`,... DELETE DELETE FROM tablename WHERE `col4`=`val6` Note You will use a lot of WHERE clauses as well along with the above. e.g. SELECT * FROM tablename WHERE `id`='15' In PHP Calling to MySQL is really easy in PHP, just use the mysql_query() function.
Read More
Connect to mysql database from php
April 16, 2010
If you need to connect to a mysql database from php you can do it like this: <?php $DBH = 'localhost'; $DBU = 'root'; $DBPWD = 'password'; $DBN = 'petstore'; $conn = mysql_connect($DBH, $DBU, $DBPWD) or die ("Error: Could not connect to database."); mysql_select_db($dbname); This allows you to make a connection to the mysql database and gets it ready for you to make queries and manipulate the data.
Read More
htaccess file and error 500 internal server error
April 14, 2010
I have a question for anyone that can answer it: I create an .htaccess file in the root of a subdomain, but if I enter either of these two lines I get an erro 500 Internal Server Error: php_flag magic_quotes_gpc off php_flag register_globals off Any suggestions anyone?
Read More
Quake 4 – Fatal Error: could not create destination file
April 9, 2010
If you get an error message similar to this one when trying to run Quake 4… Fatal Error: could not create destination file C:/Program Files (x86)/id Software/Quake 4 Multiplayer Demo/q4mp/gamex86.dll …then you should run the exe as Administrator. So Right-click, “Run as Administrator” and all will be sorted.
Read More
phpMyAdmin – Invalid field count in csv input on line 1
April 9, 2010
I was trying to import a massive csv dataset into phpMyAdmin and it kept throwing error: Invalid field count in csv input on line 1 This is quite annoying as I followed all the usual steps as per normal. To solve this I had to do the following: Import Browse for your CSV file. Select CSV using LOAD DATA (rather than just CSV) Change “Fields terminated by” from “;” to “,” Make sure “Use LOCAL keyword” is selected.
Read More
Choosing a programming IDE
April 7, 2010
This is somewhat of a debatable topic, but it has come up a lot of times without any real final clarity, so I will try and cover it all. Lets begin by explaining exactly what an IDE is and then we can move onto the more debated areas of choosing the right one for you. An IDE stands for “Integrated Development Environment” and is often used by programmers when creating their applications.
Read More
Double border in CSS
March 30, 2010
CSS allows you to add a border to almost all html elements. If you would like a double border you can use CSS like this: style="border:double"
Read More
[Exception… “Could not convert JavaScript” nsresult: “0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)”
March 30, 2010
What the heck is.. uncaught exception: [Exception… “Could not convert JavaScript argument arg 0 [nsIDOMHTMLDivElement.appendChild]” nsresult: “0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)” location: “JS frame :: PATH_TO_MY_JAVASCRIPT_FILE :: THE_METHOD_NAME :: line #” data: no] For me it was just an appendChild() that was causing the problems. You can always try the innerHTML+= way if all else fails 😉
Read More
Error 1046: Type was not found or was not a compile-time constant: Event.
March 29, 2010
Error 1046: Type was not found or was not a compile-time constant: Event. You need to import the Event class! import flash.events.Event
Read More
Add a date to a date in Actionscript 2
March 26, 2010
I needed to work out a date range according to the date 3weeks away from the current date. After a bit of thinking, I found that it’s actually quite easy to achieve. var theDate:Date = new Date(); dateDay = theDate.getDate(); dateMonth = theDate.getMonth(); dateYear = theDate.getFullYear(); var theDate2:Date = new Date(dateYear,dateMonth,dateDay); theDate2.setDate(theDate2.getDate() + 21); dateDay2 = theDate2.getDate(); dateMonth2 = theDate2.getMonth(); dateYear2 = theDate2.getFullYear(); The above code gets the current date and adds 21days/3weeks to it.
Read More
Add a month to selectable date range – Date Chooser – Actionscript 2
March 22, 2010
I have been working on a project where I need to select a date range starting today and ending a month from now, so the user cannot select anything in the past or over a month from now. This is how I did it: There is an instance of DateChooser on the stage with Instance Name “calDate”. var todayDate:Date = new Date(); dateBeginDay = todayDate.getDate(); dateBeginMonth = todayDate.getMonth(); dateBeginYear = todayDate.
Read More
hitTest and Actionscript2
March 19, 2010
if (mc.hitTest(_root._xmouse, _root._ymouse, true))) { trace("hitTest Run"); }
Read More
127.0.0.1:4664 and Google Desktop Search
March 17, 2010
Recently I checked my website stats and saw I had a few hits from “127.0.0.1:4664” and wondered to myself, what the heck is that? Am I looking at my own site from a localhost? Why am I getting backlinks from my local computer to my site. After searching around a bit I found out that port 4664 is used by Google Desktop Search and when I typed in certain queries into Google it also returned items from my desktop search.
Read More
Limited numeric input in flash actionscript 2 textfield
March 16, 2010
If you want to only show numeric characters in a textfield in flash actionscript you can use the following code: myTextField.restrict = "0-9";
Read More
Embed pound symbol (£) in flash textfield
March 10, 2010
If you use a dynamic textbox in Flash and you want to embed the British Pound symbol (£) then you will want to also embed the “Latin I” glyphs with your textfield.
Read More
Enable / Disable Cursor Hand in Actionscript 2
March 1, 2010
If you have a movieclip that by default has the hand cursor showing on RollOver and you don’t really want this, you can disable it by doing the following: myMC.onRollOver = function() { this.useHandCursor=false; } So the main code here is: this.useHandCursor=false; False disables it and true shows it.
Read More
USB Device Not Recognized! in Windows
February 25, 2010
Believe it or not, this one is super easy to fix! It’s actually a temporary problem with your motherboard, all you need to do is: turn off your computer if it’s a desktop then unplug it from the wall/powersupply if it’s a laptop then remove the battery let it sit for a minute plug it all in again reboot VOILA! No need to uninstall/reinstall drivers or anything!
Read More
Calling event functions from movieclips in actionscript 2
February 24, 2010
In a flash movie I usually have a frame of actionscript that controls all elements in the file to keep everything in one place. Sometimes I have an onPress(etc) function that refers to something happening in the scene when something is pressed, but what happens if we want another element to refer to that event for some reason? Here’s an example of that code without anything “flashy”: _root.myMC.onPress = function() { //code goes here } .
Read More
Sudo install OpenGL & SDL on Ubuntu
February 22, 2010
A quick and easy way would be to type the following in one line with single spaces in the Terminal. This way of installing OpenGL and SDL libraries only applies to Ubuntu. sudo apt-get install nvidia-glx-new-dev libglew1.4-dev libsdl1.2-dev libsdl-ttf2.0-dev libsdl-image1.2-dev libsdl-mixer1.2-dev
Read More
How To Modify Hosts File On Windows
February 19, 2010
The hosts file is located at the following address: C:\windows\system32\drivers\etc</span> or %systemroot%\system32\drivers\etc</span> But you will need to open Notepad with “Run as Administrator” first and then open it through there otherwise it will give a permissions problem
Read More
Get all directories in PHP
February 17, 2010
I think this may be the fastest way to get a list of all the directories in a given folder/directory using PHP. $directories = array_filter(glob('*'), 'is_dir'); ..and of course, you can also add a path to it if you need to: $directories = array_filter(glob($myPath.'*'), 'is_dir');
Read More
Security error: securitySandboxError with Flash
February 17, 2010
You have a flash uploader and you get this error: security error: securitySandboxError This means that the flash is not trusted by the domain and you have to place an xml file in the root of the domain. The file is called “crossdomain.xml” and this is what should be inside it: Solved! 😉
Read More
Component Inspector in Flash has ISSUES!
February 11, 2010
I discovered a very annoying bug in the Flash IDE a little while ago, and it has happened to me quite a few times. Today it happened again and so I write this post.. While in the Flash IDE you select a component on the stage, then you click “Component Inspector”. This opens up into a modal window which is nice and everything BUT…. …..if you then give focus to another program and then try click back into flash, it hides the “Component Inspector” modal window but still keeps focus on it, so basically, you can’t use the program(Flash IDE) / save your file / or even close the program!
Read More
Close/Delete Google Checkout Account
February 8, 2010
I have used Google Checkout to receive payments in the past and have had problems with some clients not paying and blaming it on Google Checkout that the money did not go through (like the guys over at Peartree DMS). I decided that this account was not worth the trouble anymore and wanted to close my account. I looked online everywhere and couldn’t find where to close the account – after quite a while I found how to do it, so here is how to close/delete/remove your Google Checkout account:
Read More
Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource
February 2, 2010
Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource You have just gotten a warning when trying to check if an inserted row was successful but when calling mysql_affected_rows(mysql_query(“INSERT INTO……”)) you get a warning telling you that the supplied argument is not a valid MySQL-Link resource. This is because mysql_query INSERT actually returns true or false and not a resource id. So rather do this: if (mysql_query(“INSERT INTO…”))
Read More
Capitalize First Letter in Word – Actionscript 2
February 1, 2010
You have a string and you want to capitalize the first character but have the rest of the word in lowercase. DO THIS! myStringVar = myStringVar.substring(0, 1).toUpperCase()+myStringVar.substring(1);
Read More
HP Pavilion Laptop Madness
January 28, 2010
I have got an HP laptop and have started experiencing problems with it starting up for the past few months, it is only about 1.5years old and is supposed to be a decent one. It is an HP Pavilion dv9700 by the way.. Today the damn thing just didnt want to startup and eventually after trying every trick in the book I got it to boot into Degugging Mode in Windows Vista.
Read More
Why you should use OpenGL and not DirectX
January 27, 2010
Below is a very interesting article I found that proves all the myths about DirectX being better than OpenGL, a very well written paper describing it best. Thanks for that guys at Wolfire.com! http://blog.wolfire.com/2010/01/Why-you-should-use-OpenGL-and-not-DirectX
Read More
What does __FILE__ in php mean?
January 26, 2010
In php there are a few magic constants and I find FILE to be a very useful one. It returns the full path and filename of the file in question. Take a look at the PHP Manual – Magic Constants for more information on the others.
Read More
Woopra Failed to Connect?
January 26, 2010
I have used Woopra for a few months now and have started seeing this warning/error almost everyday now: Could not enable live functionality at this time. Click to reconnect. If you click the text/warning/error it seems to go away… Anybody konw what’s really going on under the cover? What happened: It turns out Woopra have upgraded their desktop application and will get to the web based application once they are done with everything else.
Read More
Change PHP Session Time
January 25, 2010
The default time for a php session is 1440 seconds. You can change it by doing the following: ini_set("session.gc_maxlifetime",1440); You can obviously adjust the second parameter (1440) to anything you like to change the timeout limit.
Read More
Stop mouse click in browsers
January 8, 2010
There have been multiple ways to stop your user/s from right clicking on your site, but many of them now fail due to the way firefox’s contextual menu loads. Below is an example of how to do it: function _c(e) {if (document.all) {if (event.button==2||event.button==3) {return false;}} else {if (e.button==2||e.button==3) {e.preventDefault();e.stopPropagation();return false;}}if (e.which) {}}if (document.all){document.onmousedown=_c;}else{document.onclick=_c;document.ondblclick=_c;} ..and here is the full working example in a webpage: <script><br /> function _c(e) {if (document.all) {if (event.
Read More
Microsoft apps never care!
January 8, 2010
I often seem to have this issue when dealing with Microsoft software. You click “Cancel” and it just carrys on going, so you click it again a few more times and instead of it just stopping in it’s tracks, decides to rather tell you it’s cancelling and then shows a cancelling dialog box for the next 10 minutes! Cummon guys, that’s not very professional!
Read More
Place HTML Div on top of Flash
January 8, 2010
If you have ever tried to place a div or similar HTML element on top of a swf flash object you will know that it always tries to take precedence. You will need to do the following: In the code for the flash in the embed area add: wmode="transparent" If you are using SWFObject to insert swf files you can do the following: <script type="text/javascript"> var so = new SWFObject("movie.swf", "mymovie", "400", "100%", "8", "#336699"); so.
Read More
Get current working directory of php script/application
January 8, 2010
$myPath = realpath(dirname(__FILE__)); or $myPath = getcwd();
Read More
Stage align and Stage scale in actionscript 3
January 8, 2010
If you want to position the flash top/left and not have it scale when you resize it’s bounding box window, you can set the following code. stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; For full documentation from Adobe take a look here.
Read More
Error 406?
January 6, 2010
So you received an error 406 while trying to upload a file and you have no idea to fix it! Create an .htaccess file in the root of your local website and add the following into it: <IfModule mod_security.c> SecFilterEngine Off SecFilterScanPOST Off </IfModule>
Read More
Firefox error in FeedProcessor.js
January 6, 2010
[Exception… “Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIChannel.contentType]” nsresult: “0x80040111 (NS_ERROR_NOT_AVAILABLE)” location: “JS frame :: file:///C:/Program%20Files/Mozilla%20Firefox/components/FeedProcessor.js :: FP_onStartRequest :: line 1440” data: no] file:///C:/Program%20Files/Mozilla%20Firefox/components/FeedProcessor.js Line 1440 So what the heck does that all mean? Basically, there is an exception error on like 1440 of the local Firefox javascript file “FeedProcessor.js”. The line in question is as follows: channel.contentType = “application/vnd.mozilla.maybe.feed”; The whole section of code reads as follows: // nsIStreamListener
Read More
mySQL select multiple ids
December 18, 2009
SELECT * FROM tablename WHERE `active`='1' AND `id` IN ('107' , '125' ) ORDER BY `id` DESC LIMIT 12`
Read More
Force Download in PHP
December 16, 2009
This script works in all browsers, including Internet Explorer! 🙂 if (strstr($_SERVER['HTTP_USER_AGENT'],"MSIE")) { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application-download"); header("Content-Disposition: attachment; filename=\"".basename($filename)."\";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".@filesize($ab_file)); set_time_limit(0); } else { header("Content-type: application-download"); header("Content-Length: ".filesize($ab_file)); header("Content-Disposition attachment; filename=".$filename); } readfile($ab_file);
Read More
Remove an onRelease Handler
December 16, 2009
After creating a onRelease handler in Actionscript 2 as follows: myMovieClip.onRelease = function() { doWhatever(); } ..you then want to remove the handler for whatever reason, you can remove it like this: delete myMovieClip.onRelease;
Read More
shortText function toggler in php
December 15, 2009
I often have to show a shortened version of a news item and then a link to show the entire news article or whatever. Here’s a way to get that short text! function shortText($text, $length) { if( strlen($text) > $length ) return substr(preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $text), 0, $length)."?"; return preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $text); }
Read More
PHP – file() lines
December 15, 2009
$lines = file('all-words.txt'); foreach ($lines as $line_num => $line) { echo "Line number ".$line_num; }
Read More
Windows Live Writer – Beta2
December 14, 2009
Start writing content to your blogs from your Windows Desktop now. No need to login to your wordpress backend to post items anymore, there is now a decent desktop application that allows you to do exactly that! I have looked at it before but not until recently when Beta2 came out did I gain more interest for it. The WordPress functionality added is what got me going and now I am able to post directly!
Read More
Reported Attack Site!
December 11, 2009
What the heck is that? So you’ve just visited a website using Mozilla Firefox and this message has popped up telling you that the site looks suspicious. Usually the site has been marked as a possible virus containing website and Firefox will show you this message attempting to protect itself against Malware, Spyware or other forms of Viruses. There are occasions when this is mearly a warning and not to be taken as concrete evidence of viruses or impending browser/computer doom!
Read More
Simple HEX Colour Values
December 10, 2009
Actual Display Colour HEX Colour #000000 #FF0000 #00FF00 #0000FF #FFFF00 #00FFFF #FF00FF #C0C0C0 #FFFFFF
Read More
Send Email PHP Function
December 10, 2009
Ever find yourself typing the headers into the php mail() function over and over again? Try using a standard function and calling it when you need to send mail. function sendEmail($subject,$content,$from,$to){ $header = "Content-Type: text/html; charset=iso-8859-1\nFrom:$from"; if( mail($to, $subject, $content, $header) ); }
Read More
mySQL Development Tools
December 9, 2009
I came across a very interesting article about mySQL Development Tools. http://www.smashingmagazine.com/2009/03/25/mysql-admin-and-development-tools-round-up/
Read More
1180: Call to a possibly undefined method getURL. Actionscript 3
December 7, 2009
Hello all actionscripters, you can’t use getURL anymore in Actionscript 3. Below is how you should now start doing it: var request:URLRequest = new URLRequest("/"); try { navigateToURL(request, '_blank');} catch (e:Error) { trace("Error occurred!");}
Read More
Online Flash IDE Anybody?
December 3, 2009
Anyone up for an online Flash IDE? Take a look at this: http://antimatter15.com/ajaxanimator/build/ Nice work!
Read More
Papervision Event Listener Idea
December 3, 2009
The problem: While working on a Papervision3D Flash Project I had a problem where a back button that sits above the 3d canvas and acts as a main navigational item was required to change Events according to where the site was in 3d space at the time. The solution: Everytime I’m about to add a new EventListener to the back button movieclip I call the function “delBB()” and then add my event listener using addBB(with the event here).
Read More
Don’t cache my swf files!
December 2, 2009
I often have issues where ‘dumb browsers’ cache my published swf files and when they dynamically populate they don’t always update. This is SUPER annoying and I have found a solution. I will demonstrate the technique with a LoadsVars example var nc = Math.floor(random(1000000) / random(1000)); var send_lv:LoadVars = new LoadVars(); send_lv.sendAndLoad(_root.siteURL+"profile.php?action=showallimages&amp;nc="+nc, result_lv, "POST"); So let me describe what is happening here. The really ‘dumb browsers’ like IE7 in this case decide that seeing as the URL in question has the exact same name, it will be clever and just use the last version it saw and be totally lazy and not attempt to get the data again.
Read More
Clear an array in Actionscript 3
December 2, 2009
I personally really like this way of clearing an array’s elements: Declare your array to use: var myArray:Array=new Array(); Add elements: for (var i:Number;i<10;i++) { myArray[i] = "an item"; } Clear the array:
Read More
Change combobox font size in Flash Actionscript
November 30, 2009
Ever needed to change the font size of a standard flash combobox component? You will need to give it an instance name e.g. “myCombobox” and then add the following code: myCombobox.setStyle("fontSize", 10);
Read More
Wordwrap that PRE!
November 23, 2009
Ever used a <PRE> in a limited width div container? You will notice that the line gets cut off almost as if word-wrap was not enabled. To correct this you can add the following code into your CSS file. pre{ white-space: pre-wrap; /* CSS2.1 compliant */ white-space: -moz-pre-wrap; /* Mozilla-based browsers */ white-space: o-pre-wrap; /* Opera 7+ */ } This code was originally found somewhere else online but I found it really useful so reposted it!
Read More
Barclays ePDQ Payment Gateway
November 23, 2009
Hello all! Today we will be talking about Barclays online payment gateway valled ePDQ. You can take a look at what they have got to say by clicking here to view Barclays’ site or you could keep reading 🙂 Well, for all you php guys out there, this post if for you! Barclays ePDQ encrypts your data string of products in your basket and returns a result that is sent with your HTML form on your site.
Read More
BrainWHAT? programming language
November 23, 2009
I came across a programming language today that I have never heard of. Go take a look over here: http://en.wikipedia.org/wiki/Brainfuck
Read More
Transparent swf in html
November 23, 2009
So you have now placed a swf file into your html page and you want to be able to see through it. Lucky for you, this is a very easy thing to do! The following code does the trick: <object data="flash/home_side_left.swf" type="application/x-shockwave-flash" width="40px" height="550px"><param name="movie" value="flash/home_side_left.swf" /><param name="bgcolor" value="#ffffff" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /></object> Notice that by just adding the wmode and setting it as ‘transparent’ does everything for you!
Read More
Constant updates?
November 13, 2009
I just hate it how everything always wants to update… and then restart all the damn time! First things first: This pops up telling me it’s doing a 309.6MB Adobe Reader Update! Which to me is just crazy… Surely the constant updates shouldn’t be a million times larger than the actual initial install file for the application? I just click Cancel and then do this.. Not a minute later and this little guy pops up!
Read More
Share the mouse and keyboard!
November 13, 2009
A very interesting project I found this morning, take a look at this one! http://synergy2.sourceforge.net/
Read More
What is CWS>+?
November 12, 2009
So what the heck kind of file starts with the characters “CWS>+” ? That would be a flash swf file!
Read More
Papervision error 1046
November 5, 2009
Error: “1046: Type was not found or was not a compile-time constant: InteractiveScene3DEvent.” I got this this morning when I opened up a project I have been working on. I was using the Flash IDE to compile and FlashDevelop to code in as I am not the biggest fan of the Flash IDE for coding in….. Who is? Right? Anyways… I tried to publish my swf and I got loads of errors like the one above.
Read More
azupnpav_0.2.23
November 5, 2009
So what the heck is “azupnpav_0.2.23.zip”? It appears to be a plugin for Vuze(Azureus) the torrent client. Filesize: 198.1 kB
Read More
How to Save a Dreamweaver document as UTF8!
November 4, 2009
Today I tried to save arabic text inside a javascript file and on saving encountered a dialog box asking me to first convert the document to UTF8. Why it didnt just do it for me I’ll never know, so I had to do it myself. If you encounter this then do the following to convert the document: Click on the Modify main menu item and select Page Properties. Change the Encoding/Document Encoding dropdown to say “Unicode (UTF-8)” or “Unicode 4.
Read More
16000 Limit!
November 3, 2009
Today I discovered that Flash truly has a limit! 16,000 frames: Exceeding this limit causes the movie playback to stop. While this limit is rarely reached by most developers, it is possible. If your movie must have more than this number of frames,try creating multiple movies with fewer than 16,000 frames each and then linking the movies togetherusing a method such as the ActionScript 2 loadMovie() command. 16,000 layers: Flash is not capable of working with more than 16,000 layers in a movie.
Read More
htaccess ErrorDocument
November 2, 2009
Create a file called .htaccess in the root of your public_html/htdocs of your domain. Inside add the following text: Options +FollowSymLinks AddDefaultCharset UTF-8 RewriteEngine on Options +FollowSymLinks AddDefaultCharset UTF-8 RewriteEngine on ErrorDocument 404 /index.php ErrorDocument 301 /index.php With the index.php files being the pages that get redirected to.
Read More
How to correctly form HTML
November 2, 2009
<!DOCTYPE html PUBLIC ?-//W3C//DTD XHTML 1.0 Strict//EN? ?http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd?> <html xmlns=?http://www.w3.org/1999/xhtml?> <head> <meta http-equiv=?Content-Type? content=?text/html; charset=UTF-8? /> <script type=?text/javascript? src=?javascript/javascriptfilename.js?></script> <title>Title goes here</title> <link href=?stylesheetname.css? rel=?stylesheet? type=?text/css? /> </head> <body> Page content goes here </body> </html>
Read More
Trying to get variables into flash from the browser!
November 2, 2009
Ever wondered how to get variables from an html page to a flash element? Well, it’s quite easy using the following actionscript 2 example: I use javascript to embed my flash elements: _ <embed src="somefilename.swf?varname=varvalue&vartwo=var2value" width="550" height="400"></embed>_ Now in Flash I can just call: _root.varname and it will give us `varvalue` _root.vartwo will give us `var2value` Wasn’t that easy?
Read More
Flash Tweening
October 20, 2009
tween is an actionscript class and can be used after importing the core files. import mx.transitions.Tween; import mx.transitions.easing.*; //Tween( obj:Object, prop:String, func:Function, begin:Number, finish:Number, duration:Number, useSeconds:Boolean); e.g. var myRot:Tween = new Tween(myText, "_rotation", Elastic.easeOut, 0, 360, 3, true);
Read More
Cube Desktop on Ubuntu
October 20, 2009
Alright, so I run Ubuntu 7.10 and use the Desktop Effects via compviz, anyhow, I could get the 2d workspace but really wanted the 3d cube, even if I set up 4 desktops, it would still only show 2 sides of the cube(aka not a cube). The solution is: In Terminal do: gconftool-2 --type int --set /apps/compiz/general/screen0/options/hsize 4 😉
Read More
Animate with Actionscript [part1]
October 20, 2009
// Created by Andrew Odendaal // // :: DESCRIPTION :: // Animate a ball moving to the top // of the screen/stage and back again // // :: HOW TO USE :: // create a circle shape, convert to a movieclip(mc) and // place the registration point at the bottom center. // give the circle mc an stage instance name of 'ball'. var ball:MovieClip; var initBallY:Number = _root.ball._y; onEnterFrame = function() { if (_root.
Read More
To Install IIS 7.0 on Windows Vista – script
October 20, 2009
start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-Security;IIS-BasicAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI
Read More
Kill Adobe Updater
October 20, 2009
So adobe updater keeps doing updates eventhough you’ve said ‘NEVER DO IT AGAIN!!!’. The fix is to physically remove the dir with the info in. On a windows system go to ‘c:\program files\common files\adobe', there is a nasty little folder called UPDATER5 in there that you can DELETE! PROBLEM SOLVED 😉
Read More
Apache Cannot be Run. Another web server is using the web port or port is blocked by firewall.
October 20, 2009
Tried to start EasyPHP: “Apache Cannot be Run. Another web server is using the web port or port is blocked by firewall.” I was running Skype! And it was blocking the using the port. Check in options->advanced->connection for the setting on port 80. Another way to stop this from happening and solve the problem quicker is to go into the “Configuration->EasyPHP” [Ctrl+E] and make sure that the “Check server’s TCP port before starting” checkbox is not checked.
Read More
How to load xml into flash using actionscript 2
October 20, 2009
Create an xml object: var myXmlObject = new XML(); Perform action when xml file has been loaded: myXmlObject.onLoad = function(success) { if (success) trace("XML File has been read."); } Load the xml file into the object: myXmlObject.load("myXmlFile.xml");
Read More
TypeError: node is null message=node is null
October 20, 2009
The following error message occurs in Firefox 3 when using Firebug. TypeError: node is null message=node is null The error can be tracked back to script tags being in the head of the document instead of where they’re needed, an example would be with the ShareThis control/component that is often added to blogs and etc.
Read More
Cant start your browser?
October 20, 2009
Cant start your browser? Try checking if any torrent apps are running.. Close them and retry.
Read More
How to Temporarily Edit the Text of Any Website
October 20, 2009
Have you ever wanted to temporarily edit a webpage displayed in Chrome or another browser? How it works Let’s take a look at the Google homepage quickly. Now, after we apply our little “page hack”, let’s look at it again! How to temporarily edit a webpage Go to a website of your choice that you would like to edit. Enter the following javascript into the address bar: javascript:document.body.contentEditable="true"; document.designMode="on"; void 0
Read More
PHP __autoload function
October 20, 2009
When PHP encounters a class that hasn’t been defined yet, you can use __autoload to automatically add them instead of including masses of included at the top of your files. e.g. function __autoload($class_name) { require_once $class_name . '.php'; }
Read More
IE6 on Vista?
October 20, 2009
I find myself constantly fighting the microsoft battle of making things work in their browsers (thanks guys). On one of my machines I have Vista installed and needed to test a newly created site that apparently had some issues under Internet Explorer 6. HOWEVER, to my horror IE6 was unable to run on Vista. Once again, thanks Microsoft for making life difficult for everyone out there! After much grief, pain and agony with a million attempts to get it to run I stumbled upon a really great tool called IETester made by DebugBar.
Read More
Guillotine-Bug? Bug
October 20, 2009
Yes, it’s called a Guillotine-Bug and it’s yet another bug IE users get to look forward too 😛 So how does it work? Basically, the hasLayout messes around and elements become invisible and visible according to random things. Rather silly, but a bit of a bitch to initially figure out. So how do you fix it? Try this: in your css file add: * html .container {height: 1%;} .container:after { content: '.
Read More
Sending data from javascript to php
October 20, 2009
If you ever find yourself needing to do some ajax and in turn sending strings of characters via javascript then you should really try encodeURIComponent() to wrap your strings in. The function escape() can also be used, but I would not recommend it as encodeURIComponent() is better, it also escapes your usual ampersand ajax limiters which solved me quite a bit of pain.
Read More
What is Eb in firebug?
October 20, 2009
Gmail produces the following error/warning in firebug. Eb is not defined function Bb(a){if(a[sb]&&a[sb](daa)){var'ents)};f.x2b=c;f.B2b=b;f.y2b=a;return f} I initially started seeing this while while on clients’ websites, but can now say it’s a gmail thing. So don’t stress.. 😉
Read More
cross browser alpha css
October 20, 2009
.thediv { opacity:.80; filter:alpha(opacity=80); -moz-opacity:.80; }
Read More
Add TinyMCE code button
October 20, 2009
I had quite a few problems adding the htmlCode button to a fairly old copy of TinyMCE (I think around version 2.x). All is resolved now and this is what I had to change: Both changes are made in “editor_template.js” file, I also swopped the 2 files so that I could include and edit editor_template.js instead of the compressed “editor_template_src.js. Using the advanced theme I added the following line near the top of the file:
Read More
Runtime Error! (abnormal program termination) maya.exe
October 20, 2009
The Problem When starting Maya 8.5 an immediate error message and program termination. Runtime Error! Program C:\Program Filesz\Autodesk\Maya8.5\bin\maya.exe abnormal program termination Solution …
Read More
Need more than hover?
October 20, 2009
I had a hover effect on an html input element but also needed to have an active state. The css was like this for the inputs in mention: .contactformdiv input:hover, .contactformdiv textarea:hover { background-color:#fff; } It was simple, I just added a focus… .contactformdiv input:hover, .contactformdiv textarea:hover, .contactformdiv input:focus, .contactformdiv textarea:focus { background-color:#fff; }
Read More
Getting an internet connection under VirtualPC running Windows XP and Internet Explorer 7
October 20, 2009
Getting an internet connection under VirtualPC running Windows XP and Internet Explorer 7 Open the ‘settings’ of the virtual machine and select Networking -> then change Adapter1 to “Shared networking (NAT)” and it will use your local machine’s network settings.
Read More
Uppercase text in Actionscript
October 20, 2009
var lowerCase:String = "sample text"; var upperCase:String = lowerCase.toUpperCase();
Read More
Firefox too slow?
October 20, 2009
Is your Firefox starting to get realllllllly slow? Every few months my Firefox starts dragging, so all I do is create a new profile and reimport all my bookmarks and reinstall needed addons. For a rundown on how to create a new profile, click the following link.. http://kb.mozillazine.org/Profile_Manager
Read More
Uppercase the first character of each word in a string using PHP
October 20, 2009
You can use “ucwords()” to uppercase the first character of each word in a string. e.g. $myVar = 'this is a test!'; $myVar = ucwords($myVar); // This Is A Test!
Read More
Actionscript 3 equivalent of PHP’s print_r
October 20, 2009
A brilliant version of print_r for actionscript: http://dev.base86.com/solo/47/actionscript_3_equivalent_of_phps_printr.html
Read More
Global variables and functions in Actionscript 2
October 20, 2009
In order to reuse a variable from a different timeline within the same fla file you will need to register the inital variable or function as a _global. Todo this as a variable: _global.myString:String = "My String"; Todo this as a function: _global.myFunction = function() {}
Read More
Actionscript conflicting class name
October 20, 2009
I had a problem today where I got a flash source file from one of my developers’ and I couldnt compile it because it said that there was a conflicting class name, however, it turned out to just be a timestamp issue. Read here for more information http://www.epresenterplus.com/blog/archives/000030.html
Read More
expecting T_PAAMAYIM_NEKUDOTAYIM
October 20, 2009
What the hey? What does this mean? You may one day end up seeing the following error message produced by PHP and wonder to yourself: PHP Parse error: syntax error, unexpected ‘)’, expecting T_PAAMAYIM_NEKUDOTAYIM in ///File.php on line 160 You guessed it, “T_PAAMAYIM_NEKUDOTAYIM” is not english. It’s actually a Hebrew word meaning “unexpected” or “Twice Colon”. It happens when PHP tries to call the “::” (double colon) which is used when identifying an uninstantiated class’ method.
Read More