teleren/devto huggingface dataset:
Uri to Hostname in C (GNU-C99)
Tags: c
Published: 2011-01-13 22:01:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Uri to Hostname in C (GNU-C99)
slug: uri-to-hostname-in-c-gnu-c99
date: 2011-01-13 22:01
tags: 
 - c
---
Another C function which works quite well and has no bugs that I know of yet...

Updated: fixed this now, leak free!

    /*
     * File:   utohn.c
     * Author: Adam K Dean
     * Description: gets a hostname from an uri
     *
     * Created on 11 January 2011, 22:12
     */
     
    /* int utohn(char *uri, char *hostname)
     * Uri to Hostname
     * Author: Adam K Dean
     */
    char *utohn(char *uri)
    {
        char *pch, *hostname;
        if ((pch = strstr(uri, "://")) != NULL)
        {
            pch += 3;
            int i = 0;
            while(pch[i] != '/' && pch[i] != ':' && pch[i] != '\0') i++;
            hostname = (char *)calloc(i + 1, sizeof(char));
            return strncpy(hostname, pch, i);
        }
        else return NULL;
    }

and usage code:

    int main(int argc, char** argv)
    {
        char hn1[] = "http://www.gentoo.org/";
        char hn2[] = "http://www.gentoo.org/docs/";
        char hn3[] = "http://www.gentoo.org:80/";
        char hn4[] = "127.0.0.1";
     
        printf("%s -> %s\n", hn1, utohn(hn1));
        printf("%s -> %s\n", hn2, utohn(hn2));
        printf("%s -> %s\n", hn3, utohn(hn3));
        printf("%s -> %s\n", hn4, utohn(hn4));
         
        return (EXIT_SUCCESS);
    }

and results:

`http://www.gentoo.org/ -> www.gentoo.org  
http://www.gentoo.org/docs/ -> www.gentoo.org  
http://www.gentoo.org:80/ -> www.gentoo.org  
127.0.0.1 -> (null)`

P.S, I have no affiliation with gentoo, and actually use centos.. I just like how easy it is to type gentoo..very nice!

Enjoy
C# Int.ToString().Length in C
Tags: c
Published: 2011-01-11 22:00:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: C# Int.ToString().Length in C
slug: c-int-tostring-length-in-c
date: 2011-01-11 22:00
tags: 
 - c
---
Another little helper function here, it counts how long the int would be if it was a string, just the same as doing Int.ToString().Length in C#.

    /*
     * File:   int_strlen.c
     * Author: Adam K Dean
     * Description: get length of an int as if it was a string
     *
     * Created on 11 January 2011, 13:01
     */
     
    int int_strlen(int val)
    {
        int v = val / 10;
        int i = 1, count = 1;
         
        while(v > i - 1)
        {
            i *= 10;
            count ++;
        }
         
        return count;
    }
Replicating c# params keyword in C (GNU-C99)
Tags: c
Published: 2011-01-11 21:59:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Replicating c# params keyword in C (GNU-C99)
slug: replicating-c-params-keyword-in-c-gnu-c99
date: 2011-01-11 21:59
tags:
 - c
---
Just like Julian Assange is jumping from country to country, brothel to brothel, being hunted like a heretic, my uptime project is sending me from one job to another, programming to web design to server admin to flash design.. well the flash design has yet to come, and I don't look forward to that day!

For the last 5 years I've coded C# primarily, using ASP.NET for most sites. I did do *some* PHP but not much, and I spent a week reading a C book (K&R) but put it down. So when I decided to rewrite my node servers in C, it wasn't a small task.

