Archive

Archive for the ‘Uncategorized’ Category

Ecosystems and the myth of overpopulation

January 11th, 2023 No comments

This post is about a topic I am quite interested in, “triggered” by a post by the Copenhagen Institute for Future Studies discussing, contrary to what is mainstream now, the question of whether causal relationship between population growth and biodiversity decline exists or if discourse surrounding supposed ‘overpopulation’ actually do more harm than good?

While I wish the interview linked to in the referenced post went a bit deeper exploring the topic, it is high time that other voices bring this to the fore. The (disproved) Malthusian anti-human speech from the supposedly ecologist leftist mainstream is an entrenched meme of the political Zeitgeist, but the bidirectional relationship between population, especially population in rural areas, and biodiversity has not been paid any attention, probably as it does not fit the underlying goals of said mainstream and their ultimate goals.

General population decline and increasing concentration of that declining population in just a few cities in each country hurt the long term prospects of agricultural and livestock farming (non-industrial) activities but the preservation of rural ecosystems is in symbiosis with those activities. During electioneering cycles much lip service is paid by governments and institutions to this loss of rural population (not so much to the general population decline and skewed population pyramids, since the Ehrlich-like ideas still permeates their thinking) but not a lot seems to be actually being done.

As the article says, “we need to do is find out how we can sustain that transition to higher quality lifestyles without massively increasing the rate of consumption. A myopic focus on population control will not get us there.” Paradoxically forcing people to concentrate in a few cities probably leads to worse consumption patterns, like importing foods from further places, loss of quality of life, cultural heritage loss and so on.

The abandonment of said economic activities means a greater depopulation in large economically marginal spaces that will make it difficult to manage new extensive forest masses created naturally or by reforestation, which brings a growing virulence of forest fires we see during Summer in South Europe, leading to greater desertification. This is a vicious feedback loop which accelerates rural population loss and abandonment of large areas of land, a problem especially notable in places like Spain. Crop abandonment means that local food is also no longer produced and the countryside is left to waste with no proper management (wildfires again).

This situation leads to a kind of rural desertification caused by the break of an ecosystem that had been in place for years, maybe even centuries. Such changes also affect the local fauna already adapted to that ecosystem.

Efforts for vegetation recovery is costly in terms of economic investment, which will only be amortized in the longer term if there are incentives and economic activities that ensure its protection and viability. Even if publicly funded, you need to tax that capital first, and for that you need a productive economy, which can only be made to work by a non-declining population with enough younger people that will become eventual producers and consumers for services and products. I’d argue we need more people, not less, to not only keep our current economic systems running as well as our wealth and welfare levels, but also to improve and innovate on them, as mentioned by the article. Less people ultimately means less economic incentives for investment as there is less market for good and services. Therefore, not only depopulation but also deindustrialization, some sort of undefined rollback.

It is an uncomfortable fact that only richer societies can afford the luxury of taking good care of their environment.

Musings on the use of ChatGPT for developers

December 28th, 2022 No comments

 

On the use of ChatGPT in software development

[ Disclaimer: part of this content was generated with the help of ChatGPT for some meta- oomph as the result of several prompts but also heavily sanity-checked, edited and expanded by a human with the (at least some) relevant expertise. ]

As a software engineer, you can use ChatGPT in a variety of ways, including:

  1. Code generation: generate code snippets or entire basic programs based on a set of input parameters or requirements.
  2. Documentation: help generate documentation for your code, including API reference materials and technical guides. You can use ChatGPT to generate code documentation by providing it with a prompt that describes the code that you want to document and the information that you want to include in the documentation. ChatGPT will then generate text that is designed to explain the code and provide context for other developers who may be reading the documentation.
  3. Debugging assistance: help debug code by providing suggestions for potential solutions to errors or issues that you encounter.
  4. Collaboration: to facilitate communication and collaboration with your team by generating responses to messages or questions in real-time.
  5. Learning and exploration: to explore new programming concepts or other topics by asking it questions and receiving explanations and examples in return.

It’s important to note that ChatGPT is a tool and, like any tool, it should be used responsibly and in the context of a larger workflow. It is not a replacement for human expertise or judgment, and it should not be relied upon to make critical decisions or solve complex problems without proper oversight and review. More on this later in this article.

