Monday, June 25, 2018

tslint, detecting and fixing all tslint issues from a TypeScript project

A lot of people are using Visual Studio Code to work with TypeScript and are getting annoyed by tslint warnings. TSLint is a piece of software that statically checks your code to find issues with how you wrote it. And at first one tries to fix the warnings, but since you already started on an existing project or template, there are a lot of warnings and you have work to do. Even worse, the warnings appear only when you open a file, so you think you're done until you start working in another area and you get red all over your project file. It's annoying! Therefore a lot of people just disable tslint.

But what if there was a way to check all the linting errors in your entire code? Even better, what if there were some magical way of fixing everything that can be fixed? Well, both of these exist. Assuming you have installed tslint globally (npm install tslint -g) you have these two commands to check and fix, respectively, all the errors in the current project:

tslint "src/**/*.ts?(x)" >lint_result
tslint "src/**/*.ts?(x)" --fix >fix_result

Note the src part, which tells tslint to look in the src folder and not in node_modules :-). If you prefer a more unsafe version that checks everything in the current directory, just replace src with a dot.

The fix option is only available from TSLint 4.0.

Monday, June 18, 2018

Good in Bed Guide to Female Orgasms, by Emily Nagoski

book cover Female Orgasms is not so much as a book, as a really tiny set of chapters that are barely connected to each other. Emily Nagoski is frustrated by the way male standards are used to judge all sexuality and makes a point in this booklet that it is unhelpful, at best. However, while some of the ideas in the book are interesting, to me it seemed as a list of ideas and ramblings gathered together in order to form a volume, with most of the things either really basic or without any narrative or connection to others. 100 ebook pages and 26 chapters, that's saying something.

The book is oriented towards women, with men as a secondary audience. It is not a self-help book for men to become gods in bed, it is a self-help book for women on how to become more aware of their sexuality and enjoy themselves better. Some of the ideas I found interesting are mostly related to expectations. If we know 95% of women masturbate with clitoral stimulation, why do we even consider the necessity for women to orgasm from vaginal intercourse? It's nice when it happens, but as opposed to men, women don't orgasm predictably nor is the orgasm the end purpose of sexual encounter. Another interesting fact is that women are mostly responsive to erotic stimulation, as opposed to men who just wake up one moment wanting to have sex. It's a statistical fact, but still, one to take into consideration. One idea that the author wanted to make clear is that there is only one orgasm: the explosive release of sexual tension. How that tension is generated doesn’t matter (to the orgasm).

An important concept that Nagoski is making efforts to popularize is the one of arousal nonconcordance. In other words, while for men there is a strong correlation between physical sexual arousal and the desire or openness for sex, for women it's not quite so. Experiments of people watching porn while devices compare their sexual arousal and also take their reported input of how aroused they feel show consistently this is true. I do feel, though, that the author pushes a little too far, attempting to completely decouple the declarative and physical arousal. Considering some men use opposing ideas as justification for non consensual sex ("your body wants it, so you must want it" kind of logic) that is understandable, but less scientific than I would have liked.

This book is part of a series about sexuality, written by different authors, called Good in Bed Guide. I found it basic, but probably helpful for a lot of people. I wish it would have been better written and edited, though. Also, try reading this on the subway with a straight face.

Friday, June 15, 2018

Do NOT delete the files in Windows\WinSxS

There is a folder that appears to be quite big when you analyze your drive: Windows\WinSxS. It reports many gigabytes of files. If you are low on space, you might be tempted to delete it. The problem is that the folder is full of hard links to files that are already stored in other places. In order to determine the true size of the folder, run this command with elevated privileges:
dism /online /cleanup-image /analyzecomponentstore
the output looks like this:
Deployment Image Servicing and Management tool
Version: 10.0.16299.15

Image Version: 10.0.16299.309

[===========================99.1%========================= ]

Component Store (WinSxS) information:

Windows Explorer Reported Size of Component Store : 7.03 GB

Actual Size of Component Store : 6.94 GB

    Shared with Windows : 6.06 GB
    Backups and Disabled Features : 687.18 MB
    Cache and Temporary Data : 194.21 MB