I am doing okay, it's getting along, and I'm picking it up quit easily. Below is some C code that works on linux (I'm running CentOS and compiling with GNU-C99), which replicates the action of the lovely C# params keyword, allowing you to pass multiple parameters to a function. I will be using it to create a String.Replace replication. Note I'm not using C++ even though it has these ...I don't like the syntax changes, too many colons.

    #include <stdarg.h>

    void *passparams(int argc, char *args, ...)
    {
        va_list marker;
        va_start(marker, *args);

        for(int i = 0; i < argc; i++)
        {
            printf("arg: %s\n", args);
            args = va_arg(marker, char *);
        }

        va_end(marker);
    }

I won't explain it more than to say make sure you have some sort of terminator character when using va_list/va_arg, as you get segfaults otherwise. Some people have int lists like { 1, 2, 3, 4, -1 } but it's ugly, I prefer an argument count list.

Enjoy
SQL Correlated Sub-Queries and Group By Unions
Tags: sql
Published: 2011-01-06 21:58:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: SQL Correlated Sub-Queries and Group By Unions
slug: sql-correlated-sub-queries-and-group-by-unions
date: 2011-01-06 21:58
tags: 
 - sql
---
Whilst working on my new uptime and latency monitoring project, I've ran into more than the usual amount of SQL conundrums, and I am learning a lot by having higher than normal requirements. To call yourself a programmer, I think you have to at least have basic SQL skills. They are your basic math skills for normal people, every coder should understand select, insert, update and delete.. and for a long time I was one of them, I hated SQL because I didn't understand it, or didn't want to.. but needing it, and needing it to do advanced things, means you need to learn, and it truly saves you time when you can cut out so much coding by offloading onto SQL!

So this part I'm working on now gets a list of hosts whose last record (latency check) is past a frequency threshold. The current SQL is great, it checks from a view whether the last date is past the threshold but I realised one small problem.. it doesn't get new hosts who have zero records. It will only work for previously checked hosts!

    SELECT HostId, MAX(Hostname) AS Hostname, MAX(CheckDate) AS CheckDate, MAX(Frequency) AS Frequency
    FROM vw_HostRecords
    GROUP BY HostId
    HAVING (DATEADD(minute, MAX(Frequency), MAX(CheckDate)) < GETDATE())

And so I had to again improve my SQL, onto correlated sub-queries. It is actually quite simple it just sounds clever but shh.. here is the SQL to check if a row exists in the records and if it doesn't, it selects that row from the hosts. Basically it gets all the new ones for me.

    SELECT Id AS HostId, Hostname, Frequency
    FROM t_Hosts
    WHERE (
       Id NOT IN (
          SELECT HostId
          FROM t_Records
          WHERE (HostId IS NOT NULL)
       )
    )

So now I need to mix these using a union, and adding in CheckDate = NULL so that the UNION works (as to use that, both selects must have the same fields/columns).. and we end up with this lovely piece of work:

    SELECT HostId, MAX(Hostname) AS Hostname, MAX(Frequency) AS Frequency, MAX(CheckDate) AS CheckDate
    FROM vw_HostRecords
    GROUP BY HostId
    HAVING (DATEADD(minute, MAX(Frequency), MAX(CheckDate)) < GETDATE())
    UNION
    SELECT Id AS HostId, Hostname, Frequency, NULL AS CheckDate
    FROM t_Hosts
    WHERE (
       Id NOT IN (
          SELECT HostId
          FROM t_Records
          WHERE (HostId IS NOT NULL)
       )
    )

Awesome, no?

Edit: Had to fix a bug, it seems you also have to get all the fields in the right order as well, as SQL will not mix and match for you!

So: select a, b, c from table_a union select a, b, c from union_b etc!

Edit 2: Removed OR from having line
RUBBoS
Published: 2017-10-31 19:52:37

---
title: "RUBBoS"
published: true
tags: 
canonical_url: https://michael.mior.ca/blog/rubbos/
---

While working on my Masters thesis, I needed a solid database benchmark. RUBBoS is a fairly common benchmark in the field, but unfortunately is a few years out of date. While it was fantastically simple to set up, I did run into a few issues associated with newer versions of PHP and Java as well as a few minor bugs.

Since the benchmark is fully open-source, I decided to release my modifications. You can download these changes to RUBBoS via [GitHub](https://github.com/michaelmior/RUBBoS). Installation instructions and some additional notes can also be found there. The most important thing to note is that I have only tested the LAMP version of the application.

Hope someone finds this useful!
SQL Get most recent records with group by
Tags: sql
Published: 2011-01-01 21:52:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: SQL Get most recent records with group by
slug: sql-get-most-recent-records-with-group-by
date: 2011-01-01 21:52
tags: 
 - sql
---
The following is awesome SQL. I will right now tell you, I don't like SQL. I admire it, but I don't like it. So SQL is a bit like Alan Sugar in that respect. But what I had to do, or well, what I've just done, is something very important and vital to making my medium-secret project more efficient.

I have two tables, hosts and records, and for each host row in the hosts table there is a bunch of record rows in the records table. I needed SQL to get me all the records that were either older than X number of minutes, or newer than X number of minutes, defined by a Date field.

I could easily do this in the application, and I have been doing, but when I put 5000 hosts into the database to run a test, it couldn't keep it fully because each iteration it had to pull 5000 hosts out and grab the latest record individually. So I scaled down to 1000 hosts to test my system, and managed to get about 90% upkeep, that is, keeping up with 90% of the hosts.

The problem was that whilst it was checking if any hosts had old records, a very inefficient way of doing it by the way, it was not checking the beginning of the list, which happened to be the first checked and the first that passed the threshold.

So, the SQL. With the help of @McFly from #lifestinks, being told it was impossible from someone in #sql and with the drunken non-reply of Mihner (of No Fixed Internet Abode), I came up with some SQL that would get me exactly what I wanted.

Now it wouldn't return to me all the details of the record, just the ID and the date of the most recent record. I will give you it in plain SQL, without the T-SQL schpiel:

    SELECT HostId, MAX(Hostname) AS Hostname, MAX(CheckDate) AS CheckDate, MAX(Frequency) AS Frequency
    FROM vw_HostRecords
    GROUP BY HostId
    HAVING (DATEADD(minute, MAX(Frequency), MAX(CheckDate)) < GETDATE())

And there you have it, horrible yet beautiful SQL code, that takes a weight off my back.

Enjoy, future me!
Private set property - public get, private set
Tags: csharp
Published: 2010-12-29 21:51:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Private set property - public get, private set
slug: private-set-property-public-get-private-set
date: 2010-12-29 21:51
tags:
 - csharp
---
Just come across something I haven't needed before, a property read-only from the outside, but writeable from the inside.. I present to you the private set property!

    public SocketException LastErrorException { get; private set;  }

You can set it from within the class, but not from outside. Simple!
Ctrl+A Select all text in a text box
Tags: winforms, csharp
Published: 2010-12-17 21:50:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Ctrl+A Select all text in a text box
slug: ctrl-a-select-all-text-in-a-text-box
date: 2010-12-17 21:50
tags:
 - winforms
 - csharp
---
Another quick-snip here. Add select all (ctrl+a) to a regular textbox in less than 7 seconds, and here's how. Using the KeyDown event, look for control and A, and then select all, suppressing the keypress to stop the pingggggg noise:

    private void txtInput_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.A)
        {
            txtInput.SelectAll();
            e.Handled = true;
            e.SuppressKeyPress = true;
        }
    }