As the disclaimer in this page says, you need to not blindly trust the output of such tools, they are an aid that can certainly scale your productivity and even the quality of your output if properly used. However, you need to exert the same precautions that apply when copying code and solutions from sites like Stack Overflow or any similar advice and content from the internet.

 

Code Generation

Again, this won’t give you production code, but if you provide descriptive enough prompts, you can start from a good start already.

Take this prompt for example Generate for me a C# controller with Create, Read, Update and Delete methods with XML documentation in .Net format that takes a SiteInspection Data Transfer Object as well as Auditor information and implements a Respository patter with Dapper to write and read from the database. and ChatGPT generates this example below for us.

using Dapper;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
 
namespace SiteInspectionApp.Controllers {
    /// <summary>
    /// This controller handles CRUD (Create, Read, Update, Delete) operations for site inspection records using the repository pattern and Dapper to access the database.
    /// </summary>
    public class SiteInspectionController: Controller {
        private readonly string _connectionString;
 
        public SiteInspectionController(string connectionString) {
          _connectionString = connectionString;
        }
 
        /// <summary>
        /// Creates a new site inspection record.
        /// </summary>
        /// <param name="siteInspection">A DTO (Data Transfer Object) containing information about the site inspection, including the location, date, and notes.</param>
        /// <param name="auditor">A DTO containing information about the auditor conducting the site inspection, including their name and credentials.</param>
        [HttpPost]
        public void Create(SiteInspection siteInspection, Auditor auditor) {
          using(var connection = new SqlConnection(_connectionString)) {
            connection.Open();
            connection.Execute(
              "INSERT INTO SiteInspections (Location, Date, Notes, AuditorName, AuditorCredentials) " +
              "VALUES (@Location, @Date, @Notes, @AuditorName, @AuditorCredentials)",
              new {
                siteInspection.Location,
                  siteInspection.Date,
                  siteInspection.Notes,
                  auditor.Name,
                  auditor.Credentials
              });
          }
        }
 
        /// <summary>
        /// Retrieves a site inspection record.
        /// </summary>
        /// <param name="id">The ID of the site inspection record to retrieve.</param>
        /// <returns>A DTO containing the site inspection information, or a 404 error if the record was not found.</returns>
        [HttpGet]
        public IActionResult Read(int id) {
          using(var connection = new SqlConnection(_connectionString)) {
            connection.Open();
            SiteInspection siteInspection = connection.QueryFirstOrDefault < SiteInspection > (
              "SELECT * FROM SiteInspections WHERE Id = @Id",
              new {
                Id = id
              });
            if (siteInspection != null) {
              return Ok(siteInspection);
            } else {
              return NotFound();
            }
          }
        }
 
        /// <summary>
        /// Updates an existing site inspection record.
        /// </summary>
        /// <param name="siteInspection">A DTO containing the updated site inspection information.</param>
        [HttpPut]
        public void Update(SiteInspection siteInspection) {
          using(var connection = new SqlConnection(_connectionString)) {
            connection.Open();
            connection.Execute(
              "UPDATE SiteInspections SET Location = @Location, Date = @Date, Notes = @Notes " +
              "WHERE Id = @Id",
              siteInspection);
          }
        }

 

You be the judge of this code looks and feels, or what things are missing, such as for example validating the models or more robust error and response handling, as well as the security and secure coding angle. That being said, generating code like this is quite a help if you need something quick and dirty, for testing something, or for some little tool you will use yourself and then throw away.

 

Generating unit tests

 

Unit tests also tend to be overlooked, and writing lots of them can feel repetitive (albeit there is a dopamine effect to seeing all of those little green balls when all tests assert correctly). ChatGPT can help you with this.

For a prompt that builds on the previous example, Generate for me the unit tests for a C# controller with Create, Read, Update and Delete methods that takes a SiteInspection Data Transfer Object as well as Auditor information and implements a Respository pattern. The repository must be an injected dependency that can be mocked from the unit tests. we get something like

 

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
 
namespace MyProject.Tests {
  [TestClass]
  public class SiteInspectionControllerTests {
    private Mock < ISiteInspectionRepository > mockRepository;
    private SiteInspectionController controller;
 