Date of Last Cleanup : 2018-06-15 01:02:45

Number of Reclaimable Packages : 0
Component Store Cleanup Recommended : No

The operation completed successfully.
The actual size used is the one in bold: 687.18 MB.

Deleting the folder or the files inside it will break your machine. Moving the files and copying them back will delete the hard links (freeing no space) then copy actual files instead, wreaking havoc with your system.

JSON.stringify with circular references and nicely indented

Sometimes you want to display a Javascript object as a string and when you use JSON.stringify you get an error: Converting circular structure to JSON. The solution is to use a function that keeps a record of objects found and returns a text explaining where the circular reference appeared. Here is a simple function like that:
function fixCircularReferences() {
  const defs={};
  return (k,v) => {
    const def = defs[v];
    if (def && typeof(v) == 'object') return '['+k+' is the same as '+def+']';
    defs[v]=k;
    return v;
  }
}

And the usage is
JSON.stringify(someObject,fixCircularReferences(),2);
. If you want to use it as a JSON (so serialize the object for real), replace the return of a string with
return null
, although that means you have not properly serialized the initial object.

The function is something I cropped up in a minute or so. If there are some edge cases where it didn't work, let me know and I will update it.

Thursday, June 14, 2018

Async/await world: casting an async method to Action irrevocably loses the awaitability

My colleague showed me today something that I found interesting. It involves (sometimes unwittingly) casting an awaitable method to Action. In my opinion, the cast itself should now work. After all, an awaitable method is a Func<Task> which should not be castable to Action. Or is it? Let's look at some code:
var method = async () => { await Task.Delay(1000); };
This does not work, as compilation fails with Error CS0815 Cannot assign lambda expression to an implicitly-typed variable, which means we need to set the type explicitly. But what is it? It receives no parameter and returns nothing. So it must be an Action, right? But it is also an async/await method, which means it's a Func<Task>. Let's try something else:
Task.Run(async () => { await Task.Delay(1000); });
This compiles. If we hover or go to implementation for the Task.Run method, we reach the public static Task Run(Func<Task> function); signature. So that does it, right? It IS a Func<Task>! Let's try something else, though.
Action action = async() => { await Task.Delay(1000); };
Task.Run(action);
This compiles again! So it IS an Action, too!

What is my point, though? Consider you would want to create a method that receives an Action as a parameter. You want something done, then to execute the function, something like this:
public void ExecuteWithLog(Action action)
{
    Console.WriteLine("Start");
    action();
    Console.WriteLine("End");
}

And then you want to use it like this:
ExecuteWithLog(async () => {
    Console.WriteLine("Start delay");
    await Task.Delay(1000);
    Console.WriteLine("End delay");
});

The output will be:
Start
Start delay
End
End delay
There is NO WAY of awaiting the original method in the ExecuteWithLog method, as it is received as an Action, and while it waits for a second, execution returns to ExecuteWithLog immediately. Write the method like this:
public async void ExecuteWithLog(Func<Task> action)
{
    Console.WriteLine("Start");
    await action();
    Console.WriteLine("End");
}
and now the output is as expected:
Start
Start delay
End delay
End

Why does this happen? Well, as mentioned above, you start with an Action, then you need to await some method (because now everybody NEEDS to use await/async), and then you get an error that your method is not marked with async. Now it's suddenly something else, not an Action anymore. Perhaps that would be annoying, but this ambiguity in defining what an anonymous async parameterless void method is worse.