And there you have it. Enjoy
Non-blocking Console.ReadKey()
Tags: csharp, consoleapplication
Published: 2010-12-16 21:50:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Non-blocking Console.ReadKey()
slug: non-blocking-console-readkey
date: 2010-12-16 21:50
tags:
 - csharp
 - console-application
---
Just a quick snippet for today.

Have you ever written a quick console app to test something, and wanted it to loop until you press an escape button? But Console.ReadKey() blocks, so you can't really use it...or can you?

    while (true)
    {
        while (!Console.KeyAvailable)
        {
            // do work
        }

        Console.WriteLine("Press Q to quit or any other key to continue..");
        if (Console.ReadKey().Key == ConsoleKey.Q) break;
    }

Double while loops does seem somehow wrong to me, I can't help but feel a sense of wrong doing when I look at it knowing it's my code, and my heart rate does increase at the prospect of reading about myself on Daily WTF and Coding Horror, but it works okay when your work doesn't matter what order it's called in.

I used this particular loop for writing to a file over and over and over to see if the size of the file has any performance issues with StreamWriter, which I can report it didn't.. not at 6GB of Lorem Ipsum anyway.

So, there you go, Console.KeyAvailable simply checks if a key is available to read, and if so, it reads it and checks if it's Q for Quitters. Pretty simple.

More snippets to follow.

Merry Christmas!
Change names when you find better ones
Published: 2023-02-02 05:12:31

