CodeSOD collection


  • Discourse touched me in a no-no place

    @Bulb I've seen DOM implementations where the source of truth was the string form. That's probably OK when you're just building a static model of the contents of a page, but it gets awful once you start applying changes as each change results in much copying of string data. Unsurprisingly, the result was more than a bit slow at, well, almost everything that you might want to use a DOM for.



  • @dkf Yeah, you definitely want object form and a DOM differ if you are after any semblance of performance. I am putting some hope in wasm and the likes of yew, sycamore or dioxus. Not too much hope though.


  • Java Dev

    @dkf said in CodeSOD collection:

    user-supplied data and there ain't nobody got time for correctly localizing all that

    It's not about translating the user-supplied data. It's that English, Norwegian, Swedish, and Turkish (and dozens of other language) all have different ideas about how normal case-insensitive dictionary order works.



  • Don’t forget that modern web development is a bucket of shit that doesn’t want to deal with things as complicated as :airquotes: databases :airquotes: when they can just do it all, SPA style, on the front end.

    The sad reality is that throwing a megabyte of data at the front end and letting it sort everything out is perceived as a better solution because they don’t have to wait for subsequent API requests to do anything.


  • Discourse touched me in a no-no place

    @Arantor said in CodeSOD collection:

    The sad reality is that throwing a megabyte of data at the front end and letting it sort everything out is perceived as a better solution because they don’t have to wait for subsequent API requests to do anything.

    If you can stream it, and you're not going to mobile devices (or, worse, embedded systems) a megabyte of data isn't too big a problem. A few thousand itty bitty requests OTOH…



  • @Arantor said in CodeSOD collection:

    The sad reality is that throwing a megabyte of data at the front end and letting it sort everything out is perceived as a better solution because they don’t have to wait for subsequent API requests to do anything.

    If they just throw the complete result at the front-end and sort it there, it might be a nibble slower than it needs to be, but it will behave correctly. It's the, all too common case, when they realize they shouldn't throw a megabyte of data at the front end all at once, but don't realize they have to apply order before pagination, so if they are only getting first page, they already have to sort server-side.


  • Discourse touched me in a no-no place

    @Bulb The real fun comes when the DB decides that the result set shouldn't come back in a consistent order at all if you don't specify an ORDER BY clause. Which it is totally legal for it to do. The resulting user experience of “Dude, where's by $FooBar?” is just magnificent in a horrible way.

    See also JIRA.


  • Considered Harmful

    @dkf said in CodeSOD collection:

    The real fun

    JPA is Nedry.



  • @Gribnit said in CodeSOD collection:

    JPA is Nedry.

    Nuh-uh-uh, you didn't say the magic word!



  • @BernieTheBernie said in CodeSOD collection:

    0

    What? Did I really write 0? A magic number. Shame on me.
    The value must be calculated.

    Perhaps you remember maths lessons from times long ago...
    The sum of squares of sine and cosine yield 1:
    sin(x)*sin(x)+cos(x)*cos(x)=1
    In order to make things even clearer, remember that sin(-x)=-sin(x)and cos(-x)=cos(x).
    And we can replace that fucking stupid magic number.

    double kappa = new Random().NextDouble();
    (int)Math.Round(-Math.Sin(kappa) * Math.Sin(-kappa) + Math.Cos(kappa) * Math.Cos(-kappa) - 1, 0)
    

    But... now there's -1.
    What a shame!
    Fortunately, the logarithm of 1is 0.

    (int)Math.Round(Math.Log(-Math.Sin(kappa) * Math.Sin(-kappa) + Math.Cos(kappa) * Math.Cos(-kappa)), 0)
    

    A little better now.

    Is further improvement possible?
    Yes, it is.
    new Random().NextDouble()can be defined as a variable of a function type, and defined some where away from the place it is used. And , of course, kappa should be var.

    var g = new Func<double>(() => new Random().NextDouble());
    // several lines of other code
    var kappa = g();

  • Discourse touched me in a no-no place

    @BernieTheBernie said in CodeSOD collection:

    A little better now.

    You still have a 0 in there.



  • @dkf How can I get rid of that eventually? That's some recursive infection...


  • Discourse touched me in a no-no place

    @BernieTheBernie Well, you could try finding something that generates an empty string or list and getting the length of that.



  • @dkf string.Empty.Length. Thanks a lot!



  • @BernieTheBernie said in CodeSOD collection:

    @dkf string.Empty.Length. Thanks a lot!

    Or, you can just come out of the closet and start using JavaScript already.


  • Considered Harmful

    @BernieTheBernie said in CodeSOD collection:

    @dkf How can I get rid of that eventually? That's some recursive infection...

    Use a progressive approximation


  • ♿ (Parody)

    @dkf said in CodeSOD collection:

    @BernieTheBernie said in CodeSOD collection:

    Of course, you could stop the collection process (which takes time: TCP) when the first Thing was found which fulfills the threshold criterion.

    That reminds me of code that would laboriously fetch a big list of tens of thousands of IDs of objects from a web service, and then fetch the full details for each of those objects to flesh them out, before returning the list to the caller. Who would almost invariably just get the length of the list and compare that against zero, and that was the only use of that call anywhere. upvote all the posts.

    Ah, good times.


  • Considered Harmful

    @boomzilla said in CodeSOD collection:

    @dkf said in CodeSOD collection:

    @BernieTheBernie said in CodeSOD collection:

    Of course, you could stop the collection process (which takes time: TCP) when the first Thing was found which fulfills the threshold criterion.

    That reminds me of code that would laboriously fetch a big list of tens of thousands of IDs of objects from a web service, and then fetch the full details for each of those objects to flesh them out, before returning the list to the caller. Who would almost invariably just get the length of the list and compare that against zero, and that was the only use of that call anywhere. upvote all the posts.

    Ah, good times.

    Huh, that reminds me of a project I'd been planning to put off.



  • How can we count the number of pixels in an image which have a specific color?
    The simplest idea is of course a simple iteration combined with a check:

    Bitmap i = /* some bitmap image */ ;
    Color c = /* specify color */;
    var d = 0;
    for (var f = 0; f < i.Width; f++)
    {
        for (var g = 0; g < i.Height; g++)
        {
            if (c == i.GetPixel(f, g))
            {
                ++d;
            }
        }
    }
    

    But ... anyone would be able to follow this code snippet.
    Isn't there something more laborate? Like a Linq snippet?

    Unfortunately, C#'s Bitmap class does not have a GetAllPixels or similar function. You can get the color for a specified pixel only, the GetPixel(x,y) method used above.

    Enumerable.Range(a,b) creates an enumerable of b integers starting from a (included) . Hence we can replace a for with an Enumerable.Range(0, i.Width):

    var t = Enumerable.Range(0, i.Width).Count(x => i.GetPixel(x, 0) == c);
    

    counts all pixels in the frist row of the image which have the specified color.
    Now, we just need to iterate over the columns and sum that up:

    Enumerable.Range(0, i.Height).Sum(y => Enumerable.Range(0, i.Width).Count(x => i.GetPixel(x, y) == c));
    

    Looks good, for a starter.

    Next, I'll embellish that with the replacements for 0 and 1 I've introduced above. It will be more fun for any future code reader when he finds something like

    Enumerable.Range([complicated expression evaluating to 0] * i.Width, [complicated expression evaluating to 1] * i.Height)

    instead of Enumerable.Range(0, i.Height).

    😛


  • 🚽 Regular

    @BernieTheBernie I like that one-liner, but have you considered, instead of using Enumerable.Range directly, implementing your own IEnumerator classes and returning them from an extension method to the Bitmap class? You could have BitmapRowEnumerator and PixelsInABitmapColumnEnumerator; or the other way around, which I personally think is less intuitive.

    Next step then would be to iterate over rows and pixels out of order. Throw some prime factorization and modulus operation on that.


  • Java Dev

    @BernieTheBernie You could use a single enumerator by doing something like this. This allows iterating in semi-random order through all pixels in the grid, with an appropriate mapping function.

    Enumerable.Range( 0, i.Height * i.Width ).Sum( n => c == i.GetPixel( n / i.Height, n % i.Height ) );
    

  • Java Dev

    @PleegWat Something like this would be a reasonable basis:

        int n = 1;
        int s = c == i.GetPixel(0, 0);
    
        do s += c == i.GetPixel( n % w, n / w); while ( -1 + (n = (n << 1) % (h * w)) );
    

    This requires h and w to be primes; if they are not some pixels will not be visited. n << 1 can be replaced with n * t, where t is any positive integer which does not have h or w as factors.



  • @PleegWat said in CodeSOD collection:

    with an appropriate mapping function.

    Enumerable.Range(0, (i.Height + 1) * (i.Width + 1) - 1).Select(n => new Pair(n, Math.Floor(Math.Sqrt(n))).Select(n => new Triplet(n.First, n.Second, n.First  < (n.Second + 1) * n.Second)).Sum(n => c == i.GetPixel(n.Third ? n.First - n.Second * n.Second : n.Second, n.Third ? n.Second : n.First - n.Second * (n.Second + 1)));
    

    Obviously there are some magic numbers there that need to be dealt with. Also note the use of the System.Web.UI namespace.

    This requires the image to be square; padding of some unwanted colour could be used to extend the short side.


  • Discourse touched me in a no-no place

    @BernieTheBernie said in CodeSOD collection:

    Enumerable.Range(0, i.Height).Sum(y => Enumerable.Range(0, i.Width).Count(x => i.GetPixel(x, y) == c));
    

    Looks good, for a starter.

    Shouldn't you split that up further, with one function application to get the pixel at a location and another to decide whether that's something that should be counted?

    @Zecc said in CodeSOD collection:

    Next step then would be to iterate over rows and pixels out of order. Throw some prime factorization and modulus operation on that.

    I recommend enumerating the points by following a Hilbert curve. (You can filter them to exclude the ones that don't actually exist in the image.)



  • @BernieTheBernie Nice glass bottle for pounding that nail in. You could use a hammer.


  • Considered Harmful

    @TwelveBaud said in CodeSOD collection:

    @BernieTheBernie Nice glass bottle for pounding that nail in. You could use a hammer.

    Hammers are explicitly contraindicated by BernieTheBernie's overall problem statement.
    Can you recommend an old shoe?


  • Considered Harmful

    @dkf what's wrong with a Peano curve?


  • Discourse touched me in a no-no place

    @Gribnit Sounds like we need an AbstractCurveFactory...


  • Considered Harmful

    @dkf said in CodeSOD collection:

    a Hilbert curve

    I suggest:

    dilbert_curve.jpg



  • @TwelveBaud said in CodeSOD collection:

    You could use a hammer.

    It would help if what is actually the hammer wasn't called “doorknob”.



  • Let's start the next :wtf: .
    Fritz, the head of quality, requested Bernie to persist a boolean state. Fritz has already desided that Bernie has to use a file for that purpose, and prescribed the file name. And, his oddly worded requirement can be interpreted such that the file is expected to be removed when the state is false.

    So Bernie looked out for the place where the state was set. Actually, the code could be some simple

    try
    {
        if (state)
        {
            Directory.CreateDirectory("TheFolder"); 
            File.Create(@"TheFolder\TheFile.xml");
        }
        else
        {
            File.Delete(@"TheFolder\TheFile.xml");
        }
    }
    catch (Exception e)
    {
        Logger.LogException(Name, e);
    }
    

    The folder exists on the production system anyway, but not in a unit test, so its creation is only for that purpose (OK, the test could set that up too, but why?). And for removing the file, the folder should better be kept, because normally it contains important files.

    But that code is boring. What about a tern for replacing that if...else?

    Actually, that's possible.

    Action a = state 
               ? new Action(/*true part*/) 
               : new Action(/*false part*/);
    

    and now, the if...elsecan be replaced with a simple a().

    But I wanna play Bad Bernie!
    OK.
    Write that crap as a one-liner, and note that the path delimiter can be dealt with in several ways in C#:

    @"TheFolder\TheFile.xml"
    "TheFolder\\TheFile.xml"
    "TheFolder/TheFile.xml"
    

    and mix that apropriately.
    Also add some unnecessary casts to Action, some superfluous {}, and extra unnecessary options, like with File.Create(@"TheFolder\TheFile.xml", 1, FileOptions.WriteThrough).Close());
    😅



  • On start, that state must be reconstituted and passed on to some other component. Actually, just testing for the existence of the file should do. But that's too simple:

    bool state = new FileInfo(path).Exists;
    

    So let's read in all its contents into an array and check if the array contains at least 0 elements (um, the file is empty anyway...)

    bool state = new FileInfo(path).Exists && File.ReadAllBytes(path).Length >= 0
    

    Since File.ReadAllBytesthrows a FileNotFoundExceptionwhen the file does not exist, that check must come second.

    Also,

    new FileInfo(path).CreationTimeUtc.Ticks > 0
    

    will always be true for an existing file.

    Rather lame, but, :wtf-whistling: , let's just do a long one-liner passing on this state to the next component with this triplicate existence check.



  • @BernieTheBernie said in CodeSOD collection:

    File.ReadAllBytes(path).Length >= 0

    👍

    @BernieTheBernie said in CodeSOD collection:

    Since File.ReadAllBytesthrows a FileNotFoundExceptionwhen the file does not exist, that check must come second.

    Why don't you use exception-based control flow then?

    try {
        if (File.ReadAllBytes(path).Length >= 0) {
            return true;
        }
    } catch(FileNotFoundException e) {
        return false;
    }
    return true;
    

    … ok, not a one-liner … but a bit of a head-scratcher.



  • @BernieTheBernie You and your explicitness...

    var a = state ? delegate { /*true part*/ } : () => /*false part*/;
    


  • @TwelveBaud Why do you write such easy-to-read clean code?


  • Considered Harmful

    @BernieTheBernie Count the :wtf:s:

    bool? IsFileNotFoundException(Object exception) => exception as FileNotFoundException != null ? true : exception is Exception ? false : null;
    bool? IsInputOutputException(Object exception) => exception as IOException != null ? true : exception is Exception ? false : null;
    
    DirectoryInfo filePlaiceName = new DirectoryInfo("TheFolder");
    FileInfo fileRealName = new FileInfo("TheFile.xml");
    
    string Getpath(string p)
    {
    	string result = "\\";
    	foreach (var s in p)
    	{
    		if (s.ToString() == Path.DirectorySeparatorChar.ToString())
    		{
    			result = Path.DirectorySeparatorChar.ToString();
    		}
    	}
    	foreach (var s2 in p)
    	{
    		if (s2.ToString() == Path.AltDirectorySeparatorChar.ToString())
    		{
    			result = Path.AltDirectorySeparatorChar.ToString();
    		}
    	}
    	return result;
    }
    
    string GetFilePlaiceName()
    {
    	string file = filePlaiceName.Name;
    	string path = GetPath(filePlaiceName.FullName);
    	string name = file + path + fileRealName.Name;
    	return name;
    }
    
    try
    {
    	if (!state)
    	{
    		var path = new DirectoryInfo(filePlaiceName.Name);
    		var location = path.Name;
    	    if (!Directory.Exists(location.Name))
    	    	path.Create();
    		if (!Directory.Exists(location.Name))
    			throw new Exception();
    		string name = GetFilePlaiceName();
    		var item = new FileInfo(name);
    		item.Delete();
    		if (File.Exists(item.Name))
    		{
    			Thread.Sleep(55);
    			item.Delete();
    		}
    	}
    }
    catch (Exception error) when IsFileNotFoundException(error) == true || IsInputOuptutException(error) == true || error.GetType() == new ArgumentException().GetType()
    {
    	Logger.LogException(Name, error);
    }
    
    try
    {
    	if (state)
    	{
    		var folder = new DirectoryInfo(filePlaiceName.Name);
    	    if (!Directory.Exists(folder.Name))
    	    	folder.Create();
    		string name = GetFilePlaiceName();
    		var data = new FileInfo(name);
                       if (data.Exists())
                         data.Delete();
    else
         File.WriteAllText(name, name);
    		FileStream fs = new FileStream(name, FileMode.Truncate, FileAccess.ReadWrite);
    	}
    }
    catch (Exception error) when IsFileNotFoundException(error) == true || IsInputOutputException(error) == true
    {
    	Logger.LogException(Name, error);
    }
    

  • Considered Harmful

    @Applied-Mediocrity I get a count of... null. Debugging...



  • @Applied-Mediocrity Wha? Wha? What? Where's tea?

    Does that even do anything other than drawing an eight-sided pentagram on your ear in a misguided attempt to summon daemons from your nose?


  • Considered Harmful

    @Bulb it's fishy, that's for sure



  • @Gribnit It's not merely fishy. It has pockets full of wet trout and slaps everyone with it.


  • 🚽 Regular

    @Bulb said in CodeSOD collection:

    eight-sided pentagram

    5 sides of pentagram + 1 inside + 1 outside + 1 side of fries?


  • Considered Harmful

    @Bulb said in CodeSOD collection:

    pockets full of wet trout

    Flatter than trout, surely.



  • @Zecc said in CodeSOD collection:

    @Bulb said in CodeSOD collection:

    eight-sided pentagram

    5 sides of pentagram + 1 inside + 1 outside + 1 side of fries?

    It's a bit unclear what should be called sides of a pentagram, but I'd probably say a normal pentagram has 10 sides.



  • @Bulb said in CodeSOD collection:

    @Zecc said in CodeSOD collection:

    @Bulb said in CodeSOD collection:

    eight-sided pentagram

    5 sides of pentagram + 1 inside + 1 outside + 1 side of fries?

    It's a bit unclear what should be called sides of a pentagram, but I'd probably say a normal pentagram has 10 sides.

    I count 12 for your standard "5-pointed star in a circle" shape or 7 for the bare "5-pointed star".

    6 individual sections inside the star (5 triangles and 1 pentagon) and then either

    • 1 "outside" section (for the bare star)
    • 5 "outside the star but inside the circle" sections + 1 "outside the circle" section (for the circled star, assuming it's inset so that the star's vertexes intersect with but do not cross the circle)

    Other definitions:

    • Keeping the circled star, but ignoring the internal divisions gives 2 (inside the circle/outside the circle) or 7 ( outside the circle, outside-the-star section x5, inside the star x 1) depending
    • Using a bare star but ignoring the internal divisions gives 2.


  • @Bulb said in CodeSOD collection:

    It's a bit unclear what should be called sides of a pentagram, but I'd probably say a normal pentagram has 10 sides.

    According to Wikipedia, it's five:

    For an n-sided star polygon, the Schläfli symbol is modified to indicate the density or "starriness" m of the polygon, as {n/m}. If m is 2, for example, then every second point is joined. If m is 3, then every third point is joined. The boundary of the polygon winds around the center m times.

    The (non-degenerate) regular stars of up to 12 sides are:

    Pentagram – {5/2}


  • Considered Harmful

    @Zerosquare

    it's five:

    that's odd.

    a normal pentagram has 10 sides.

    He's right you know.



  • Let's return to my cow-orkers' achievements, i.e. ♭♯♮:wtf: (accidental wtf).
    We use some communication over TCP. If the other machine is not available, that takes very long till timeout. So, long ago, Bernie just added a method for failing faster in such a case:

        private void FailFast()
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(Host);
            if (reply.Status != IPStatus.Success)
            {
                throw new RemotingException($"The machine '{Host}' cannot be reached.");
            }
        }
    

    Send a ping, and if that fails, do not try to get a TCP connection. If the other machine is available (in the local network), that method wasted a small number of milliseconds (if it is a millisecond at all).

    That concept is below the mental incapabilities of Jim. He changed that:

        private void FailFast()
        {
            int[] pingTimes = { 100, 200, 500, 2000 };
            Ping ping = new Ping();
    
            foreach (int pingTime in pingTimes)
            {
                PingReply reply = ping.Send(Host, pingTime);
                if (reply != null && reply.Status == IPStatus.Success)
                {
                    return;
                }
            }
            throw new RemotingException($"The machine '{Host}' cannot be reached.");
        }
    

    He has the code try the ping4 times before failure. Why? Just why?
    And why does he check for reply != null . Never does ping.Sendreturn null. Never.

    But, :technically-correct: , in case of failure, Jim's code is faster than Bernie's: the default timeout is 5 seconds, and Jim's code consumes only 2,800 milliseconds.
    That's a remarkable achievement.



  • @BernieTheBernie said in CodeSOD collection:

    Send a ping, and if that fails, do not try to get a TCP connection.

    Just watch out for all the firewalls out there that by default drop pings (ICMP) though the TCP port is open just fine.



  • @Bulb Not necessary. Everything open to everyone in those networks...



  • @BernieTheBernie You are a lucky guy.

    I am more used to networks segmented into bambillion subnets divided to a different extent by firewalls, requiring stations to have firewalls many of which don't by default respond to pings, and lot of similar shenanigans.


Log in to reply