    [TestInitialize]
    public void Setup() {
      mockRepository = new Mock < ISiteInspectionRepository > ();
      controller = new SiteInspectionController(mockRepository.Object);
    }
 
    [TestMethod]
    public void TestCreateSiteInspection() {
      // Arrange
      SiteInspectionDTO siteInspection = new SiteInspectionDTO {
        Id = 1,
          Date = DateTime.Now,
          Location = "Test Location",
          Auditor = "Test Auditor"
      };
 
      // Act
      controller.Create(siteInspection);
 
      // Assert
      mockRepository.Verify(repo => repo.Create(siteInspection), Times.Once());
    }
 
    [TestMethod]
    public void TestReadSiteInspection() {
      // Arrange
      int id = 1;
      SiteInspectionDTO expectedSiteInspection = new SiteInspectionDTO {
        Id = id,
          Date = DateTime.Now,
          Location = "Test Location",
          Auditor = "Test Auditor"
      };
 
      mockRepository.Setup(repo => repo.Read(id)).Returns(expectedSiteInspection);
 
      // Act
      SiteInspectionDTO actualSiteInspection = controller.Read(id);
 
      // Assert
      Assert.AreEqual(expectedSiteInspection, actualSiteInspection);
    }
 
    [TestMethod]
    public void TestUpdateSiteInspection() {
      // Arrange
      SiteInspectionDTO siteInspection = new SiteInspectionDTO {
        Id = 1,
          Date = DateTime.Now,
          Location = "Test Location",
          Auditor = "Test Auditor"
      };
 
      // Act
      controller.Update(siteInspection);
 
      // Assert
      mockRepository.Verify(repo => repo.Update(siteInspection), Times.Once());
 
    }
 
    [TestMethod]
    public void TestDeleteSiteInspection() {
      // Arrange
      int id = 1;
      // Act
      controller.Delete(id);
 
      // Assert
      mockRepository.Verify(repo => repo.Delete(id), Times.Once());
    }
  }
}

 

Provide an example of a XUnit test that tests for a custom SiteInspectionExpection type. The test passes when the exception is thrown by the system under test.

using System;
using Xunit;
 
namespace MyProject.Tests {
  public class SiteInspectionTests {
    [Fact]
    public void TestSiteInspectionException() {
      // Arrange
      var systemUnderTest = new SystemUnderTest();
      // Act and Assert
      Assert.Throws < SiteInspectionException > (() => systemUnderTest.MethodThatThrowsSiteInspectionException());
    }
  }
}

 

Generating documentation

Few developers want to write good documentation, it is time consuming and perceived and not fun, even when it is a critical part of the SDLC workflow, either if you are writing code for others to use, or simply a LoB application that you will have to maintain later on.

Using ChatGPT you can generate snippets such as this below that you can take as a start for Markdown readmes and documentations for your project. This can be an aid when creating Azure DevOps wikis or GitHub documentation for a repo.

 

## SiteInspectionController
 
This controller is responsible for handling requests related to site inspections.
 
### Input
 
- `siteInspection`: A SiteInspection DTO object containing information about the site inspection
 
- `auditor`: An AuditorDTO object containing information about the auditor who conducted the inspection
 
### Output
 
- HTTP status code 200 (OK) if the site inspection is successfully recorded
 
- HTTP status code 400 (Bad Request) if the request is invalid or missing required parameters
 
- HTTP status code 401 (Unauthorized) if the request is not authenticated
 
- HTTP status code 403 (Forbidden) if the user does not have permission to perform the requested action

 

public async Task < IActionResult > RecordSiteInspection(SiteInspectionDTO siteInspection, AuditorDTO auditor) {
  // Validate the request and perform authentication/authorization checks
  if (!ModelState.IsValid || !IsAuthenticated || !IsAuthorized) {
    return BadRequest();
  }
 
  // Record the site inspection
  try {
    await _siteInspectionService.RecordSiteInspection(siteInspection, auditor);
    return Ok();
  } catch (Exception) {
    return StatusCode(500);
  }
}

 

Or for example, with this prompt Generate documentation in XML .net format for a C# MVC controller that takes a SiteInspection DTO, an AuditorDTO and can return common http status codes such as 200 or 400 you can get this output, which can be handy to generate stubs of the XML comments in .Net format.

The implementation is obviously a placeholder basically, but in this case we were more interested in saving some time writing documentation.

 

using Microsoft.AspNetCore.Mvc;
 
namespace SiteInspectionApp.Controllers {
 