---
title: Change names when you find better ones
published: true
date: 2010-11-12 17:29:00 UTC
tags: 
canonical_url: 
---

Names are everywhere in software. We name our classes, variables, namespaces, etc.  
  
The name should answer all the big questions about your code.   
  
When I'm refactoring my code that is one of the first thing I look for: Does the name of this method reveal its intent? If at that point I can think of a better name then I change it right away.   
  
Choosing good names can take a lot of time but it could save you more time in the future.
Regex split by spaces except inside quote marks
Tags: regex, csharp
Published: 2010-11-09 21:47:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Regex split by spaces except inside quote marks
slug: regex-split-by-spaces-except-inside-quote-marks
date: 2010-11-09 21:47
tags:
 - regex
 - csharp
---
Here's a nifty little bit of code I just wrote while writing a console input handler. Sometimes you will want to split up a string by a space, but then how do you input more than one word as a single argument? You put it in quote marks, but then how do you split those separately? Like this:

    MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");

Yep, one line of code. Don't forget to include System.Text.RegularExpressions though!

Lets take it further for a little test (actually the test code I was using):

    MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");
    WriteToConsole("Match Count: {0}", matches.Count);

    foreach (Match match in matches) WriteToConsole(match.ToString());

Input:

`The "quick brown fox" jumps over "the lazy dog"`

Output:

`Match Count: 5  
 The  
 "quick brown fox"  
 jumps  
 over  
 "the lazy dog"`

So there you have it, probably the easiest way to do it.

Enjoy
The Dangers of strlen
Published: 2017-10-31 19:52:08

---
title: "The Dangers of strlen"
published: true
tags: 
canonical_url: https://michael.mior.ca/blog/dangers-of-strlen/
---

I’ll keep this post brief, but I wanted to share something I just found about the C `strlen` function. It’s slow. It can make a big difference in program execution time.

For example, I had a function in an external which consumes a string, so I call `strdup` each time around a loop to make sure I have a copy for the next iteration.

In my case, the function I was calling already had the length of the string passed in as a parameter. This means `s2 = strdup(s1);` can be rewritten as

```
s2 = (char*) malloc(length);
memcpy(s2, s1, length);
```

Note that I used memcpy instead of strcpy. Since we already have the length of the string, this also avoids the loop in strcpy which would be required to find the end of the string. These kind of optimizations may seem like splitting hairs, but they can make a big difference in the overall runtime of your code. For example, with the optimization shown above, I was able to reduce the runtime of a particular loop by around 15%.

Know of any other common functions with performance problems people may not be aware of? Share your inside info in the comments!

Aside: While researching the performance of strlen, I came across this interesting forum post which provides an efficient strlen implementation from Knuth.

## Update: June 14, 2012

GCC 4.7.1 has an optimization to address this very issue. See the snippet below from the release notes.

> A string length optimization pass has been added…The pass can e.g. optimize
> 
> ```
> char *bar (const char *a)
> {
> size_t l = strlen (a) + 2;
> char *p = malloc (l); if (p == NULL) return p;
> strcpy (p, a); strcat (p, "/"); return p;
> }
> ```
> 
> into:
> 
> ```
> char *bar (const char *a)
> {
> size_t tmp = strlen (a);
> char *p = malloc (tmp + 2); if (p == NULL) return p;
> memcpy (p, a, tmp); memcpy (p + tmp, "/", 2); return p;
> }
> ```
Fibonacci Numbers & The Golden Ratio
Tags: php, fibonacci
Published: 2010-10-26 22:45:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Fibonacci Numbers & The Golden Ratio
slug: fibonacci-numbers-the-golden-ratio
date: 2010-10-26 22:45
tags: 
 - php
 - fibonacci
---
So here I am doing some designs when I think, hmm, maybe I will use the golden ratio to lay out the design, Fibonacci's Spiral and what not, but the amount of tedious workings out.. (having to use a pencil..tedious...physical movement you see..) so I wrote a script. I don't really like using C# for scripts, being it isn't a script but.. sometimes you just want something like putty in your hands to quickly test a hypothesis or whatnot, and PHP is great for that. Big project, ASP.NET but a little versatile albeit-unable-to-really-report-errors-very-well scripting language, PHP is the don.

