Showing posts with label problem solution. Show all posts
Showing posts with label problem solution. Show all posts

Saturday, 28 October 2023

Destructibility Unveiled: From Artifacts to Cosmos

Prelude:


The concept of destructibility is a universal and profound theme that touches both tangible and intangible dimensions of our existence. It reminds us of the inherent impermanence and transience not only of human-crafted artifacts but also of life itself. To delve deep into this concept, we embark on a journey that starts with exploring its philosophical roots. In particular, we draw inspiration from the Buddhist concept of "Anicca," which emphasizes the impermanence of all things. This prelude sets the stage for our exploration of destructibility, emphasizing its significance and relevance in both the world of human creations and the broader human experience.


Destructibility in Artifacts Forged by Humanity:


The concept of destructibility in human-crafted items is a multi-faceted one that warrants a closer look. At its core lies the motivation behind designing products and software with planned obsolescence or recyclability in mind. We delve into the intricacies of this design philosophy and consider its implications for the environment and sustainability. Of particular interest is the practice of designing commodities and software with recyclability in mind, incorporating sustainable design principles that encourage the use of recyclable or biodegradable materials in physical products. Shifting our focus to the software realm, we explore the concept of modular design, which allows for the reuse and recycling of software components, emerging as a key technique to create "destructible" software. By introducing these dimensions, our discussion broadens to encompass not only the end of an artifact's life but also its potential for renewal and repurposing through recycling practices.


Software and Destructibility:


In the digital age, the concept of destructibility extends to the realm of software development and management. This section uncovers the layers of this concept within the world of code and algorithms. We delve into the heart of software architecture and discuss the critical concept of IDisposable and resource management. It becomes clear that this is not merely a technicality but a pivotal aspect of creating "destructible" software. Efficient memory allocation and deallocation are paramount for the proper functioning of software and the prevention of memory leaks. Furthermore, we explore the techniques and best practices for designing software that is effectively "destructible." Such software can handle resources efficiently, minimizing memory leaks, optimizing performance, and enhancing system stability. We also consider the potential implications of indestructible software, which extend beyond degraded performance to encompass security vulnerabilities. By the end of this section, it becomes evident that the idea of software destructibility is not confined to technical discussions but extends its influence into the realms of security, stability, and, ultimately, user experience.


Philosophical Facets of Destructibility in Hinduism:


Within the context of Hinduism, the philosophical aspects of destructibility take on a profound and ancient character. Our journey through this philosophical realm centers on Lord Shiva, one of the most revered deities in Hinduism, celebrated as the harbinger of destruction and transformation. Within the Hindu Trinity of Brahma, Vishnu, and Shiva, it is Shiva's role to preside over the destruction and renewal of the universe. This section delves into Shiva's multifaceted character, unveiling his significance as both the annihilator and transformer. Shiva's destructive potency is not an act of wanton destruction but a means of rejuvenation and rebirth, symbolizing the cyclical nature of existence. The profound philosophy underlying Shiva's role invites us to contemplate the idea that destruction within Hinduism is not about mere annihilation but rather an integral part of a grand cosmic cycle.


Interconnections and Parallels:


Our exploration continues as we uncover the interconnections and striking parallels that exist between the concept of destructibility prevalent in human-crafted items and the philosophical essence of Shiva's destruction within Hinduism. The cyclical nature of destruction and creation in Hinduism resonates with the life cycle of human-made products and software. Furthermore, the idea of rebirth or renewal transcends both realms, drawing parallels between the transformative aspects of destruction in Hindu philosophy and the potential for innovation and progress in human creations. It is in these parallels that we find a unifying thread that transcends cultural and disciplinary boundaries, revealing that the concept of destructibility, in its essence, resonates with the human experience of transformation and renewal.


Challenges and Ethical Considerations:


While the concept of destructibility offers profound insights, it also presents important ethical and practical considerations. This section addresses these multifaceted dimensions. We delve into the ethical implications of planned obsolescence and the disposable culture, raising essential questions about sustainability and responsible consumption. The section also navigates through the potential conflicts that may arise between software destructibility and data privacy and security concerns. Technology's ever-expanding role in our lives brings forth significant ethical considerations, and this discussion takes them head-on. Moreover, we turn our attention to the ethical dimensions surrounding depictions of destruction in religious symbolism and their interpretation in modern contexts. As we contemplate these ethical facets, we encourage thoughtful reflection on the implications of destructibility in various domains, underlining the need for a balance between renewal and sustainability.


Epilogue:


Our exploration of destructibility reaches its conclusion in an epilogue that brings together the threads of our journey. It offers a concise summary of the key points discussed throughout the manuscript, highlighting the interconnectedness between destructibility within human-crafted artifacts, software development, and Hindu philosophy. As we ponder the insights gathered, the epilogue prompts readers to contemplate their own perspectives on destructibility, impermanence, and renewal, inviting them to explore the transformative power of these concepts in their own lives.


Future Trajectories:


