Help Bites


  • Banned

    @dkf Status: Was confused by what you mean by that gif, due to what the proboscis monkey symbolizes in Poland.


  • Banned

    @PleegWat said in Help Bites:

    Yeah, I parsed the original as C style.

    Did foreach not tip you off?


  • Discourse touched me in a no-no place

    @Gąska said in Help Bites:

    @PleegWat said in Help Bites:

    Yeah, I parsed the original as C style.

    Did foreach not tip you off?

    #define foreach


  • Banned

    @dkf ... in ...



  • I'm working with a library providing a C interface that has been evolved from a "C++ but mostly C" application written by a guy who had much better understanding of physics he needed to model than software design.

    The header file defines a bunch of structs:

    typedef struct ab_foo { /* ... */ } AB_FOO;
    typedef struct ab_bar { /* ... */ } AB_BAR;
    // more structs
    typedef struct ab_baz AB_BAZ; // used as opaque pointer
    

    and the functions that have to be called in a certain order:

    // this reads the settings file, sets some parameters that cannot be changed later and allocates some memory
    int ab_param_init (const char * ferr_name, const char * f_settings_name, AB_FOO *, AB_BAR *, /* more structs */);
    
    // this fixes some more parameters, allocates more memory and downloads stuff from database
    int ab_frobnicate_init (const char * f_err_name, AB_FOO *, AB_BAR *, double ini_florgle, AB_BAZ ***, /* more struct pointers */);
    
    // probably the most important function
    // can be called repeatedly after setting some structure fields that still can be changed
    // fills a different structure with calculated values
    int ab_frobnicate (const char *f_err_name, AB_FOO *, AB_BAR *, AB_BAZ ***, /* ... */);
    
    // and the destructor is three different functions freeing different structures
    void ab_foo_free (AB_FOO *);
    void ab_baz_free (AB_BAR *);
    void ab_free (AB_BAZ ***, /* more struct pointers */);
    

    The file specified by const char * f_err_name is opened by all functions and all error messages are appended there. The file specified by const char * f_settings_name is an INI file that is parsed by a copy of iniparser.

    I am now in a position to influence the interface changes. Aside joining the structures in a single Parameter object that can be created with default values set, ditching logging to files and providing a way to set all parameters programmatically without creating an INI file, what else should I (try to) change?


  • :belt_onion:

    @anonymous234 said in Help Bites:

    int main(){
        while(true){
            if(fireAlert() || intruderAlert() || somethingElseAlert()) soundAlarm();
            sleep(500);
       }
    }
    

    Not answering to the actual question, but the design of the existing code is awful. Instead of a busy loop, consider using events, e.g. in some simplified pseudo-c# without code editor:

    private int _houseTemperature;
    
    public delegate void alertDelegate();
    public event alertDelegate OnCriticalTemperatureReached;
    
    public int HouseTemperature {
      get { return _houseTemperature; }
      set { 
        _houseTemperature = value;
        if ( _houseTemperature > 100 ) {
            OnCriticalTemperatureReached ();
        }
      }
    }
    
    int main() {
      OnCriticalTemperatureReached += new alertDelegate(SoundAlarm);
    
      // wait for user input to terminate program
      // ...
    }
    
    static void SoundAlarm () {
       // sound the alarm
    }
    
    

    ... or something like that. Might need threads somewhere. I did not try to run this.

    EDIT: I can actually answer the question: In order to enable/disable the alert, all you need to do is subscribe/unsubscribe from the event



  • @bjolling said in Help Bites:

    Instead of a busy loop, consider using events

    What if the sensors are "pull" rather than "push"? Like you send a message and they respond with the current value (and the lag is very small). Then you'll need a busy loop somewhere no matter what.

    EDIT: I can actually answer the question: In order to enable/disable the alert, all you need to do is subscribe/unsubscribe from the event

    That's a good point. Shows how different coding paradigms can make some problems disappear.

    I think events are one of the nicest C# ideas. By extension, I think the reluctance languages have to adding "syntactic sugar" for higher level concepts like them is holding so many good things back.


  • Banned

    @aitap said in Help Bites:

    I am now in a position to influence the interface changes. Aside joining the structures in a single Parameter object that can be created with default values set, ditching logging to files and providing a way to set all parameters programmatically without creating an INI file, what else should I (try to) change?

    You can put everything that should not be changed after creation behind opaque struct, so users cannot change them even if they try to. Also, this triple pointer looks suspicious - I'm assuming it's some kind of nested array; consider making it flat array.



  • @Gąska said in Help Bites:

    You can put everything that should not be changed after creation behind opaque struct, so users cannot change them even if they try to.

    Good idea, thank you.

    Also, this triple pointer looks suspicious - I'm assuming it's some kind of nested array; consider making it flat array.

    Yeah, it's a pointer to an "array of arrays". The code we currently have first allocates an array of pointers, then allocates a bunch of actual arrays, then stores it all using the provided pointer. Life is fun.


  • Discourse touched me in a no-no place

    @bjolling said in Help Bites:

    I did not try to run this.

    Yep. What happens when you try to sound the alarm when the alarm is already sounding? When should the alarm stop sounding? (You've written a level event, not a critical threshold event.)


  • :belt_onion:

    @dkf said in Help Bites:

    @bjolling said in Help Bites:

    I did not try to run this.

    Yep. What happens when you try to sound the alarm when the alarm is already sounding? When should the alarm stop sounding? (You've written a level event, not a critical threshold event.)

    Good question. Peer review makes for better code 😇

    Out of genuine curiosity: how do you define a "level event" versus a "critical threshold event". I did a simple Google search but it referred me back to your comment.


  • Discourse touched me in a no-no place

    @bjolling said in Help Bites:

    Out of genuine curiosity: how do you define a "level event" versus a "critical threshold event". I did a simple Google search but it referred me back to your comment.

    At a minimum, remember the previous value. When a set changes from below the critical threshold to above it, fire an event. When a set changes from above to below, fire a separate event (or fire the first event with a PANIC_OVER flag; whatever works for you). It's basic control systems theory, whether you're level sensitive or edge sensitive.



  • I'm trying to do some stuff the hard way in .NET to learn.

    Suppose I have a IEnumerable that's a list of characters like "H" "e" "l" "l" "o" ";" "w" "o" "r" "l" "d". I want to take characters until each ";" and joint them in one string, then repeat, equivalent to string.Join(list).Split(';'). Is there any reasonable way to do this with LINQ, with only one enumeration?

    I'd need an operator that can aggregate multiple elements, but not all of them. Or equivalently, an N to M transformation.


  • Considered Harmful

    @anonymous234


  • 🚽 Regular

    I've been successfully nerd-sniped.
    	return chars
    		.Aggregate((true, new List<string>()), (state, c) => {
    			if (state.Item1){
    				state.Item2.Add("");
    				state.Item1 = false;
    			}
    			if(c == ';'){
    				state.Item1 = true; 
    			} else {
    				state.Item2[state.Item2.Count-1] += c;
    			}
    			return state;
    		})
    		.Item2;
    

  • Banned

    @Zecc why bother with LINQ at this point? Just write regular for loop.


  • 🚽 Regular

    @Gąska said in Help Bites:

    @Zecc why bother with LINQ at this point? Just write regular for loop.

    I like using LINQ instead of just some basic iterator because I think the resultant code generally looks cleaner. I just wish select was called transform or project or something, 'select' is pretty inaccurate for what it can do.


  • Banned

    @Cursorkeys said in Help Bites:

    @Gąska said in Help Bites:

    @Zecc why bother with LINQ at this point? Just write regular for loop.

    I like using LINQ instead of just some basic iterator because I think the resultant code generally looks cleaner.

    Generally. Not in this specific case.

    @Cursorkeys said in Help Bites:

    I just wish select was called transform or project or something, 'select' is pretty inaccurate for what it can do.

    Most other languages call it map. Yeah, I'm not a fan of LINQ naming conventions either - but you must remember the major selling point of LINQ, back when it was brand new, was that you can treat your collections as if they were SQL tables and write SQL queries on them inline in your C# code (they still thought it makes sense back then). LINQ's Select does pretty much what SQL's SELECT does.

    Edit: I wonder how many C# programmers today would know that from x in Enumerable.Range(0,10) where x % 2 == 0 select x+3 is valid C# code.


  • Considered Harmful

    SetConsoleCtrlHandler(CtrlHandlerPtr, false) blocks indefinitely when the managed delegate CtrlHandler has been called once (regardless of the return value).

    Nothing of particular importance, might as well be WONTFIX, but... any ideas what I'm on about?



  • @Zecc I ended up making myself a new JoinedEnumerable class to do the hard part. Could probably have been a IEnumerable extension method to fit with LINQ but this works well too.

    Behold!
    public class JoinedEnumerable<T>: IEnumerable<IEnumerable<T>>
    {
        private readonly IEnumerable Source;
        private readonly Func<T, bool> EndSequenceFunction;
        public JoinedEnumerable(IEnumerable source, Func<T, bool> endSequenceFunction)
        {
            Source = source;
            EndSequenceFunction = endSequenceFunction;
        }
        public IEnumerator<IEnumerable<T>> GetEnumerator()
        {
            List<T> res = new List<T>();
            foreach(T item in Source)
            {
                res.Add(item); //separator is included in the output in this implementation
                if (EndSequenceFunction(item)) {
                    yield return res;
                    res = new List<T>();
                }
            }
            yield return res;
        }
        IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException("Fuck your non-generics");
    }
    

    Use:

    var letters = new List<char> { 'H', 'e', ';', 'l', 'l', 'o', ';', 'w', 'r', 'l', 'd' };
    
    IEnumerable<IEnumerable<char>> ListOfListsOfLetters =  new JoinedEnumerable<char>(letters, l => l == ';');
    IEnumerable<string> ListOfWords =
        ListOfListsOfLetters.Select(
        (IEnumerable<char> listOfLetters) =>
            listOfLetters.Aggregate(
                new StringBuilder(), //optimization!
                (StringBuilder sb, char c) => { sb.Append(c); return sb; },
                (sb) => sb.ToString()
                )
        );
    foreach (string word in ListOfWords) Debug.WriteLine(word);
    

  • Considered Harmful

    @anonymous234

    @Gąska said in Help Bites:

    why bother with LINQ at this point? <capslock>Just write regular for loop.</capslock>

    For want of LINQ teh millisecondz was lost
    (and for millisecondz 15 minutes were lost)

    static List<string> Stringify(this IEnumerable<char> chars, char split)
    {
        var list = new List<string>();
        var data = chars.ToArray();
        var end = data.Length - 1;
            for (int i = 0, j = 1, k = 0; i <= end; i++, j++)
            {
                if (data[i] == split)
                {
                    list.Add(new string(data, k, j));
                    j = 1;
                    k = ++i;
                }
                else if (i == end)
                    list.Add(new string(data, k, j));
            }
        return list;
    }
    
    // does not preserve the ';'
    Time(10000000, () => { var list = new string(letters.ToArray()).Split(';'); foreach (string str in list) ; })
    1369 ms
    
    Time(10000000, () => { var list = letters.Stringify(';'); foreach (string str in list) ; } )
    1724 ms
    
    // does not preserve the ';'
    Time(10000000, () => { var list = what @Zecc wrote...; foreach (string str in list) ; }
    4721 ms
    
    Time(10000000, () => { foreach (string word in ListOfWords) ; })
    7401 ms :eek:
    

     
    (Paging @Zecc FOOOOM)



  • Necromancy!Post-mortem communications!

    I found myself in the position today of having to add a full-width content block to pages in a (responsive) template that has a max-width wrapper.
    I could have changed the template to a full-width one, then hunted down the code for the rest of the page and tried to adapt it to work with the template (it wasn't simply the width, some of the styling was not being applied). But for a combination of reasons that really wasn't practical today.
    So I came up with this bit of CSS, which worked absolutely beautifully when added in the dev tools:

    .full-width {
        width: 100vw;
        margin: 0 calc(50% - 50vw);
    }
    

    So long as the parent is central, this works responsively, arbitrary margin, arbitrary widths, arbitrary heights (as opposed to messing around with absolute positioning). I'm sure there's ways to thwart it and it would become tricky if you didn't want the full width of the page but that of some ancestor, but for my purposes, beautiful. I usually feel like I've failed a little but if I have to resort to calc() but given what I'm trying to do, I was pretty happy with it. Useful little unit, vw.

    Trouble is, I'm working with Less (which I've never worked with before), and at some point between putting my little bit of CSS into one of the Less source files, and it showing up in the browser, the horizontal margin was converted to calc(0%) which is quite spectacularly pointless. I didn't have time to investigate today but I assume it's the Less compiler that's doing it.
    I can probably do it with inline style and in the circumstances, that's not a big deal. But I am curious as to :wtf: is going on and whether there's any way to stop it. Or any better/other way to achieve the desired effect.



  • As it turns out, it is possible to escape strings in Less and stop the compiler "evaluating" the contents of calc:

    .full-width {
        width: 100vw;
        margin: 0 calc(~'50% - 50vw');
    }
    


  • Double post during possible server cooties attack.


  • Banned

    In C#, how do I get the name of CultureInfo's language, but only the language and not the whole culture?


  • And then the murders began.

    @Gąska This is the best I can do, assuming your original CultureInfo is called origCulture:

    var language = new CultureInfo(origCulture.TwoLetterISOLanguageName, false).DisplayName;

    Basically, construct a new CultureInfo without the region and then use the name from that.

    Actually, you don't even need to construct a new one:

    var language = origCulture.Parent.DisplayName;

    Or if you want to be really thorough:

    var lanuage = (origCulture.IsNeutralCulture ? origCulture : origCulture.Parent).DisplayName;


  • Banned

    @Unperverted-Vixen well...

    MSDN said:

    Remarks

    The cultures have a hierarchy in which the parent of a specific culture is a neutral culture, the parent of a neutral culture is the InvariantCulture, and the parent of the InvariantCulture is the invariant culture itself. The parent culture encompasses only the set of information that is common among its children.

    So while technically very incorrect, I guess it's close enough for Europe. Thanks!



  • Does anyone have multiple email accounts for security? Is that a reasonable measure or is it overkill?

    I've actually had this setup for years with my PayPal and other various accounts, but when I look back it it just feels like more inconvenience than security.


  • Banned

    @anonymous234 I do. Partly so the hacked main email doesn't fuck everything up, partly so a brute-forcing script kiddie doesn't lock me out of my money, in case the provider has a bullshit "security" measure against too many failed logins.


  • Notification Spam Recipient

    @anonymous234 said in Help Bites:

    Does anyone have multiple email accounts for security? Is that a reasonable measure or is it overkill?

    I wouldn't consider it "security", they both have each other marked as "recovery" (perhaps I should change that?)

    I've slowly let die 15 legitimate email accounts over the years.



  • @anonymous234 In the IT-literate crowd of TD:wtf:, I'd be surprised if there are many people who do not have several emails (and use them for different services), even after excluding personal vs. business addresses. I certainly do. The question is more whether that is the result of a voluntary security setup, or just the semi-organic way our use of email has grown.

    In my case, I have 3 personal emails that I got for various reasons not related to security (and that I still regularly use... there are more created along the years but they're mostly dead), but I do tend to split their use roughly according to security/confidentiality nowadays. Address 1 is used for the closest circle i.e. close friends and family, and a few select services (banking, mostly). Address 2 is used for random friends and the bulk of all online activity. Address 3 is basically a spam folder, I use it for throwaway conversations with strangers (like asking a single support question to a company/individual) and commercial sites that force me to register but where I'm not planning to return any time soon.

    I don't try very hard to keep the 3 separated, mostly because it's impossible to draw a clear-cut line between what is "sensitive" information and what is not. For example the article says that your Facebook account is not sensitive information (assuming you have one, which I don't, but obviously many people do...), but arguably someone who really wants to hack you would have access to a huge amount of personal information by accessing it (depending on how you use Facebook, of course). Potentially you could also factor in the risk of the address being leaked (some sites are more trustworthy than other), and the risk of losing control of an address (e.g. given the way my bank uses my email, i.e. almost never and not for anything of importance, I wouldn't be at much risk if someone took control of that email address).

    For me, rather than security, it's more a convenience thing: Address 1 is the one where useful/important info comes through, the other are more like various degrees of spam, I can check them once in while (except e.g. if I've ordered something and I'm waiting for it). This way I can keep email input to a minimum.


  • Discourse touched me in a no-no place

    @remi said in Help Bites:

    The question is more whether that is the result of a voluntary security setup, or just the semi-organic way our use of email has grown.

    Mine started off as separation of the more important stuff but I got a bit slack and now it's just two email addresses.


  • Banned

    @loopback0 same here. I try to split it so one is money-related and the other money-unrelated, but I didn't always manage to stick to this rule.



  • @anonymous234 said in Help Bites:

    Does anyone have multiple email accounts for security?

    used to. now i make heavy use of +suffixes in my gsuite address, as well as the fact that since it is a gsuite address my email is really just the canonical name for the catchall inbox at the domain, so i can make up my own email addresses on the spot.

    need one for paying the gas bill? gascompany@domain.fox works. bam!

    banking? money@domain.fox woo!

    want to be a bit more personal? vixem+shopping@domain.fox (that even gets tagged Shopping when it hits my inbox. those + suffixes are awesome)

    all the security and awesomeness of having multiple email addresses, with none of the hassle.



  • @Vixen said in Help Bites:

    catchall inbox at the domain, so i can make up my own email addresses on the spot.

    This. Although not for security so much as tracking who's sharing/leaking my data. It doesn't really work, though; nearly all my spam comes to my primary address.



  • @HardwareGeek said in Help Bites:

    It doesn't really work, though; nearly all my spam comes to my primary address.

    and that's where the German VPN endpoint comes in so I can invoke GDPR as one who is "in" the EU.

    okay so maybe a VPN won't stand up in court as qualifying for GDPR protections.... and maybe i'm a bad and evil fox for abusing the GDPR as a big stick for getting off spam lists..... but if imma going to actually do that i'll have already tried the nice ways to get you to stop emailing me.... and waited a reasonable amount of time so any mass emails you'd already scheduled will reasonably have already been sent out (two weeks typically, though for political organization i have been known to be as short tempered as ten minutes)

    so if you're still emailing me enough for me to get that snippy....... y'all had it coming.

    and if after i try GDPR on you you bet your ass i'm adding an email rule to forward your emails to abuse@gmail, abuse@hotmail, abuse@yahoo, and abuse@spamhaus to get you all on the naughty spammer lists. because if the GDPR threat doesn't get your attention and you're still emailing me after 90 days or so (because i do try to be nice and give you time to get me off your lists) then the sudden undeliverability of most of your marketing mailings will make you sit up and pay attention.


  • Banned

    @Vixen said in Help Bites:

    the sudden undeliverability of most of your marketing mailings will make you sit up and pay attention.

    As if.


  • BINNED

    @Vixen I always thought the +Suffix idea is neat in theory to track who sells your data, but isn’t this well known enough that the spammers will just remove the suffix?



  • @topspin said in Help Bites:

    @Vixen I always thought the +Suffix idea is neat in theory to track who sells your data, but isn’t this well known enough that the spammers will just remove the suffix?

    they don't seem to have caught onto that trick for non gmail domains, and since i pay for gsuite custom domain.........

    maybe they'll eventually catch on..... but not yet.


  • Discourse touched me in a no-no place

    @topspin said in Help Bites:

    @Vixen I always thought the +Suffix idea is neat in theory to track who sells your data, but isn’t this well known enough that the spammers will just remove the suffix?

    Spammers probably not.
    Someone who got your data from various leaks and wanted to link it up? Probably.



  • Is there a way to specify, in Java, that a placeholder in a .properties file should just output the default string representation of whatever is passed in, rather than applying some number format? e.g. if I have common.text.docId=Document #{0}, it works great if I give it a String "12345", but if I use an int 12345 it outputs "Document #12,345"

    All the online resources seem to be dealing with the opposite of what I want, namely how to specify that it should format dates, percentages, currency, etc. I could do something like {0,number,#} but then if I happen to pass a string version, it blows up. I'd rather it default to 12345, then I could optionally specify some number format whenever I actually want it.


  • Discourse touched me in a no-no place

    @hungrier said in Help Bites:

    Is there a way to specify, in Java, that a placeholder in a .properties file should just output the default string representation of whatever is passed in, rather than applying some number format?

    It depends on which substitution engine you're using, as the basic properties file format doesn't support substitutions at all. You appear to be using one that is locale-aware (without setting the current locale to Locale.ROOT).



  • @dkf I'll see if I can figure it out from config classes, but I'm assuming it's the default one used by/included with Spring Framework 5.


  • 🚽 Regular

    @hungrier I hate to be that guy, but what's wrong with passing the number as a string?
    (Identifiers/references should be opaque strings anyway, right?)

    Is it a :kneeling_warthog: thing? I totally understand if it's a :kneeling_warthog: thing.



  • @Zecc Mostly it just adds extra conversion steps, since it's a (sequential) numeric ID in the database. If I don't find a way to just display the .toString representation without any number formatting, I may end up doing that anyway. I haven't checked everywhere but there may not be that many places where I have to go from the page backing object back to the hibernate bean



  • @hungrier said in Help Bites:

    a (sequential) numeric ID

    what application? Maybe they're susceptable to ID Enumeration attacks?



  • @Vixen said in Help Bites:

    what application?

    One that's publicly accessible via unsecured http, and each document contains all known user data including full name, passwords in plain text, credit card info, etc.



  • @hungrier In fact the full localized property is common.text.ive.seen.everything=Document {0}: User {1} {2} with username {3}, password ''{4}'', {5} credit card (number {6}, expiry {7}, security code {8}), birthday {9,date}



  • @hungrier said in Help Bites:

    @Vixen said in Help Bites:

    what application?

    One that's publicly accessible via unsecured http, and each document contains all known user data including full name, passwords in plain text, credit card info, etc.

    /me rubs hands in an evil manner while laughing manaicly

    now you must tell us what it is!

    .....what?

    oh...

    would it really be that evil though?

    it would?

    really?!

    oh.

    ooooooooooooh....

    oh.

    so my plan to..?

    I see.... jail you say?

    uh huh....

    and what's the food like there?


  • Considered Harmful

    Is there a way to preview how an email template will render over the bajillion or so different email clients out there?

    I know the lowest common denominator is like... HTML 3.


Log in to reply