So, Fibonacci's numbers, very nice and easy to do:

    <?php
     
    $numbers[] = 0;
    $numbers[] = 1;
     
    $a = 0;
    $b = 1;
     
    for ($i = 0; $i < 10; $i++)
    {
     $c = $a + $b;
     $a = $b;
     $b = $c;
     
     $numbers[] = $c;
    }
     
    // output
    foreach($numbers as $n) echo "$n, ";
     
    ?>

and then for the golden ratio, a slightly bigger script. 

    <?php

    error_reporting(E_ALL);

    $width = 1024;
    $height = 768;

    $phi = 0.6180339887;

    $boxes[] = array($width, $height);

    for($i = 1; $i < 10; $i++)
        {
        $w = round($boxes[$i - 1][0] * $phi, 4);
        $h = round($boxes[$i - 1][1] * $phi, 4);
        $boxes[] = array($w, $h);
    }

    echo "<pre>";
    for($i = 0; $i < count($boxes); $i++)
    {
        $box = $boxes[$i];
        $w = sprintf("%-10s", $box[0]);
        $h = sprintf("%-10s", $box[1]);

        echo "W: $w H: $h "; 
        if ($i > 0)
        {
            $pbox = $boxes[$i - 1];
            $tw = sprintf("%-10s", $box[0] + $pbox[0]);
            $th = sprintf("%-10s", $box[1] + $pbox[1]);
            echo "TW: $tw TH: $th";
        }
        echo "\r\n";
    }
    echo "</pre>";

    ?>

You'll see I supply three variables, the initial width, height and then phi, which shouldn't really need to change. This script gives us a nice output, which works out the desired width and height for each new box, allowing you to quickly code that, rather than working it out and all that..tedious work..

    W: 1024       H: 768        
    W: 632.8668   H: 474.6501   TW: 1656.8668  TH: 1242.6501 
    W: 391.1332   H: 293.3499   TW: 1024       TH: 768       
    W: 241.7336   H: 181.3002   TW: 632.8668   TH: 474.6501  
    W: 149.3996   H: 112.0497   TW: 391.1332   TH: 293.3499  
    W: 92.334     H: 69.2505    TW: 241.7336   TH: 181.3002  
    W: 57.0656    H: 42.7992    TW: 149.3996   TH: 112.0497  
    W: 35.2685    H: 26.4514    TW: 92.3341    TH: 69.2506   
    W: 21.7971    H: 16.3479    TW: 57.0656    TH: 42.7993   
    W: 13.4713    H: 10.1036    TW: 35.2684    TH: 26.4515 

Simples, simply take your new width and height (W & H) and check the values add up (TW & TH add up the current and the previous width and height), and you're set.

Enjoy.
SQL INSERT with WHERE clause
Tags: sql
Published: 2010-10-14 22:44:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: SQL INSERT with WHERE clause
slug: sql-insert-with-where-clause
date: 2010-10-14 22:44
tags: 
 - sql
---
So here I am, again, resigned to having to deal with SQL. I don't like SQL and it doesn't like me. One of the main reasons is because when I put a nicely formatted piece of code into Management Studio, it mangles it and disfigures it horribly as if saying "not only does this SQL not work but I have chewed it up and spat it back out at you."

I am currently writing a util to extract email addresses from a customer database and generate the SQL to insert them into our mailing list database. Rather than risk having two email addresses and therefore maybe spamming a customer, I wanted the get some SQL that would first check if the email existed within the database, and if not, then insert it.

After lots of horribly small examples SQL and about 45 Googles, I finally came up with some working code! Below you will see that I first check if a select statement does not exist. And then if it doesn't, I run the insert code. Nice and simple, yeah ...once it's done and working..

    IF NOT EXISTS (SELECT EmailAddress FROM t_MailingList
     WHERE EmailAddress = 'test') 
    BEGIN
     INSERT INTO t_MailingList
     (EmailAddress, AcceptsPostal, AcceptsEmail)
     VALUES ('test', 0, 1) 
    END

P.S, if you get the compound errors like I did, then I suggest either 1) asking an experienced sqler, 2) keeping calm or my preferred method 3) a hammer. Enjoy!