Page 239 of 239

Re: Coding: Fleeting Thoughts

Posted: Tue Feb 21, 2017 6:37 pm UTC
by Yakk
Powers of two and am lazy.

17 gives you a carry bit.

Re: Coding: Fleeting Thoughts

Posted: Tue Feb 21, 2017 8:44 pm UTC
by Xanthir
That's a valid point, sure.

Re: Coding: Fleeting Thoughts

Posted: Fri Mar 17, 2017 12:29 pm UTC
by Xenomortis
git bisect is awesome.
Tracing an odd performance degradation and I would never have suspect the commit it landed on.
And it's neat way to hammer in the difference between binary and linear searches.

Re: Coding: Fleeting Thoughts

Posted: Sat Mar 18, 2017 10:05 am UTC
by The Great Hippo
I keep forgetting I can store references to the same set on different objects.

Like, I had a dictionary that mapped values to a set, but I also wanted the set's contents to be accessible by another object -- so I kept trying to think up a scheme to update the object every time this set changed. For some reason, I completely missed that I can just have the object refer to this set, thereby accessing it directly.

(I know that's kind of dangerous because you now have two places where you can modify the set, but in this context, I'm pretty sure it's okay)

Re: Coding: Fleeting Thoughts

Posted: Sat Mar 18, 2017 11:39 am UTC
by The Great Hippo
Actual coding question:

I'm working with a class that wraps two dictionaries -- one that maps a unique value ("A") to a non-unique value ("b"), and one that maps that non-unique to a set containing all the unique values that are mapped to it. In other words, as one dictionary maps A -> b, another maps b -> {All As mapped to b}.

Does this have a bad smell? I mean, I see a use for it right now -- it solves a major problem and seems really, really useful. But should I be concerned that I'm basically mapping in two directions? Also, is there a name for this sort of mapping? Is it just a normal bijective mapping? It doesn't look like it, since (I think?) bijective mappings must have unique keys and values.

EDIT: Both keys and values are hashable; by 'non-unique', I only mean that A1 -> 5 and A2 -> 5 is valid. Also, maybe this would be describable as an 'invertible' dictionary?

Re: Coding: Fleeting Thoughts

Posted: Sat Mar 18, 2017 12:17 pm UTC
by Tub
The Great Hippo wrote:(I know that's kind of dangerous because you now have two places where you can modify the set, but in this context, I'm pretty sure it's okay)

Either wrap all related sets in another class, which guarantees that additions/deletions are propagated correctly, or (in C++) use a combination of shared_ptr and weak_ptr.

As for your other question, it's not even close to a bijection. It's neither injective nor surjective.

If it's not performance critical, your implementation is ok. It's possible to create a composite data structure that makes updates cheaper and removes redundancy, but it's probably not worth it.

Re: Coding: Fleeting Thoughts

Posted: Sat Mar 18, 2017 1:30 pm UTC
by WorldTradeRichard
http://mentalfloss.com/article/26316/why-does-my-gadget-say-its-december-31-1969 wrote:Unix is a computer operating system that, in one form or another, is used on most servers, workstations, and mobile devices. It was launched in November 1971 and, after some teething problems, the “epoch date” was set to the beginning of the decade, January 1, 1970. What this means is that time began for Unix at midnight on January 1, 1970 GMT. Time measurement units are counted from the epoch so that the date and time of events can be specified without question. If a time stamp is somehow reset to 0, the clock will display January 1, 1970.


So where does December 31 fit in? It’s because you live in the Western Hemisphere. When it’s midnight in Greenwich, England, it’s still December 31st in America, where users will see December 31, 1969—the day before Unix’s epoch.


I know it's probably been said, in the few years I missed to answer, but that's why it always resets to 1969.
additionally, This question makes me think that all Unix systems, i.e.

(everything)

stops making more dates at that time, probably for memory reasons or something. no clue.

Sorry about the randomness of that.

Re: Coding: Fleeting Thoughts

Posted: Sun Mar 19, 2017 3:52 pm UTC
by PM 2Ring
The Great Hippo wrote:Actual coding question:

I'm working with a class that wraps two dictionaries -- one that maps a unique value ("A") to a non-unique value ("b"), and one that maps that non-unique to a set containing all the unique values that are mapped to it. In other words, as one dictionary maps A -> b, another maps b -> {All As mapped to b}.

Does this have a bad smell? I mean, I see a use for it right now -- it solves a major problem and seems really, really useful. But should I be concerned that I'm basically mapping in two directions? Also, is there a name for this sort of mapping? Is it just a normal bijective mapping? It doesn't look like it, since (I think?) bijective mappings must have unique keys and values.

EDIT: Both keys and values are hashable; by 'non-unique', I only mean that A1 -> 5 and A2 -> 5 is valid. Also, maybe this would be describable as an 'invertible' dictionary?


It's a Good Idea to mention which language you're using. IIRC, you use Python. Some languages may have better ways to handle that, but what you're doing is fine in Python. Although I guess you could wrap it in a class to make it cleaner. That way you're bundling the two dicts into one object which can have methods that let you manipulate both dicts in one operation.

Re: Coding: Fleeting Thoughts

Posted: Mon Mar 20, 2017 6:11 pm UTC
by pogrmman
PM 2Ring wrote:
The Great Hippo wrote:Actual coding question:

I'm working with a class that wraps two dictionaries -- one that maps a unique value ("A") to a non-unique value ("b"), and one that maps that non-unique to a set containing all the unique values that are mapped to it. In other words, as one dictionary maps A -> b, another maps b -> {All As mapped to b}.

Does this have a bad smell? I mean, I see a use for it right now -- it solves a major problem and seems really, really useful. But should I be concerned that I'm basically mapping in two directions? Also, is there a name for this sort of mapping? Is it just a normal bijective mapping? It doesn't look like it, since (I think?) bijective mappings must have unique keys and values.

EDIT: Both keys and values are hashable; by 'non-unique', I only mean that A1 -> 5 and A2 -> 5 is valid. Also, maybe this would be describable as an 'invertible' dictionary?


It's a Good Idea to mention which language you're using. IIRC, you use Python. Some languages may have better ways to handle that, but what you're doing is fine in Python. Although I guess you could wrap it in a class to make it cleaner. That way you're bundling the two dicts into one object which can have methods that let you manipulate both dicts in one operation.


I second building it into a class. It would not be good if you had to remember to modify one after modifying the other. Its best to write methods that do both.

Re: Coding: Fleeting Thoughts

Posted: Tue Mar 21, 2017 3:01 pm UTC
by The Great Hippo
Thanks! I ended up wrapping two dicts in a class, yeah -- and overloading their __set__ and __del__ built-ins (regrettably, using 'update' -- or other methods like it -- will prolly break the dict, but since this is for my own use, I'm not too concerned).

Semi-related: I've been struggling with the notion of submitting my own PEP for Python; it's probably doomed to failure, but it'd be nice to try something. It's to solve a problem I keep encountering and having to find creative ways to code around. Specifically, it has to do with the variable positional and variable keyword arguments:
Spoiler:

Code: Select all

def foo(*args, **kwargs):
    pass
This function will accept an arbitrary number of positional arguments and keyword arguments. So anything from...

Code: Select all

foo()
...to...

Code: Select all

foo(1, 2, 3)
...to...

Code: Select all

foo(1, 2, 3, keyword="Hello!")
...to...

Code: Select all

foo(keyword="Hello!")
...are all permissible. The positionals are stored in a tuple (in this case, args), and the keywords in a dict (in this case, kwargs). This is super-useful, and I deploy it a lot in my code.

However: Sometimes, I want to use variable keyword arguments with non-variable positional arguments. So I want...

Code: Select all

def foo(a, b, **kwargs):
    pass
...which means I need at least two positionals (in this case, a and b) and an arbitrary number of keywords. Cool! Except what if I want to use 'a' or 'b' as possible keyword arguments? Well...

Code: Select all

foo(1, 2, a=0, b=0)
...is not permissible; it raises a TypeError (because I can't both have 'a' and 'b' as positionals and use them as keyword arguments).

So, I guess the solution is 'use names for your positionals you know you'll never use for keywords' -- but what if I have no idea what keywords I'll be using, yet? When I have a **kwargs, why can't that **kwargs contain labels that are also shared by positionals?

I realize this seems like a pretty slim use-case, but I've seen it come up a couple of times -- particularly where you're trying to use a function or class to produce objects with arbitrary attribute assignments (so you're using **kwargs to basically assign attributes). If you have any positional arguments, whatever name you use for those positional arguments cannot be keywords.


EDIT:
Spoiler:
--and actually, using **kwargs to assign attributes to objects is super-helpful, because **kwargs only accepts string to object assignment -- which means you can't use **kwargs to assign attributes and somehow manage to stash a non-string in the object's __dict__. So you eliminate a whole subclass of possible errors by using **kwargs instead of just passing a dictionary through a function. So yeah, it's a slim use-case, but it's still a pretty useful functionality to have?

Re: Coding: Fleeting Thoughts

Posted: Tue Mar 21, 2017 10:41 pm UTC
by firechicago
I understand the problem you're running into, but I'm not sure I understand what you think the actual behavior should be. If you have

Code: Select all

def foo(a, b, **kwargs):
    return a

foo(1, 2, a=0)

what should that last line return? 1? 0? 0.5? choose one at random?

I feel like this is a perfect example of what Douglas Crockford likes to call "foot-guns", i.e. language features that are perfectly calibrated to ruin your day if you don't handle them extra carefully.

Spoiler:
Also, is there a reason you can't just do something like

Code: Select all

def foo(a, b, dict):
and then explicitly reach into the dict when you need to access those variables?

Re: Coding: Fleeting Thoughts

Posted: Wed Mar 22, 2017 1:34 am UTC
by The Great Hippo
It should return one.

Code: Select all

def foo(**kwargs):
    return a

foo(a=0)
This returns a NameError; the contents of kwargs are not loaded into foo's namespace implicitly. To access them, you must go through kwargs:

Code: Select all

def foo(**kwargs):
    return kwargs["a"]

foo(a=0)
As for why -- **kwargs has some extra benefits in Python 3 (such as preserving order), and by using it, you avoid the risk of accidentally mutating a dictionary (or the pain of having to define a new dictionary every time you just want to call a function).

Re: Coding: Fleeting Thoughts

Posted: Wed Mar 22, 2017 2:34 am UTC
by Flumble
Why does python have this named parameter thing in the first place? The language allows for pretty JSONic notation that only takes a few characters extra. They could've invested time in pattern matching on dicts/named tuples/records rather than supporting this variadic-in-positional-and-named-arguments monstrosity. Even worse, TIL they removed pattern matching power.

Re: Coding: Fleeting Thoughts

Posted: Wed Mar 22, 2017 2:44 am UTC
by The Great Hippo
Being able to perform easy introspection on functions is super important, though? Especially when you're dealing with stuff like callbacks (where you can store a function with the wrong number of parameters and never find out until it fires much, much later). Pretty sure they got rid of it to expand on inspect.Signature, which -- though a bit bulky and sometimes awkward -- makes function introspection much easier and straightforward.

I don't have a lot of experience with function parameters outside of Python, but -- aside from what I'm talking about now -- I've never encountered any major problems. Python even supports function notation (and through it, I'm pretty sure you can implement pattern checking -- or even type checking, if you'd really like).

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 4:10 am UTC
by chridd
Possible workaround?

Code: Select all

def foo(*args, **kwargs):
   (a,b) = args
   ...

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 8:14 am UTC
by The Great Hippo
I was about to say that's the workaround I typically use, but I don't like it because it doesn't raise errors when you fail to provide the appropriate number of positionals (less or more than two). But then I realized that since you're unpacking the tuples into two values, it will raise an error -- just not the type of error you'd expect. So, actually, yeah, that's a pretty great workaround, thanks! I'd only make one slight modification:

Code: Select all

def foo(*args, **kwargs):
    try:
        a, b = args
    except ValueError as e:
        raise TypeError(e)
This is just so I get a TypeError, which is what I expect when I feed a function the wrong number of arguments.

(which I realize is... probably some pretty fine hair-splitting on my part. Regardless, yes, that works very well, thank you!)

This even covers the rather narrow use-case of times when I want one of my 'anonymous' positionals to have a default value:

Code: Select all

def foo(*args, **kwargs):
    try:
        a, b = args
    except ValueError:
        try:
           a, b = args[0], None
        except IndexError as e:
            raise TypeError(e)

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 8:44 am UTC
by Maelstrom.
The Great Hippo wrote:This even covers the rather narrow use-case of times when I want one of my 'anonymous' positionals to have a default value:

Code: Select all

def foo(*args, **kwargs):
    try:
        a, b = args
    except ValueError:
        try:
           a, b = args[0], None
        except IndexError as e:
            raise TypeError(e)


This misbehaves when there are >2 args:

Code: Select all

>>> args = (1, 2, 3)
>>> a, b = args
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> a, b = args[0], None
>>> a
1
>>> b
None


I would expect this to fail when len(args) > 2

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 12:29 pm UTC
by Xenomortis

Code: Select all

// BaseClass x = ... assigned from some where
Object thing;
if (x instanceof ClassA) {
  thing = do_A_things((ClassA) x)
} else if (x instanceof ClassB) {
  thing = do_B_things((ClassB) x)
} else if (x instanceof ClassC) {
...

} else throw Exception();


vs

Code: Select all

Map<Class<?>, Function<Class<?>, Object> functions = new Hashmap....;
functions.put(ClassA.class, y -> do_A_things((ClassA) y);
functions.put(ClassB.class, y -> do_B_things((ClassB) y);
...
Object thing = functions.get(x.getClass()).apply();


The latter is definitely more cool, but is it better? It resembles virtual dispatch quite a bit, but we don't control ClassA/B/C...

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 5:38 pm UTC
by The Great Hippo
Maelstrom. wrote:I would expect this to fail when len(args) > 2
Oops; pardon, yeah -- I didn't even bother trying to test that code to see if it works.

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 7:40 pm UTC
by Flumble
Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)

Re: Coding: Fleeting Thoughts

Posted: Thu Mar 23, 2017 10:43 pm UTC
by Xenomortis
Flumble wrote:Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)


I don't know Java's type rules well enough to answer that.
What I do know is that "Object" is passed around alarmingly liberally in this "greenfield" project.

Edit:
I've gone for the "cool" thing, partly to test my suspicions that certain people aren't actually "reading" the diffs on Github pull requests.
Sometimes, I'm not a nice person.

Re: Coding: Fleeting Thoughts

Posted: Fri Mar 24, 2017 1:11 am UTC
by chridd
Flumble wrote:Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)
Pretty sure Java overloads are determined at compile time.

Code: Select all

$ cat OverloadTest.java
public class OverloadTest {
   public static void doThing(Object o) {
      System.out.println("doThing(Object)");
   }
   public static void doThing(String s) {
      System.out.println("doThing(String)");
   }
   public static void main(String[] args) {
      Object o = "hello";
      doThing(o);
   }
}
$ java OverloadTest
doThing(Object)

Re: Coding: Fleeting Thoughts

Posted: Fri Mar 24, 2017 3:30 pm UTC
by Sizik
chridd wrote:
Flumble wrote:Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)
Pretty sure Java overloads are determined at compile time.

Code: Select all

$ cat OverloadTest.java
public class OverloadTest {
   public static void doThing(Object o) {
      System.out.println("doThing(Object)");
   }
   public static void doThing(String s) {
      System.out.println("doThing(String)");
   }
   public static void main(String[] args) {
      Object o = "hello";
      doThing(o);
   }
}
$ java OverloadTest
doThing(Object)


Otherwise you couldn't do this:

Code: Select all

   public static void main(String[] args) {
      String s = "hello";
      doThing((Object)s); // prints "doThing(Object)"
   }

Re: Coding: Fleeting Thoughts

Posted: Fri Mar 24, 2017 3:33 pm UTC
by Flumble
chridd wrote:
Flumble wrote:Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)
Pretty sure Java overloads are determined at compile time.

Thanks, I had no idea overloading would be done statically.


Sizik wrote:Otherwise you couldn't do this:

Code: Select all

   public static void main(String[] args) {
      String s = "hello";
      doThing((Object)s); // prints "doThing(Object)"
   }

...which is completely reasonable because casting to a superclass to call another overload is stupid. :P

Re: Coding: Fleeting Thoughts

Posted: Fri Mar 24, 2017 3:42 pm UTC
by Xenomortis
chridd wrote:
Flumble wrote:Xenomortis, can you define some kind of local function do_things :: BaseClass -> Object with overloads for the specific classes? (The program will still call the most specific overload, regardless of whether the object was bound to a variable of a superclass type in between, right?)
Pretty sure Java overloads are determined at compile time.

Of course they are.
Otherwise we wouldn't need the confusingly named "visitor" pattern (for double-dispatch).

Re: Coding: Fleeting Thoughts

Posted: Sat Mar 25, 2017 1:47 am UTC
by phlip
Yeah, as Xenomortis alludes, the magic word here is single dispatch... which method is actually called is based on the actual runtime type of the "this" parameter (ie: calling overridden methods in subclasses) but all of the other parameters are bound statically based off their declared types.

Code: Select all

class Sup {
  public String foo(Sup x) {
    return "Sup.foo(Sup)";
  }
}
class Sub extends Sup {
  public String foo(Sup x) {
    return "Sub.foo(Sup)";
  }
  public String foo(Sub x) {
    return "Sub.foo(Sub)";
  }
}

Sup sup = new Sup();
Sub sub = new Sub();
Sup subAsSup = new Sub();

System.out.println("sup.foo(sup) -> " + sup.foo(sup));
System.out.println("sup.foo(sub) -> " + sup.foo(sub));
System.out.println("sup.foo(subAsSup) -> " + sup.foo(subAsSup));
System.out.println("sub.foo(sup) -> " + sub.foo(sup));
System.out.println("sub.foo(sub) -> " + sub.foo(sub));
System.out.println("sub.foo(subAsSup) -> " + sub.foo(subAsSup));
System.out.println("subAsSup.foo(sup) -> " + subAsSup.foo(sup));
System.out.println("subAsSup.foo(sub) -> " + subAsSup.foo(sub));
System.out.println("subAsSup.foo(subAsSup) -> " + subAsSup.foo(subAsSup));