As our journey through the realms of destructibility concludes, we look to the future and propose potential areas for further exploration. We encourage the pursuit of sustainable design practices that align with the ideals of recyclability and eco-friendliness. In the realm of software development, we advocate for innovative approaches that incorporate built-in destructibility to enhance user experiences. Additionally, we invite deeper philosophical investigations into the interplay between creation, destruction, and renewal in various cultural and religious contexts. These avenues of exploration promise to enrich our understanding of destructibility and its enduring significance in our ever-evolving world.


Destructibility and Transformation in the Cosmic Context:


The concept of destructibility and transformation is not limited to human-crafted artifacts or software; it extends to the universe as a whole. The cyclical nature of destruction and creation is a fundamental aspect of the cosmos, as evidenced by phenomena such as supernovas, black holes, and the Big Bang itself. In this expanded section, we delve into the concept of destructibility and transformation on a cosmic scale. We examine how the cycle of creation and destruction is a fundamental aspect of the universe's evolution, shaping the cosmos as we know it. We illustrate the cyclical nature of destruction and creation through examples of cosmic phenomena, such as the explosive death of stars in supernovas, the mysterious gravitational behemoths known as black holes, and the cataclysmic birth of the universe in the Big Bang. Philosophically, we ponder how this cosmic cycle reflects broader notions of impermanence, change, and renewal in the human experience. Additionally, we draw connections between these cosmic principles of destructibility and the Hindu concept of Lord Shiva's role as the god of destruction, unveiling profound insights into the alignment of these concepts on both cosmic and philosophical levels. By incorporating this cosmic dimension, we offer a more holistic perspective on the concept of destructibility, emphasizing its ubiquity and timeless significance in the grand narrative of our universe.



Tuesday, 16 August 2011

ConsistentHash implementation in C# 4.0

For those not familiar with ConsistentHash, start here: Consistent Hashing

The following is an attempt to implement the functionality using features of C# 3/4. I needed this functionality for the distributed cache project that I was working on (Available at HoC )

namespace HoC.Common
{
    public class ConsistentHash  : ICloneable
    {
        SortedList<string, string> itemCircle = new SortedList<string, string>();

        public string GetNearestItem(string key)
        {
            if (itemCircle.Count == 0)
                throw new ConsistentHashCircleEmpty();

            string keyHash = Hasher.GetHash(key);

            //find the last item that is just after the passed in key (clockwise)
            Func<KeyValuePair<string, string>, bool> stringCompare = x => (x.Key.CompareTo(keyHash) > 0);
            KeyValuePair<string, string> item = itemCircle.FirstOrDefault(stringCompare);

            if (string.IsNullOrEmpty(item.Key)) 
            {
                //if no item, fallback to the first item => traverse circle clockwise 
                return itemCircle.First().Value; 
            }

            return item.Value;
        }

        public void StoreItem(string item)
        {
            string hash = Hasher.GetHash(item);
            itemCircle[hash] = item;
        }

        public void RemoveItem(string item)
        {
            string hash = Hasher.GetHash(item);
            if (itemCircle.ContainsKey(hash))
                itemCircle.Remove(hash);
        }

        public string GetNextItemInCircle(string key)
        {
            return GetNearestItem(key);
        }

        //this function traverses anticlockwise, whereas GetNearestItem() traverses clockwise
        public string GetPreviousItemInCircle(string key)
        {
            if (itemCircle.Count == 0)
                throw new ConsistentHashCircleEmpty();

            string keyHash = Hasher.GetHash(key);

            //traverse, anticlock wise , find first item
            Func<KeyValuePair<string, string>, bool> stringCompare = x => (x.Key.CompareTo(keyHash) < 0);
            KeyValuePair<string, string> item = itemCircle.FirstOrDefault(stringCompare);

            if (string.IsNullOrEmpty(item.Key))
            {
                //if no item, fallback to the last item => traverse circle anti clockwise 
                return itemCircle.Last().Value;
            }

            return item.Value;
        }



        public object Clone()
        {
            return (ConsistentHash)MemberwiseClone();
        }
    }

    class ConsistentHashCircleEmpty : ApplicationException
    {

    }


}

Couple of drill downs:

1.) Basically each objects gets assigned a hash (Hasher class internally uses RIPEMD160Managed) so that it can be arranged in the circle and then gets stored to the internal circle. RIPEMD160Managed though a bit slower, supposedly has the lowest collision.

2.) The circle as seen is implemented using a SortedList list class - itemCircle

3.) The core functionality is implemented using the two methods:

3.1) GetNearestItem : This method traverses clockwise - basically find the object that comes up next in the sorted list after the given key.

3.2) GetPreviousItemInCircle : Opposite of GetNearestItem. Traverses anti-clockwise.

In the project that I use this internally, the objects are all serializable, hence the objects could be easily represented as a string.


Wednesday, 10 August 2011

Object Pool - Quick and Short in .NET 4.0