The Unholy Consult (The Aspect-Emperor #4), by R. Scott Bakker

book cover What the hell?! After starting with so much potential, the story started fizzling, but there still was a lot of room for greatness. Instead, Bakker seems to have contracted Martinitis for his last book in the series, having important characters die off randomly, insignificant ones suddenly pop up, and filling space with feudal descriptions of the battles fought by completely irrelevant characters. Oh, and talking about erect penises. And then the end comes, everything seems to come to some sort of confluence, only it actually doesn't. It all goes completely to the left. Things get confused, the story goes nowhere, and the reader goes to WTF land for the entire day.

What is the purpose of having the reader getting invested in characters, only to kill them off, then return them later on (oh, they didn't die!), only to have them do nothing or die (again!)? What is the point of reading the names of every leader of men and no-men while they battle gloriously, complete with a short description of these characters right before they die in said battle? Was this book written with dice?

The Unholy Consult is a complete disappointment of a series finale. It ends practically nothing! Consider that it all started with Drusas Achamian, as a learned, in love, slightly damaged magus who liked to consider the world with wisdom. At the end, he is a bumbling old buffoon who can't string a thought in his head. Esmenet, the ex-prostitute, chosen by Achamian for her beauty and by the Emperor for her intellect and strength for bearing his children, first rises to the challenge of being a queen, then is just hauled away like a child and just does random things. Mimara gives birth to twins. But one is dead. There is no significance to this at all, it's just a random event. The four horns... they appear and disappear in the plot, like they have some great significance, but they don't. Why write about one character almost a quarter of a book only to kill him randomly in the next? Why be so verbose for 95% of a book only to break out into incoherent scenes and inconsistent actions in the last tiny chapter?! And it goes on and on like that. There is no moral to the story, no resolution to the fact that we followed the action of a psychopath for twenty years of book time waiting for this precise ending, only to be robbed of any meaningful closure.

Bottom line: I guess the author has a "great vision" in mind. If Prince of Nothing was followed by The Aspect Emperor, then a new series of books follows which is, in fact, another volume of the story. Only I lost all interest. What is the point in following characters if the author is going to butcher them (and I don't mean kill them off) later on to the point of irrelevancy? What is the point of following a story, if it leads to nothing?

Tuesday, June 12, 2018

Saturday, June 09, 2018

Hagane no renkinjutsushi: Mirosu no seinaru hoshi (2011)

Fullmetal Alchemist: The Sacred Star of Milos is the film that banks on the hunger of Alchemists all over the world after the Brotherhood series ended. It is not a sequel, just a full feature film happening sometime around the 21st episode of the series. The story is complicated: three nations in turmoils, alchemy of all sorts, chimeras and in the middle of it all: Ed and Al, fighting for what is right.

I liked the story, it hit a lot of sour points of the present, with large nations literally shitting on smaller ones, while they can only maintain their dignity by hanging on old myths that give them moral rights over some God forsaken territory. What I didn't particularly enjoy were the characters and the details of the plot. There were many holes and, in all, no sympathetic characters. The few promising ones were only barely sketched, while the main ones were kind of dull. The animation also felt lazy. If this was supposed to be a send off for the characters, it exceeded its purpose, as now I am considering if I would have even enjoyed a series made in such a lazy way.

So, bottom line, part cash grab, part great concept. A promising film that reminded me of the series I loved so much a decade ago, but failed to rekindle the hunger I felt when the series ended. Goodbye, Elric brothers!

Thursday, June 07, 2018

Easy and free unit test coverage reporting for .NET projects without having to buy Visual Studio Enterprise

Visual Studio has a nice little feature called Code Coverage Results, which you can find in the Test menu. However, it does absolutely nothing unless you have the Enterprise edition. If you have it, then probably this post is not for you.

How can we test unit test coverage on .NET projects without spending a ton of money?

I have first tried AxoCover, which is a quick install from NuGet. However, while it looks like it does the job, it requires xUnit 2.2.0 and the developer doesn't have the resources to upgrade the extension to the latest xUnit version (which in my case is 2.3.1). In case you don't use xUnit, AxoCover looks like a good solution.

Then I tried OpenCover, which is what AxoCover uses in the background anyway, which is a library that is suspiciously showing in the Visual Studio Manage NuGet Packages as published in Monday, February 8, 2016 (2/8/2016). However, the latest commits on the GitHub site are from April, only three months ago, which means the library is still being maintained. Unfortunately OpenCover doesn't have any graphical interface. This is where ReportGenerator comes in and some batch file coding :)

Bottom line, these are the steps that you need to go through to enable code coverage reporting on your projects:
  1. install the latest version of OpenCover in your unit test project
  2. install the latest version of ReportGenerator in your unit test project
  3. create a folder in your project root called _coverage (or whatever)
  4. add a new batch file in this folder containing the code to run OpenCover, then ReportGenerator. Below I will publish the code for xUnit
  5. run the batch file

Batch file to run coverage and generate a report for xUnit tests:
@echo off
setlocal EnableDelayedExpansion
 
for /d %%f in (..\..\packages\*.*) do (
    set name=%%f
    set name="!name:~15!"
    if "!name:~1,9!" equ "OpenCover" (
        set opencover=%%f
    )
    if "!name:~1,15!" equ "ReportGenerator" (
        set reportgenerator=%%f
    )
    if "!name:~1,20!" equ "xunit.runner.console" (
        set xrunner=%%f
    )
)
SET errorlevel=0
if "!opencover!" equ "" (
    echo OpenCover not found in ..\..\packages !
    SET errorlevel=1
) else (
    echo Found OpenCover at !opencover!
)
if "!reportgenerator!" equ "" (
    echo ReportGenerator not found in ..\..\packages !
    SET errorlevel=1
) else (
    echo Found ReportGenerator at !reportgenerator!
)
if "!xrunner!" equ "" (
    SET errorlevel=1
    echo xunit.runner.console not found in ..\..\packages !
) else (
    echo Found xunit.runner.console at !xrunner!
)
if %errorlevel% neq 0 exit /b %errorlevel%
 
set cmdCoverage="!opencover:\=\\!\\tools\\opencover.console -register:user -output:coverage.xml -target:\"!xrunner:\=\\!\\tools\\net452\\xunit.console.exe\" \"-targetargs: ..\\bin\\x64\\Debug\\MYPROJECT.Tests.dll -noshadow -parallel none\" \"-filter:+[MYPROJECT.*]* -[MYPROJECT.Tests]* -[MYPROJECT.IntegrationTests]*\" | tee coverage_output.txt"
set cmdReport="!reportgenerator:\=\\!\\tools\\reportgenerator -reports:coverage.xml -targetdir:.\\html"
 
powershell "!cmdCoverage!"
powershell "!cmdReport!"
start "MYPROJECT test coverage" .\html\index.htm

Notes:
  • replace MYPROJECT with your project name
  • the filter says that I want to calculate the coverage for all the assemblies starting with MYPROJECT, but not Tests and IntegrationTests
  • most of the code above is used to find the OpenCover, ReportGenerator and xunit.runner.console folders in the NuGet packages folder
  • powershell is used to execute the command strings and for the tee command, which displays on the console while also writing to a file
  • the little square characters are Escape characters defining ANSI sequences for showing a red text in case of error.

Please feel free to comment with the lines you would use for other unit testing frameworks, I will update the post.

.NET Framework assemblies can be called from .NET Core ?!

I was under the impression that .NET Framework can only reference .NET Framework assemblies and .NET Core can only reference .NET Core assemblies. After all, that's why .NET Standard appeared, so you can create assemblies that can be referenced from everywhere. However, one can actually reference .NET Framework assemblies from .NET Core (and not the other way around). Moreover, they work! How does that happen?

I chose a particular functionality that works only in Framework: AppDomain.CreateDomain. I've added it to a .NET 4.6 assembly, then referenced the assembly in a .NET Core program. And it compiled!! Does that mean that I can run whatever I want in .NET Core now?

The answer is no. When running the program, I get a PlatformNotSupportedException, meaning that the IL code is executed by .NET Core, but in its own context. It is basically a .NET Standard cheat. Personally, I don't like this, but I guess it's a measure to support adoption of the Core concept.

What goes on behind the scenes is that .NET Core implements .NET Standard, which can reference .NET Framework assemblies. For this to work you need .NET Core 2.0 and Visual Studio 2017 15.3 or higher.

Tuesday, June 05, 2018

Angular 5: Importing classes from their module, rather than importing them individually

Caveat lector: while this works, meaning it compiles and runs, you might have problems when you are trying to package your work into npm packages. When ng-packagr is used with such a system (often found in older versions of Angular as index.ts files) it throws a really unhelpful exception: TypeError: Cannot read property 'module' of undefined somewhere in bundler.js. The bug is being tracked here, but it doesn't seem to be much desire to address it. Apparently, I have rediscovered the concept of barrel, which now seems to have been abandoned and even completely expunged from Angular docs.

Have you ever seen enormous lists of imports in Angular code and you wondered why couldn't they be more compact? My solution for it is to re-export from a module all the classes that I will need in other modules. Here is an example from LocationModule, which contains a service and a model for locations:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LocationService } from './services/location.service';
import { LocationModel } from './models/location-model';
 
@NgModule({
  imports: [ CommonModule ],
  providers: [ LocationService ]
})
export class LocationModule { }
 
export { LocationModel, LocationService };

Thing to note: I am exporting the model and the service right away. Now I can do something like
import { LocationModule, LocationModel, LocationService } from '../../../location/location.module';
instead of
import { LocationModule } from '../../../location/location.module';
import { LocationModel } from '../../../location/models/location-model';
import { LocationService } from '../../../location/services/location.service';

Monday, June 04, 2018

Conventions in .NET API method names

In .NET APIs we usually adorn the action methods with [Http<HTTP method>] attributes, like HttpGetAttribute or AcceptVerbsAttribute, to set the HTTP methods that are accepted. However, there are conventions on the names of the methods that make them work when such attributes are not used. How does ASP.Net determine which methods on a controller are considered "actions"? The documentation explains this, but the information is hidden in one of the paragraphs:
  1. Attributes as described above: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
  2. Through the beginning of the method name: "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch"
  3. If none of the rules above apply, POST is assumed

Sunday, June 03, 2018

The Great Ordeal (The Aspect-Emperor #3), by R. Scott Bakker

book cover I have read all the Prince of Nothing books and the first two of The Aspect Emperor, in truth a single large story rather than two separate series. I am amazed of how many details and human truth could R. Scott Bakker stuff in the books and I wrote in the review of The White Luck Warrior that I was in withdrawal after I realized the next book was not published. Therefore my strategy was to wait until this and the fourth and last book in the series were published. Which is both a blessing and a curse. I had to remember what the hell happened "before", though the book has an intro in which is tells the story up to that point which I found very useful. I was also detached from the story and characters.

With that being said, the book felt even more like filler material. It mostly covers a rather boring part of the Ordeal, Esmenet and the story of a now more interesting Sorweel. Yet throughout the book I felt like the author was struggling to push meaning into less and less interesting concepts by his overuse of italics and very detailed introspection. That is both the general flavor that makes the series so good and the bit that sometimes made me want to fast forward. Kellhus is almost absent, like in the previous book, which is strange for a series called after him, but there is also less action. Or at least less from characters that I enjoy reading about (there is a nuclear explosion in there and large army conflicts, but again they felt like filling space). I was disappointed with the short and empty solution to Ishual, considering the largest part from the previous book was about getting there and towards the end there is an interaction between a Dûnyain and Qirri that left me in a "WTF?!" kind of state. On the bright side, a character that I enjoyed a lot reappeared as an agent of the Consult. That was fun!

So I am overly glad that I waited for both books from the series to get published so I can now get at the meat of the story (praise the meat!). I may have given you the impression that I didn't like the book, but I was merely comparing it with the rest. It is still a damn good book, however I am the type of guy to focus on the negative, so that is that. If I were meeting my past self, the advice I would give would be to read The Prince of Nothing and The Aspect-Emperor back to back. Oh well, that ship has sailed.

Friday, June 01, 2018

Algorithmic Weight Loss

Update: Many people have asked me how can the Body Mass Index be right when people who are very muscular are heavier than fat guys their exact volume. The truth is BMI and any other metric is just a tool to measure your own progress. Another one that I found interesting is the waist size around the belly button. Apparently, there is a nice heuristic that tells you how big it should be: half of your weight. Here is a simple calculator to tell you the optimal weight and waist size given the height and sex:


    




How is that right that a male should have the same waist as a woman when they have 2 points of extra BMI? That's the muscles that you should have :) The rest of the article applies just as well. Use whatever metric you feel comfortable with. Now for the meat of it:

Intro


As many other people, I am not satisfied with my weight. Putting aside the medical implications of having a lot of fat around my internal organs, I am mostly motivated by girls looking at me not as a hunk of a man, but as a fat old guy. I've tried various diets, which all worked in some capacity, but in the end I've just gained back the weight, in something called the Yo-Yo effect. So I've decided to approach the problem in a rational manner.

In order to solve the problem, one needs several pieces of information. First, you need to define the problem. Then you have to measure it, see if you have it or not and in what degree. Only then you can think of solutions, having the tools to measure your progress in applying them. Finally, you have to compare the solutions in terms of effort and results, predicted and actual.

Defining and measuring the problem


So yeah, I am overweight, but how is that a problem? Being overweight or obese may increase the risk of many health problems, including diabetes, heart disease, and certain cancers. There is a whole damn list. In order to define the term overweight, people have used various metrics, the most common being the Body Mass Index or BMI that takes into account just your height and weight. Recently that metric has been updated to include other factors, like age, race and gender. There are a lot of sites on the Internet that compute this.

I am going to eschew the fancy calculators and instead use the BMI calculator from calculator.net. For my input, the desired weight if I were to be smack in the middle of the normal range is 84 kg. That's surely a bit extreme for a guy who is 197 cm tall, but let's go with it. If I had that weight, I would have a BMI of 21.64. As it was a month ago, it was 31, meaning Obese class 1. Well, I don't want to be obese!

But what does make me fat? I mean, if I could change the gravitational pull, like going to Mars, I would be lighter, right? My BMI will lower considerably. But it wouldn't solve my problem which is actually related to how much extra fat I carry around.

Solutions


There are three ways of losing fat:
  • Using more energy than you put in
  • Tricking the body to not store it and/or eliminate it
  • Mechanical removal

For my intents and purposes, I will not discuss the last two. I don't want to have unnecessary surgery performed on me and if I had some medicine to make me eliminate fat, I wouldn't be able to know enough to judge the side effects. Either way, I wouldn't recommend things like that on my blog without being an expert, due to the inherent risks. The thing is that what I am going to propose at the end of this blog post - that you have to read to the end - is that how you lose fat is irrelevant, as long as you do. But I'll get there.

Now, burning fat requires a negative balance of calories. Stuff you put in has to be less than the stuff you use. If you look up how many calories are stored in a kilogram of fat, you will get a huge value: around 7500. To put that in perspective, running or cycling for 10km at a reasonable pace consumes about 500 calories and a whole Domino's pizza is around 2500. Fortunately, there are inefficiencies in processing, storing and using fat as an energy reserve, but we can use this as a comparison.

While healthy and promoting muscle growth and a sure way towards those girls seeing the hunk beneath all that fat, using sport to lose weight seems terribly inefficient. That being said, the long term effects of sport are that your metabolic rate increases. That means you normally burn more energy, even if you are not constantly exercising. However, understanding how much effort to expend, in what way and what are the long term effects pushes me more toward the unknown territory of "maybe it works". Going there would not be rational. So while I will hold sport as an optional nice to have, it is NOT a solution.

If you are wondering how many calories you are using in a day, there is the Harris-Benedict formula that computes the BMR and then you multiply it with your daily activity level. Just to put more nails into the sports coffin, the daily activity level is a number between 1.2 (sedentary) and 1.9 (extra active). So the best you can achieve through sports is a 50% increase in your energy use if you are "extra active". No, thanks! For me, the calorie burn from a month ago was 2678 in order to maintain my weight.

So if I am not burning more energy, I have to input less. The same useful calorie calculator tells me that in order to lose weight I have to eat 1678 calories, so 1000 calories less than what I am burning. That is why a lot of diets are based on "eat only low calorie food that tastes like crap at fixed hours to the second, while avoiding anything that feels like an actual meal", with painstakingly complicated menus of what you are allowed to eat. Well, those are complications I don't need. And this calorie calculation adds even more complexity. I have actually lost 10 kg in a month, so now the daily calorie use is 2522, a sliding value as I lose weight!

How are all these metrics calculated? They take into account some constants, like my height and age and gender, and then some variables, like my weight. In order to affect any of them I need to simply lose weight. I have a simple way of measuring weight - with a scale, I have a target - 84 kilograms, a starting point - 120 kilograms. I also have a solution for decreasing the weight: eat less. This also leads to muscle loss, which CAN be solved by physical exercise, but that's another story.

Possible hurdles


As I said, there are more ways to lose weight, but there are even more ways of eating less. Less carbs, less fat, eat only certain things, avoid certain things, fasting, eat many small meals, eat one enormous meal very rarely, don't drink sugary drinks and alcohol, drink disgusting vegetable concoctions, etc. While trying other diets I've discovered several impediments to losing weight that are based more on human nature than anything else:
  • it's much easier to start eating than stopping
  • strict schedules constrain my way of life
  • diet food is bland at best
  • the world is constantly bombarding me with offers to eat and drink
  • once I've slipped, it's hard to get back on track
  • eating is social
  • eating is a habit to pass boredom
  • food is a source of comfort
  • complex diet systems are easier to cheat and I always find how
  • dieting goals can be daunting
  • losing weight is slowing down as you go along
  • your body learns that they should burn less when you eat less, decreasing the metabolic rate. Your subconscious learns that if it makes you feel miserable enough you will slip and eat

I would like a diet that takes all that into consideration.

Let's start with ambitious dieting goals. Let's say I wanted to lose weight until I got to 84 kilograms (which I will actually never do, because it's insane) meaning I would have planned to lose a third of my weight. Isn't that a little daunting? You start off fast, because the first thing you lose is a little water and you say "wow! 5 kilos in a week, if I keep it up I will lose 40 kilos in two months!" and then the next week you barely lose one kilo (because it was your birthday and you deserved that cake!). Well, not only it's not because of the cake, it's also because of all the other points on the list above. Your weight loss is slowing down, your body is switching to a slower burn, social events are constantly bombarding you with high caloric foods, your diet is depressing you and your normal solution for depression is to drink booze and eat comfort food, once you started with the slice of pizza you couldn't just stop there, and so on and so on. In the end, after two miserable weeks you have all the reasons to stop dieting and continue with your normal routine. Nothing from a normal diet is pushing you towards keeping with it. It's torture.

Yet it all started with an ambitious goal. What if the goal was closer, as in "baby steps"? If I weigh 120 kilos, I can consider a victory getting to 119. An therefore lies my solution.

My take on the solution


My system is simple. You have three parameters: your weight target, your weight decrement and your grace period. Also, choose a dieting method. Any dieting method, and/or even some other solutions like sport, medication or medical procedures. This is how it works for me: my target is 84 kg, my decrement is 1 kg and my grace period is two days, which I intend to increase progressively as it becomes harder to lose weight. The method I chose (because of the first point) is to not eat or drink anything caloric, therefore fasting. I started at 120 kg and with the decrement of 1 kg, I need to not eat until I get to 119 kg. Once I get to that, I can eat. And I mean eat anything, drink anything, as much as I want. After that first meal, I have the grace period until I apply the decrement again.

Here is an example: I started on the first of May. Just by not eating for a day I lost more than 1 kilogram. On the second of May I had 118.5 on the scale. So I ate normal stuff, which made me get to 119.5 the next day, so I didn't eat that day at all. Next day I had 118.1, so I could eat again. On the fourth of may I had 118 kilograms, but the grace period of two days from the first meal had expired. Now the weight I needed in order to be allowed to eat was 117.

What are the advantages? I need a fancy list to enumerate them all:
  1. the Yo-Yo effect works for you now! You gain weight, then lose just a little more
  2. as long as you get to your target you may continue to keep the diet without the decrement. You can continue your entire life eating whatever you want, as long as you are at your desired weight
  3. you don't need to feel guilty about eating what you like and you don't have to stop once you started eating
  4. there are no schedules or special menus as long as you are on target
  5. you can pause the diet whenever you want. If you go on a vacation and you gain 10 kg, all you need to do is diet until those 10 kilos are gone, and then you are on track again. Same for social occasions, you don't have to be the guy that says no because he's on a diet.
  6. the dieting method is irrelevant, as are the various metrics and computations. It's as easy as getting to the next decrement. There are no complexities and no way to cheat
  7. it's so simple you can automate it in a computer program or smartphone app
  8. you can adapt parameters to your weight loss rate. As long as you plan to lose 10 grams in a billion years, you have a plan and can get on target. Take it as slow as you want, you will get there eventually. In other words, you need to get under a curve on a graph, not feel constantly bad if you have not reached your target yet
  9. and this is the best yet: if you eat a lot when you are allowed to, the later dieting will punish you for it. You get punished for indulging yourself and rewarded for losing weight. You are motivated to eat less, with less calories, but you choose it with your own free will. Your body also learns this and starts burning fat to get to the good part

Results


So, I am writing this article a month after I've decided to try this. I started at about 120 kilograms and now I have 107 kilos. It's not a lot, but I haven't felt I was really dieting. I drink a lot of water and I supplement it with vitamins and mineral pills if I have to not eat for a few days. I have the feeling the water is helping the losing of weight as I was usually getting the water only from the food I was eating or Cola and now I drink at least three liters of water a day. Our office is a "pizza office" so I slip often, but I don't feel bad about eating a slice of pizza, it still way under the calorie limit that leads to weight loss. At first I would eat a whole pizza, then fast longer afterwards, but after a few tries, it's much easier to just taste a slice and stop. My body is not usually craving anything and when it does, I just promise myself I will get that as soon as I get on target. And this has the extra advantage of delaying gratification. Often, when I can eat whatever I want, I remember the list of things that grabbed my attention and most of it is not appealing anymore. I started cooking weird stuff, just because while I am not eating I get ideas of what I would really like to eat when I get the chance.

In fact, I am starting a diet every two days or so. I lose a kilo, the diet is over, then I start another. In total I am reducing my calorie intake, but only by eating less of what I was already enjoying. I occasionally ride a bike or eat stuff that fires the metabolism up, but those are just extras. Even if I am allowed to, I stopped drinking so much Coca Cola. Strangely, I thought that it would taste better after a long pause, but it's just the normal aromatic sugar water taste.

Now, I doubt that eating once in two or three days works for everyone. Do whatever is easier for you: don't eat sugar, set your decrement to 100 grams, do those only meat things, eat only leafy veggies, whatever! For me, not eating is much easier than eating and stopping or eating bland things. I need my sausages and pizza and food that is so spicy that you need to keep eating it lest your mouth catches fire and alcohol and fizzy drinks and all the unhealthy crap that people usually eat. This doesn't stop me from eating that, but it slowly erodes my need to. It's an interesting side effect that I intend to explore further. Also, while there are reports of apparent health benefits for intermittent fasting, they have no part in my decision to do the diet the way that I am doing it.

So what is my real target? I am still deciding. I started with 97 kg just because I was expecting to give up around 110. Now I am thinking I haven't weighed 97 kg since high school and then I kinda felt I was too fat. Who knows. The beauty of this is that the graph stays there. Even if I stop for a few years, it just patiently waits for me to get under it. I feel no pressure which is more than I can say about any other diet I've tried or heard of.

StreamRegex published

I've just published the package Siderite.StreamRegex, which allows to used regular expressions on Stream and TextReader objects in .NET. Please leave any feedback or feature requests or whatever in the comments below. I am grateful for any input.

Here is the GitHub link: Siderite/StreamRegex
Here is the NuGet package link: Siderite.StreamRegex