  /// <summary>
  /// This controller handles requests for creating and retrieving site inspection records.
  /// </summary>
  public class SiteInspectionController: Controller {
 
    /// <summary>
    /// Creates a new site inspection record.
    /// </summary>
    /// <param name="siteInspection">A DTO (Data Transfer Object) containing information about the site inspection, including the location, date, and notes.</param>
    /// <param name="auditor">A DTO containing information about the auditor conducting the site inspection, including their name and credentials.</param>
    /// <returns>An <see cref="OkResult"/> if the site inspection was successfully created, or a <see cref="BadRequestResult"/> if the request was invalid or there was a problem with the provided data.</returns>
 
    [HttpPost]
    public ActionResult Create(SiteInspection siteInspection, Auditor auditor) {
      if (ModelState.IsValid) {
        // Save the site inspection and auditor information to the database
        return Ok();
      } else {
        return BadRequest();
      }
    }
 
    /// <summary>
    /// Retrieves a site inspection record.
    /// </summary>
    /// <param name="id">The ID of the site inspection record to retrieve.</param>
    /// <returns>An <see cref="OkObjectResult"/> containing the site inspection information, or a <see cref="NotFoundResult"/> if the record was not found.</returns>
    [HttpGet]
    public ActionResult Get(int id) {
      // Retrieve the site inspection with the specified ID from the database
      SiteInspection siteInspection = _siteInspectionRepository.GetById(id);
      if (siteInspection != null) {
        return Ok(siteInspection);
      } else {
        return NotFound();
      }
    }
  }
}  

 

Learning

Perhaps this is more similar to Googling for things and find good content that provides a good answer to your query. Learning does not necessarily have to be for purely technical things, you could also explore topics that a bit more exotic. Let’s go with some less technical for this

 

What are good meditation techniques for software developers?

Meditation can be a helpful practice for software developers to manage stress, improve focus and concentration, and increase overall well-being. Here are a few meditation techniques that may be particularly beneficial for software developers:

– Focus meditation: This type of meditation involves focusing your attention on a single object or sensation, such as your breath or a mantra, and letting go of distracting thoughts as they arise. This can help improve concentration and clarity of mind. – Body scan meditation: In this practice, you lie down or sit comfortably and focus on each part of your body, tensing and relaxing each muscle group in turn. This can help reduce stress and increase relaxation. – Loving-kindness meditation: This involves silently repeating phrases of love and compassion to yourself and others. This can help increase feelings of connection and reduce stress and anxiety. – Transcendental meditation: This involves repeating a mantra or word in a specific way, typically for 20 minutes twice a day. This can help reduce stress, improve focus, and increase overall well-being.

It’s important to find a meditation technique that works for you and to be consistent in your practice. It may take some time to see the benefits of meditation, so it’s important to be patient and stick with it.

Your mileage might vary with this one 🙂

 

 

Caveats

Stanford University researched have published an interesting paper titled “Do users write more insecure code with AI assistants?“ which explores the problems these AI tools can introduce if blindly trusted and when human judgement and supervision abdicates shifting the burden to the tool almost exclusively, as mentioned here previously “AI assistants have the potential to decrease user pro-activeness to carefully search
for API and safe implement details in library documentation directly
“.

Not only that, this paper also shows that the output of these tools varies a lot with the quality and parameters of the prompts given by the user (called temperature) and that less experienced users tend to accept and trust the output and generated code in a less questioning way.

The paper seeks not to demonstrate whether AI assistants generate “buggy code”, which we already know they do – at least for now -, but whether using them causes programmers to be less diligent and allow the introduction of bugs, errors, insecure code, etc. as opposed to programmers who they don’t use them. For 5 experiments, the secure code generated by programmers not using AI assistants was 79% while that of programmers with AI assistant was 67%. “participants with access to an AI assistant often produced more security vulnerabilities than those without access, with particularly significant results for string encryption and SQL injection“. With this, the study incidentally demonstrate too that classic vulnerabilities like the simplest forms of SQL injection are still not widely understood and make it to the final code too frequently.

In sum, the results suggest that while AI code assistants may significantly lower the barrier of entry for non-programmers and increase developer productivity, they may provide less experienced users a false sense of security, be it in programming or in any other area where the user can be fed incorrect output that they are not prepared to detect and fix or discard accordingly.

On the other hand, these revolutionary tools are still in their infancy, and they will probably reach – and then perhaps surpass – human expert parity soon, and that will be when these tools become exponential multipliers of human capacity and productivity.

 

Conclusion

A powerful tool that can yield benefits if used correctly, but that does not automatically produce the best code or the one that you need in a particular scenario. Still, the scaffolding and support it brings to the overall workflow can be a bonus for productivity.

Be aware that the model may produce correct sounding but incorrect answers. That’s because the model itself has no true inherent understanding of code, but rather know what correct code “looks like” for the prompt and based on the model it has been trained with, which includes all of Stack Overflow (I hope some curation took place there) and GitHub.

Being as precise as possible with your prompts is required for the highest probability of a “correct answer”, or at least for a good quality one.

The more context there is around your code, the less it can offer you a fitting “solution” or provide code that you need.

Apart from the mere writing of code, it can also be a good source of at least inspiration to get ideas and solve problems.

