16 votes

Topic deleted by author

11 comments

  1. [3]
    Nitta
    Link
    // I need a comma separated list in Java listOfStrings.toString().replace("[", "").replace("]", "");
    // I need a comma separated list in Java
    listOfStrings.toString().replace("[", "").replace("]", "");
    
    5 votes
    1. [2]
      ali
      Link Parent
      Pretty sure string.replace uses regex like string.split does. So you could use Fstrings.replace("[|]","") The pipe character meaning either [ or ]

      Pretty sure string.replace uses regex like string.split does.

      So you could use
      Fstrings.replace("[|]","")

      The pipe character meaning either [ or ]

      1 vote
      1. Nitta
        Link Parent
        Well this is a topic with bad code. Square brackets can be in strings of the array too. Kotlin, the "improved Java", has a neat function for this purpose: // I need a comma separated list in...

        Well this is a topic with bad code. Square brackets can be in strings of the array too.

        Kotlin, the "improved Java", has a neat function for this purpose:

        // I need a comma separated list in Kotlin
        listOfStrings.joinToString(separator = ", ")
        
        1 vote
  2. Soptik
    Link
    Here's a method in my published Clash Royale .Net Wrapper. public IEnumerable<IEnumerable<O>> Mine<T, O>(IEnumerable<T> input, Func<string, T> getObjectFromTag, IEnumerable<Func<T,...

    Here's a method in my published Clash Royale .Net Wrapper.

            public IEnumerable<IEnumerable<O>> Mine<T, O>(IEnumerable<T> input, Func<string, T> getObjectFromTag, IEnumerable<Func<T, IEnumerable<string>>> selectTagsFunction, Func<string, O> resultFunction)
            {
                List<string> tags = new List<string>();
    
                foreach (T inp in input)
                {
                    foreach (Func<T, IEnumerable<string>> function in selectTagsFunction)
                    {
                        tags.AddRange(function(inp));
                    }
                }
    
                List<string> ts = new List<string>();
                ts.AddRange(tags);
                for (int i = 0; i < tags.Count; i++)
                {
                    T result = getObjectFromTag(tags[i]);
                    foreach (Func<T, IEnumerable<string>> function in selectTagsFunction)
                    {
                        foreach (string tag in function(result))
                        {
                            if (!tags.Contains(tag))
                            {
                                tags.Add(tag);
                                ts.Add(tag);
                            }
                        }
                    }
                    yield return ts.Select(tag => resultFunction(tag));
                    ts.Clear();
                }
        }
    

    But this is more interesting. It's one method call, one statement. I list this code at the readme.md as example usage.

    // Player is the thing I work with (I mine players), string is the thing mining returns (player tags)
    var result = wr.Mine<Player, string>(
        new Player[] { wr.GetPlayer(wr.GetTopPlayers().First().tag, false, true) }, // As first data, use best player (here may be more players, even all players in wr.GetTopPlayers())
        playerTag => wr.GetPlayer(playerTag, false, true), // How to get object Player from tag
        new Func<Player, IEnumerable<string>>[]{ // Define array of actions to do with each player object (how to get more tags)
            // Here, do only three actions:
            new Func<Player, IEnumerable<string>>( // Get other players from clan
                player => player.clan == null ? new string[0] : // If player doesn't have clan, return nothing
                            wr.GetClan(player.clan.tag) // Get player's clan
                            .members.Select(member => member.tag) // For each clan member, get his tag (this is used to mine additional tags from known players)
                ),
            new Func<Player, IEnumerable<string>>( // Get players from player's battles (from opponents)
                player => player.battles.SelectMany(battle => battle.opponent.Select(plinfo => plinfo.tag))
                ),
            new Func<Player, IEnumerable<string>>(
                player => player.battles.SelectMany(battle => battle.team.Where(plinfo => plinfo.tag != player.tag).Select(plinfo => plinfo.tag))
                )
            },
        new Func<string, string>( // This functions gets tag (string) and returns required object - in this case, string. If you want to get for example
                                    // full player profile, use something like tag => wr.GetPlayer(tag)
                resultTag => resultTag
            )
        );
    

    Pretty nice code, right?

    3 votes
  3. [4]
    ali
    Link
    I had something like this the other day. I'll try to format it later when I'm not on the phone. The idea is to call a function with a name and the parameters, when a parameter is passed in. To do...

    I had something like this the other day. I'll try to format it later when I'm not on the phone.

    The idea is to call a function with a name and the parameters, when a parameter is passed in. To do this I created a dict with a string as a key and a function as a value.

    # get all filters
    filters = {}
    filters["rotate"]= (rotate,args.rotate)
    filters["gauss"] = (gauss,args.gauss)
    
    
    # list all files in folder (keeping subfolders)
    for file in files:
        #get folders recursively
        path = file
        img = cv.imread(file)
        for filter in filters:
            #run filter passed in
            filters[filter][0](filters[filter][1])
    
    

    The last line is the abomination

    2 votes
    1. [2]
      Comment deleted by author
      Link Parent
      1. ali
        Link Parent
        I'll check it out this week. It might be that I have already changed parts of the code

        I'll check it out this week. It might be that I have already changed parts of the code

        1 vote
    2. [2]
      unknown user
      Link Parent
      You can extend that to any number of arguments by abusing functools.partial: partial(*filters[filter])() I can't decide if that's better or worse :P

      You can extend that to any number of arguments by abusing functools.partial:

      partial(*filters[filter])()
      

      I can't decide if that's better or worse :P

      1 vote
      1. ali
        Link Parent
        I'll check that out, thanks

        I'll check that out, thanks

        1 vote
  4. fishinginthecoy
    Link
    The worst code I've written... I'll describe it instead of sharing it, as it's a bit of an animal to copy and paste here. When I first started programming seriously, I was concurrently learning...

    The worst code I've written... I'll describe it instead of sharing it, as it's a bit of an animal to copy and paste here. When I first started programming seriously, I was concurrently learning C++, bash, and Python. I decided to use all three to write a parser for a specific web page of interest. Not too bad, right? Well, here's what the pipeline looks like:
    C++ program -> generates input for the bash script and calls the bash script using system() -> bash script -> generates link to scrape from input given by C++, as well as handling the directory tree creation, subsequently calls the python program with the link as input -> Python program -> pulls web page, prints it to stdout -> bash program takes over again, parses the printed table value with awk and sed and saves the result to a text file.

    Could probably be re-written in <100 lines of just python, which I need to do, as that monstrosity is still on my github!

    2 votes
  5. unknown user
    (edited )
    Link
    It's relatively tame, but I often find myself writing something like this: f"{hex(n)[2:]:0>2}" It's amazing how hard it is to turn an int into a two-digit hexadecimal number... The most horrible...

    It's relatively tame, but I often find myself writing something like this:

    f"{hex(n)[2:]:0>2}"
    

    It's amazing how hard it is to turn an int into a two-digit hexadecimal number...

    The most horrible code I've had to write was probably this line:

    ipl_image.tostring()
    

    It looks innocuous, right? That line of code should do absolutely nothing. It's meant to turn an image into a "string" (read: stream of bytes), and discard it. But that ipl_image gets passed (via ctypes) to a big, unmaintained C library, and if you remove that line, you'll get a segmentation fault. I still have no idea why it works!

    Edit: on second thought, this is probably the worst code I've ever written:

    // transform display-style math
    f_str = f_str.replace(/\$\$(?!\s)([^$]*?\S)\$\$(?!\d)/gm, function(match, math, offset, string) {
        return "$$" + AMTparseAMtoTeX(math) + "$$"
    })
    
    // transform inline math
    config.displaystyle = false
    f_str = f_str.replace(/(?:^|[^$])\$(?!\s)([^$]*?\S)\$(?!\d|\$)/gm, function(match, math, offset, string) {
      return "$" + AMTparseAMtoTeX(math) + "$"
    })
    

    Regex feels like cheating, but I'll freely admit that I'd have no idea what either of those regexes were meant to do if not for the comment above.

    1 vote
  6. mat
    Link
    This might be some of the dumbest code I've ever written (which I can share, at least, I've done nastier stuff at work), which makes it fairly ugly.... It's supposed to take a series of ints (from...

    This might be some of the dumbest code I've ever written (which I can share, at least, I've done nastier stuff at work), which makes it fairly ugly.... It's supposed to take a series of ints (from a wav file originally) and reduce the amount of them to a preset number. So I might have 1394 numbers and want to turn them into 60 numbers while still keeping roughly the right values for the new set. Or at least keeping the proportions along the series roughly the same. You'll notice I start by just throwing away a load of the data, then doing worse things to what's left.

    The rest of the code, which generates an STL file containing 3D shapes based on the sound, I'm pretty pleased with. But not this bit. It was always supposed to be quick and dirty until I figured out a better way but it is disgustingly dirty.

    ############### holy balls this is a mess.
    # int_data needs to be in the range 0-1 and len() = 360 or 180 or some other factor of 360.
    # trim to be factor of 360
    ef = len(int_data) - (len(int_data) % 360)
    fl = int_data[:ef]
    chop = len(fl)/totalsegs
    cl=0
    sl = []
    
    # take every X items from the wav numbers where X is how many time segcount divides into list length
    for i in range(0,totalsegs):
    	sl.append(fl[cl])
    	cl += chop
    
    ## log transform the short list
    nl=[]
    for n in sl:
    	nl.append(math.log1p(n))
    
    # now normalise to 0-1
    old_min = min(nl)
    old_max = max(nl)
    old_range = old_max - old_min
    nll=[]
    for n in nl:
    	new = round(((n - old_min) / old_range),2)
    	nll.append(new)
    
    ################### end mess'o'balls
    
    1 vote