A simple object pool that could be used to maintain a set of objects readily available in memory, especially if you see that the object creation time is heavy. Eg:- creation of a MemoryStream on a need basis is typically time consuming in a server based app. In this case, it could best to have a set of MemoryStream objects readily available in memory. But, we definitely have to make sure to couple of things first :

1.) The way the object pool is filled happens is async.
2.) Access to a pool instance from the client app is thread safe.

To solve 1, we could exploit the AsyncMethodCaller together with its BeginInvoke(), while to make sure that the access to the pool is thread safe, we could check out the ConcurrentBag in .NET 4.0. So, where is the code?!

namespace HoC.Client
{
    /// <summary>
    /// maintains a pool/list of objects, provides it on request
    /// usually used for classes whose construction call is heavy
    /// </summary>
    /// <typeparam name="W"></typeparam>
    public class ObjectInstancePool<W>
    {
        private const int objectCount = 20; //can be updated to receive through the constructor
        private ConcurrentBag<W> objectList = new ConcurrentBag<W>();

        public ObjectInstancePool()
        {
            //refresh the bag first
            new AsyncMethodCaller(Filler).BeginInvoke(null, null);
        }

        public W GetInstance()
        {
            W result;

            if (!(objectList.TryTake(out result)))
            {
                result = Activator.CreateInstance<W>();
            }
            else
                new AsyncMethodCaller(Filler).BeginInvoke(null, null); //refresh the bag
            
            return result;
        }

        public delegate void AsyncMethodCaller();

        private void Filler()
        {
            while (objectList.Count < objectCount)
            {
                objectList.Add(Activator.CreateInstance<W>());
            }
        }
    }
}


I totally like it short and sweet :)



Tuesday, 23 March 2010

Setting Physical Memory Limit for a .NET application

We needed to limit the physical memory used by a .NET application as it was taking too much of it and the other apps appeared to be in a struggle mode.

The straightforward way appeared to use Process.GetCurrentProcess().MaxWorkingSet. Strangely, no matter what we tried, this never worked. Yet to figure out why it does not work - if anyone has a clue, please ping.

Anyways, looking at options we came across job objects in Windows that allow setting the max working set. So the approach that finally worked was this:

1.) Create a Job object using CreateJobObject() Win32 call

2.) Setup the memory limits against this job using
SetInformationJobObject()


3.) Assign our process to this job using AssignProcessToJob().

Now, when we look at the task manager, the physical memory assigned to this process never goes over the specified limit. All good.

Note that this is applicable only for the physical memory and not for the virtual memory - no limits can be set for this [?]. The physical memory limit is affected when the application is paged-in from the page file into the memory.

Thursday, 18 March 2010

Exploiting ObjectFromLresult() to get the IHTMLDocument2 from a window handle

Assume you have a window handle to a html control (which implements IHTMLDocument2) within a browser page (which is an IWebBrowser2), how would you access the HTML elements?

This is interesting as with just a window handle, it was relatively unknown on how that can be mapped to an object.

What you need to do is this:

1.) Register the windows message WM_HTML_GETOBJECT

2.) Send this message to the window handle we have in hand using a SendMessageTimeOut(). The out parameter in the lpdwResult returns you an UIntPtr to the object after the call.

3.) Next, use this out parameter as part of the ObjectFromLresult() call:
ObjectFromLresult(result from sendmessagetimeout, IHtmlDocument, 0)


4.) Cast the result from ObjectFromLresult() to IHTMLDocument2.

5.) Use the all property to get the HTML elements.

The powerfull function here definitely is the ObjectFromLResult() which effectively returns you an object that is 'accessible'. Accessible in terms of the user accessibility factor.

A framework worth checking out in this regard is the UIA framework that allows manipulating individual entities on the screen be it winforms, browser controls...

Saturday, 19 May 2007

The Jukebox Issue

Problem at hand
What we had in place was a jukebox system wherein the client application on user machines would request songs from the main play list on the server. The server would pick up the next song in this queue and play it using media player on the server machine. The sound output is directed to the music system such that everyone around could listen to the many songs requested by others.

Everything appeared to go well until the non-jukie fellows started complaining - they did not want to hear to these songs, usually a different language/dialect. The music system had to go :(

Requirement
Now how do we fix this problem ? Music enthusiasts needed to be able to listen songs requested by others from their individual machines, perhaps using the headphones such that the non-jukies are not bothered.

Solution
Instead of directing the output from mediaplayer to the music system, use windows media encoder 9 series on the juke box server machine. Windows media encoder could encode music coming out from the soundcard into a live stream.

We needed a Win2003 box with Windows Media Services 9 series installed (comes with SP2) which can broadcast streams. Once we have this, setup the windows media services to feed from the media encoder stream off the jukebox server. What is remaining is simple. Ask all our dear enthusiasts to use Windows media player to listen to the live stream off the 2003 box. This way, the enthusiasts listen to the songs requested by other enthusiasts without disturbing the non-jukies.

Peace reigns once again.