  • Use it for debugging. You can provide a small piece of code and perhaps it can come with an idea that gives you a solution or a new way of looking at the problem.
  • Get architectural and infrastructure options.
  • Write test cases and documentation, like we saw, to save some time.
  • Learn about implementation options or common design patterns by asking it to provide examples

Some prompts I tried, but did not check for correctness shown below. You can try questions like these, or variations thereof, to get a better idea of what the system can come up with.

  • Generate a yaml pipeline that builds a dockerized image of a To Do List API in GO and deploys the image to an Azure Function
  • Provide a canonical implementation of the Visitor Pattern in C# (or your language of choice)
  • Why should I not use PHP in mission critical applications?
  • What is wrong with this SQL code? (you provide the example, but bear in mind the caveats mentioned)

 

Categories: Uncategorized Tags:

Review of Exponential Organizations

June 27th, 2017 No comments

Cover of Exponential Organizations

Some say that the Singularity University is science fiction expensively packaged for execs, but even if one always needs to take grandiose claims and hyped inventions-to-be (or never-to-be) with a grain of salt and some skepticism, this is still a book anybody with an interest in innovation and technology should read. It is an enjoyable read and there is plenty of good ideas in the book, although these are not fleshed out in enought detail to make them actionable advice.

One of the most important points is the Massive Transformative Purpose (MTP), which is more than a vision or mission statement. This core idea has to be stated clearly in few words, but it has to be compelling enough to inspire the initial people, smart enough to nurture a community as it grows, and audacious enough to give plenty of room for growth.

Other key points from the book are the notions of SCALE and IDEAS:

S: staff on demand
C: community & crowd
A: algorithms
L: leveraged assets
E: engagement

I: interfaces
D: dashboards
E: experimentation
A: autonomy
S: social technologies

As a somewhat negative point, it necessarily has to take from the same examples as everyone else ( Uber, AirB&B, Twitter, GitHub, Local Motors, SnapChat, FaceBook etc) and in that sense it is too mainstream. It would have been nice to look at minor players making an impact in more significant areas, because, honestly, SnapChat does not really have an MTP.

If you like the Lean Start up approach, this book looks at some of the same ideas. It has some really interesting insights into how larger organisations can create, invest in, develop businesses that are free to grow and change without the constraints of the larger parent company. Gives great rules/guidelines for how to setup a business that could grow quickly, not so much from an actionable advice angle, but more from the inspirational outlook and the potential of great bold ideas.

My own copy is heavily underlined and annotated, but I leave here a list of quotes other readers have taken the trouble to put together in a list.

 

Categories: Uncategorized Tags: