Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue Aug 13, 2013 5:38 pm UTC

Thesh wrote:
3fj wrote:That's certainly part of it. I've got more experience with C than with C++, so I'm biased towards the format specifiers way of doing things. That said, I still don't think it's beneficial to make the parsing of a string any more complex than it already is. If you have a function that you wish to run, I think it's more easily read when separated out from the string. And as I pointed out earlier, to me plaintext readability should be the minimum level that we're thinking about.


The main benefit is type safety; this is where C has its problems. That, and the lack of portability given that Windows and Linux use different format specifiers for 64-bit integers. If you are using a recent version of VIsual Studio, you finally have inttypes.h and stdint.h for cross-platform programming, but PRI* macros just look like they should be a syntax error: printf("%"PRId64"\n",x);

I still think you're undervaluing extensibility to user-defined types, and to get that with a remotely reasonable syntax you need either (1) templates (preferably either variadic templates or member templates) or (2) "abuse" of operator overloading.

At least to me, I really think there's no syntax you could propose that is better than << and >> enough that you'll get me to give up extensibility for it, short of implementing in the compiler either (1) mind reading or (2) magic, which means that looking through a historical lens, the design of iostreams was IMO by far the best possibility at the time it was created. Once templates were around, the question was not so much "can we do better than iostreams" but "are the alternatives to iostreams better enough to add a new mechanism".

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

Re: Coding: Fleeting Thoughts

Postby korona » Tue Aug 13, 2013 5:55 pm UTC

You could create your own type safe $ function (using another name of course) using templates and polymorphic type erasure. This would yield a syntax similar to

Code: Select all

std::string x = my_print("hello %s, here is pi: %f\n", "world", 3.14);

You could also add named parameters. I wouldn't mind if such a function was added to the standard library if it supported custom types and custom memory allocators. But it really has no place as a language construct.

jareds
Posts: 436
Joined: Wed Jan 03, 2007 3:56 pm UTC

Re: Coding: Fleeting Thoughts

Postby jareds » Wed Aug 14, 2013 5:37 am UTC

Yakk wrote:If you know your list consists of 32 bit ints, loading it into a std::map< int, counter > is linear time.

Each lookup in the std::map will take no more than lg(2^32) time. For each int in our input, we look it up in the map, then increment the counter. O(N).

Then we iterate over the map and print out counter copies of each int. O(N)

I believe you can do the same with merge sort, adding a counter, and when you run into adjacent identical elements, merging them into one entry with a counter.

The magic of radix sort isn't that it is linear time on fixed size data: but it is linear time with a relatively low constant on such data. The granularity of fixed sized data violates the preconditions of the comparison sort proof that it must takes n lg n time: once you rework your comparison sort to take into account common duplicates, comparison sort can be sped up to linear time.

While this is all correct for the degenerate case that you analyzed, the superiority of non-comparison sorts to comparison sorts does hold asymptotically in the general case. The true magic of radix sort is that it opens the black box and exploits the lexicographic structure of the keys.

Say we are sorting n strings of length k. A comparison sort will perform O(n log n) comparisons of cost O(k), for a running time of O(n k log n). A radix sort will have running time of O(n k). Strings are great as both a theoretical and a practical example. See Sedgewick's "multikey quicksort", aka "three-way radix quicksort" or maybe "ternary quicksort". This is a hybrid quicksort that proceeds one key (or character) at a time, for a running time of O(n k + n log n) (typically with a better constant on the nk than radix sort, but in any event asymptotically better than a comparison sort) (this being quicksort, you still have to randomize or use a true median selection to get this sub-quadratic time). I had good success replacing a regular quicksort with such a radix quicksort in a use case with strings that were fairly long and generally had many groups of strings with longish identical prefixes.

Or go back to the integer example. Say that instead of 32-bit integers, you have (log n)-bit integers. Then a comparison sort is back at O(n log n) in a standard unit-cost model, but a radix sort is O(n). (You can, for example, do radix sort for digits with (log n)/c bits for some constant c. This is valid since the number of buckets scales with the cth root of n, so c does not need to increase as n increases on either theoretical or practical grounds.) A log-cost model bumps them both up by a factor of log n, so that doesn't make a difference.

User avatar
3fj
Posts: 1715
Joined: Wed Jun 11, 2008 1:13 pm UTC
Location: Land of Whisky and Bagpipes (LOWAB)
Contact:

Re: Coding: Fleeting Thoughts

Postby 3fj » Wed Aug 14, 2013 9:12 am UTC

Thesh wrote:If you are using a recent version of VIsual Studio, you finally have inttypes.h and stdint.h for cross-platform programming, but PRI* macros just look like they should be a syntax error: printf("%"PRId64"\n",x);

Yeah, fair enough. Type safety can be a pain in the ass, and you're right enough in saying the PRI macros look like garbage. If your point was "If I could magically take everyone back to the inception of C++ while removing parts I don't like" then I guess I would agree with you in theory.

Thesh wrote:Personally, I hate both C++ and PHP, and prefer C# and C.

We are kindred spirits, you and I :P
Everything's dead until it's alive. Man will exist, and then he will die. Just take the ride!

User avatar
skeptical scientist
closed-minded spiritualist
Posts: 6142
Joined: Tue Nov 28, 2006 6:09 am UTC
Location: San Francisco

Re: Coding: Fleeting Thoughts

Postby skeptical scientist » Thu Aug 15, 2013 1:30 am UTC

jareds wrote:Say we are sorting n strings of length k. A comparison sort will perform O(n log n) comparisons of cost O(k), for a running time of O(n k log n).

Comparing strings of length k is worst-case O(k), but average-case O(1) as long as your strings are somewhat random.
I'm looking forward to the day when the SNES emulator on my computer works by emulating the elementary particles in an actual, physical box with Nintendo stamped on the side.

"With math, all things are possible." —Rebecca Watson

jareds
Posts: 436
Joined: Wed Jan 03, 2007 3:56 pm UTC

Re: Coding: Fleeting Thoughts

Postby jareds » Thu Aug 15, 2013 6:59 am UTC

skeptical scientist wrote:
jareds wrote:Say we are sorting n strings of length k. A comparison sort will perform O(n log n) comparisons of cost O(k), for a running time of O(n k log n).

Comparing strings of length k is worst-case O(k), but average-case O(1) as long as your strings are somewhat random.

That sentence is true standing alone, but are you sure it's true in the context of a comparison sort of strings? Say your n strings of length k are selected uniformly at random. That doesn't mean that every comparison the sort makes can be treated as if between two uniformly random strings, because the sort's decision of which elements to compare is not random. Consider a few cases:

Quicksort: When you partition a subsequence, all the elements including the pivot will be contiguous in the final array, so comparisons in deeper levels of the recursion will be disproportionately likely to be near each other (i.e., strings with common prefixes).

Mergesort: When you merge two lists, you're deliberately comparing elements that are as near as possible as you move along the lists.

Heapsort: When you fix a node in the heap, you may need to check which of its two children is larger than the other. Each child is the max of its subheap, so they are likely to be near each other.

So, I don't have a proof that your statement is inapplicable to all comparison sorts of strings, but at the very least you would need some serious justification to say that the average comparison in an average-case comparison sort of strings is O(1). Average-case running time cannot be determined by simple composition of the average-case running times of the subproblems, because the algorithm may not invoke the subproblems in a uniform way even if it itself is given uniform input.

(Anyway, I did of course mean the worst case, not the average case. These sorts of difficulties are one of the reasons that average-case analysis is not the default.)

Edit: To be clear, I'm not claiming that the average-case run-time of comparison-sorting n strings of length k is O(n k log n), just that it isn't O(n log n). It's probably something like O(n log(n) min(k, log n)).

User avatar
roband
Posts: 2545
Joined: Tue Sep 21, 2010 2:52 pm UTC
Location: UK

Re: Coding: Fleeting Thoughts

Postby roband » Thu Aug 15, 2013 1:50 pm UTC

I'm trying to use Google App Engine to take some code on GitHub and turn it into a bot which takes posts from my subreddit and posts them onto twitter for me.

Here is what I'm doing: https://github.com/JKirchartz/yinzbot

The instructions were ok, until I got to the point where it came to actually putting the code into Google App Engine. I can't see where to do it for the life of me.
All the directions I can find just say "run <command>" but I don't know where I'm meant to run it.

Please help! :)

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Thu Aug 15, 2013 5:39 pm UTC

roband wrote:I'm trying to use Google App Engine to take some code on GitHub and turn it into a bot which takes posts from my subreddit and posts them onto twitter for me.

Here is what I'm doing: https://github.com/JKirchartz/yinzbot

The instructions were ok, until I got to the point where it came to actually putting the code into Google App Engine. I can't see where to do it for the life of me.
All the directions I can find just say "run <command>" but I don't know where I'm meant to run it.

Please help! :)


Have you tried the actual AppEngine documentation?
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

User avatar
skeptical scientist
closed-minded spiritualist
Posts: 6142
Joined: Tue Nov 28, 2006 6:09 am UTC
Location: San Francisco

Re: Coding: Fleeting Thoughts

Postby skeptical scientist » Fri Aug 16, 2013 6:35 am UTC

jareds wrote:Edit: To be clear, I'm not claiming that the average-case run-time of comparison-sorting n strings of length k is O(n k log n), just that it isn't O(n log n). It's probably something like O(n log(n) min(k, log n)).

Yeah, that's true. I think it's exactly O(n log(n) min(k, log n)).
I'm looking forward to the day when the SNES emulator on my computer works by emulating the elementary particles in an actual, physical box with Nintendo stamped on the side.

"With math, all things are possible." —Rebecca Watson

User avatar
roband
Posts: 2545
Joined: Tue Sep 21, 2010 2:52 pm UTC
Location: UK

Re: Coding: Fleeting Thoughts

Postby roband » Fri Aug 16, 2013 7:59 am UTC

Aaeriele wrote:
roband wrote:I'm trying to use Google App Engine to take some code on GitHub and turn it into a bot which takes posts from my subreddit and posts them onto twitter for me.

Here is what I'm doing: https://github.com/JKirchartz/yinzbot

The instructions were ok, until I got to the point where it came to actually putting the code into Google App Engine. I can't see where to do it for the life of me.
All the directions I can find just say "run <command>" but I don't know where I'm meant to run it.

Please help! :)


Have you tried the actual AppEngine documentation?

I had attemped to do so. I didn't see the specific page you linked - I was looking directly at https://developers.google.com/appengine ... /uploading

Think I must have been distracted by something. Cheers for the simple pointer.

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Sun Aug 18, 2013 6:13 pm UTC

No worries, glad I could help. :)
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Mon Aug 19, 2013 1:00 pm UTC

I borrowed a graphing calculator from a friend so I could re-write my programs from high school of about 10 years ago. At the time I always copied my source code to paper because graphing calculators were very vulnerable at my school and the memory contents even more so. That's why I'm able to re-write the programs at all. These are the first working computer programs I ever wrote.

I remembered that I used stackless jumps for nearly all branching and I knew the code would be messy. However when first reading and re-typing the code after all those years I was still completely baffled by the terrible mess of spaghetti code. It was so hard to comprehend I thought junior Julian must have been really smart to be able to hold all of that in his head! (You may wonder how bad it could be, given that graphing calculator programs tend to be very short. I was an exception, my programs were very large and did fancy things. I loved challenging myself to do something unusual.)

Then when I "got into it" again I started to realize I was just a bad programmer at the time, and the fact I got my stuff to work was despite rather than thanks to my capabilities. In one of my largest programs, by using proper loops and if-else, replacing a reinvented wheel by a builtin, factoring out a lot of duplicate code and using a dash of sensible inlining in one place, I could eliminate two variables and 16 out of 18 labels, reduce the file to half its original size and speed up execution by at least a factor 2. Yes, there were 18 labels and even more gotos.

In defense of my young self, I've also come to realize how very bad a graphing calculator really is as a programming platform. The dialect of BASIC that runs on it sucks, typing ruins your hands, program execution is horribly slow and you get only 127x63 pixels in three colours. I will never, ever again write a new program for this device.

But I think I'll try some more of my old programs for nostalgia. :)
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Mon Aug 19, 2013 1:07 pm UTC

That's not the proper attitude!

What you should do is write a PC-based emulator for the thing.
Image

User avatar
Yakk
Poster with most posts but no title.
Posts: 11128
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Mon Aug 19, 2013 1:35 pm UTC

What you should do is write a PC-emulator that permits arbitrary expansion of the address space, then write a SNES emulator on your graphing calculator.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Mon Aug 19, 2013 3:24 pm UTC

Why is my Javascript code not working! It works for this other block of code, and mine looks just like it! :(
Image

User avatar
skeptical scientist
closed-minded spiritualist
Posts: 6142
Joined: Tue Nov 28, 2006 6:09 am UTC
Location: San Francisco

Re: Coding: Fleeting Thoughts

Postby skeptical scientist » Mon Aug 19, 2013 3:36 pm UTC

Jplus wrote:I remembered that I used stackless jumps for nearly all branching and I knew the code would be messy. However when first reading and re-typing the code after all those years I was still completely baffled by the terrible mess of spaghetti code. It was so hard to comprehend I thought junior Julian must have been really smart to be able to hold all of that in his head! (You may wonder how bad it could be, given that graphing calculator programs tend to be very short. I was an exception, my programs were very large and did fancy things. I loved challenging myself to do something unusual.)

We're the same, you and I. I remember spending most of my time in math class writing games for my graphing calculator (they tended to be fairly simple games, so writing them was way more fun than playing them). One of them was a racing game, which contained 6 nearly-identical copies of the same code with the variable names changed, because I didn't know about arrays. :roll:

At one point I remember discovering a bug in the TI-86 random number generator, where it would get into a steady-state and output the same number every time. I tried to reproduce this bug years later, but didn't manage to do it.
I'm looking forward to the day when the SNES emulator on my computer works by emulating the elementary particles in an actual, physical box with Nintendo stamped on the side.

"With math, all things are possible." —Rebecca Watson

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Mon Aug 19, 2013 4:02 pm UTC

High five!
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Mon Aug 19, 2013 4:12 pm UTC

Jplus wrote:Then when I "got into it" again I started to realize I was just a bad programmer at the time, and the fact I got my stuff to work was despite rather than thanks to my capabilities. In one of my largest programs, by using proper loops and if-else, replacing a reinvented wheel by a builtin, factoring out a lot of duplicate code and using a dash of sensible inlining in one place, I could eliminate two variables and 16 out of 18 labels, reduce the file to half its original size and speed up execution by at least a factor 2. Yes, there were 18 labels and even more gotos.
There were proper loops? I just used goto-labels I think. :shock:

My programs were actually fairly structured for what they were at the time. But most of my programming involved solve-this-for-me-formula-machines. I think most of the people in my school had my version of the quadratic formula since you could copy from one calculator to another... :mrgreen:

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Tue Aug 20, 2013 12:25 pm UTC

Xeio wrote:There were proper loops? I just used goto-labels I think. :shock:

Well, they existed in Casio Basic. I don't know whether the same is true of TI Basic.

The funny thing is, I knew about the existence of the proper loops at the time. Somehow it just didn't cross my mind to use them. Perhaps I believed stackless jumps were faster or something. In reality the opposite is true.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
3rdtry
Posts: 152
Joined: Sat Feb 16, 2013 1:46 pm UTC

Re: Coding: Fleeting Thoughts

Postby 3rdtry » Tue Aug 20, 2013 3:58 pm UTC

I had a Casio graphical calculator in high school too, not too many years ago. It was a total ripoff, cost around 80€, monochrome display and the Basic programs ran at 4 instructions per second tops, meaning that any slightly complex program would take 5 minutes to run.

The language had its idiosyncrasies. The only variables were A, B, C, D... to draw on screen you had to use the graphic functions, which meant setting the scale so that 1 unit corresponded to 1 pixel. It was faster to draw a zero-length line than to just draw a point. And there was a function that would tell you if a certain pixel was on or off, but trying to use it in a program threw an error, you could only use it manually (WTF?).

I did have fun with it though. Wrote a Brainfuck interpreter, a Mandelbrot set viewer (took an hour to fill the screen), and a program to display RLE compressed images on screen (after which I spent an hour copying a sprite of Mario from SNES there, it was really cool). A friend lent me his that was slightly better and had string functions, and I made a crappy chatterbot (with just 3 preprogrammed sentences).

Other people just bought a cable and downloaded 50 games from a website. I guess that works too.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Aug 22, 2013 6:56 pm UTC

I've been messsing around a bit with python. I'm not super-familiar with the subtleties of the language, and I've run into something that I simply do not understand why it happens. Wrote code that looked like this (the 'trans' dictionary contains transformations)

Code: Select all


class Foo:
        def __init__(self):
                self.trans = {}

        def const(self, transes):
                for key in transes:
                        self.trans[key] = lambda x : transes[key]
        def prt(self):
                for key in self.trans:
                        print key, self.trans[key]("something irrelevant")

foo = Foo()
foo.const({'a':'b', 'c':'d'})
foo.prt()


Why does this print
a d
c d

and not

a b
c d

? Am I missing something about how closures work in python?

I get it to work if I build a function like

Code: Select all

def make_closure(const):
  def closure(junk):
     return const
  return closure


Why is this different from the lambda above?
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Thu Aug 22, 2013 7:15 pm UTC

My WAG would be that the lambda is evaluating "key" when the lamba runs, rather than when it's created.

So at the end of the "const" function, "key" sticks around (because there are two lambdas that reference it), but key has changed to 'c', and thus both lambdas use 'c'.

But as I said, wild ass-guess. Can you print key in the lambda instead and see what happens?

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Aug 22, 2013 7:22 pm UTC

Code: Select all

lambdas = {}
def say(x):
        print x
for index in range(3):
        lambdas[index] = lambda : say(index)
for key in lambdas:
        lambdas[key]()



Code: Select all

3
3
3
3


So... yeah. Seems like some sort of pass-by-reference affair.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Thu Aug 22, 2013 7:28 pm UTC

If it makes you feel better, C# does the same thing.

Code: Select all

static void Main(string[] args)
{
    List<Func<int>> actions = new List<Func<int>>();
    for(int i = 0; i < 3; i++)
    {
        actions.Add(() => i);
    }
    foreach (var action in actions)
    {
        Console.WriteLine(action());
    }
    Console.ReadLine();
}
Prints:

Code: Select all

3
3
3

jareds
Posts: 436
Joined: Wed Jan 03, 2007 3:56 pm UTC

Re: Coding: Fleeting Thoughts

Postby jareds » Thu Aug 22, 2013 7:54 pm UTC

Capturing variables by reference (by capturing the current lexical environment) is how closures normally work. It's the loop that's not working like you'd expect. In languages where people normally get exposure to closures, variable bindings tend not to be altered except by explicit mutation (if that is even available), so closures appear to capture by value unless you deliberately try to do otherwise. For example, in Scheme the iteration constructs create a new lexical environment on each iteration. For example:

Code: Select all

(define (f1 lst)
  (let ((key))
    (do ((lst lst (cdr lst))
         (result '() (cons (lambda () key) result)))
        ((null? lst) result)
      (set! key (car lst)))))
;Value: f1

(define (f2 lst)
  (do ((lst lst (cdr lst))
       (result '() (cons (lambda () (car lst)) result)))
      ((null? lst) result)))
;Value: f2

(map apply (f1 '(1 2 3)))
;Value 16: (3 3 3)

(map apply (f2 '(1 2 3)))
;Value 17: (3 2 1)

You can see in f1 that it is the lexical environment, not the current values of the free variables in the closure, that is captured by the closure. At the same time, you can see in f2 that the iteration variables of do are not mutated--like I said, you get a new environment on each iteration--so closures will work as if they'd captured the current values unless you explicitly mutate the environment.

I'm not a Python expert, but if you want to create a lexical environment in Python on each iteration I think you need to make a function call on each iteration:

Code: Select all

class Foo:
         def __init__(self):
                 self.trans = {}
         def set_key(self, transes, key):
                 self.trans[key] = lambda x : transes[key]
         def const(self, transes):
                 for key in transes:
                         self.set_key(transes, key)
         def prt(self):
                 for key in self.trans:
                         print key, self.trans[key]("something irrelevant")

>>> foo = Foo()
>>> foo.const({'a':'b', 'c':'d'})
>>> foo.prt()
a b
c d

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Thu Aug 22, 2013 11:18 pm UTC

Here is a previous post I've made on the same topic, of making closures in loops and why it behaves like it does.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Fri Aug 23, 2013 3:07 pm UTC

Yo dawg, I herd you like XML so I put some escaped XML in your XML so you can parse XML while you parse XML.

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Fri Aug 23, 2013 3:17 pm UTC

Ooh, is it one of those ones where the outer XML is all specified and XSDed and stuff, but the inner XML is where all the important information is, and there's absolutely no documentation for its format at all? Because I've been there, and it's the best.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Fri Aug 23, 2013 3:46 pm UTC

No XSD, but I don't have any documentation. I think someone has documentation though. I just don't know where it is.

I just hate that there's this big text blob of XML inside the XML I'm try to read, so I have to copy it out unescaped for IE* to automatically indent.

*Don't judge me, it works pretty well at reading XML. I use Notepad++ when I need to write or edit since I have XML macros to auto-indent or minify.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Fri Aug 23, 2013 4:47 pm UTC

Y u no

Code: Select all

<xml-tag><![CDATA[<unescaped-xml />]]></xml-tag>

?!
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Fri Aug 23, 2013 6:29 pm UTC

You assume I control the system that's receiving and parsing this XML.

Nope, I just create and send it.

User avatar
Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Fri Aug 23, 2013 10:55 pm UTC

Xeio wrote:If it makes you feel better, C# does the same thing.

So does Javascript.

However, if you're using a browser that supports some of the newer Harmony stuff, in particular "let" and "for-of" loops, this isn't a problem. (Only Firefox supports these right now, but they're coming to Chrome.)

Code: Select all

var arr1 = [];
for(var x of [1,2,3]) {
  arr1.push(function(){ console.log(x); });
}
arr1.forEach(function(x) { x(); }); // prints 3, 3, 3

var arr2 = [];
for(let x of [1,2,3]) {
  arr2.push(function(){ console.log(x); });
}
arr2.forEach(function(x) { x(); }); // prints 1, 2, 3


"let" is a block-scoped var, and in the case of loops, it scopes itself to the *inside* of the block, so you get a nice fresh reference every iteration and avoid this common foot-gun.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Mon Aug 26, 2013 5:48 pm UTC

Being able to change code while debugging it is awesome.

I wish I could do it at work, but the build process isn't really designed for that. :?

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Mon Aug 26, 2013 8:38 pm UTC

Welcome to web development, where your program is the database and everything else is a scripting language.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Mon Aug 26, 2013 9:05 pm UTC

Hrmmm, I was talking about C#. Specifically rewriting a function while that function is on the stack.

Being able to change files while the app is running would be nice too, but all my web work is in IIS and C# so no scripty language file drop-in for me. :(

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6580
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Tue Aug 27, 2013 12:29 am UTC

I wish I was coding in C# right now. Nothing against C, but I'm writing a secure messaging library that supports compression. In C#, I can just wrap a DeflateStream around a MemoryStream and magic. If I run out of memory (and it's possible, since while it is intended for sending at most email-sized messages, if it became used it would undoubtedly be used for files as well), C# will just throw an exception and I just don't catch it and let the magic happen. Now, I have to check the return value of realloc, check the return value of deflate(), and return my own error codes. Oh, and do you want to know if everything you passed me was written (it might not be if realloc fails), well since I can only have one return value I have to have the output size passed as a pointer.
Summum ius, summa iniuria.

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Tue Aug 27, 2013 7:57 am UTC

A friend on another forum needs some C++ help. I know C, but not C++. He knows a little C++, but would like an expert's opinion.

Wocky wrote:I’m trying to maintain a piece of software written by someone else, and who I no longer have contact with, and keep coming across snippets like this:

Code: Select all

std::vector DataSegment::getPropertiesInIndexRange( uint16_t start, uint16_t finish ) const

{
    if( start > finish ) {
        int a=2;
        a++;
        }

the method then goes on to do stuff with start and finish, as I expected. The if statement seems to do nothing, though. The a has memory allocated if start > finish, then is deallocated immediately. But does the fact that the method is a vector change anything?

In C, a is obviously local to the block. And we expect the same to be true in C++. So is this just crazy code, or does it actually do something useful in C++?

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Tue Aug 27, 2013 8:14 am UTC

Yeah, that's going to do nothing. Your basic types... your ints, your chars, your arrays and "simple" structs ("simple" having a quite complicated definition, but mostly boils down to "not using any C++ features") should behave essentially the same in C++ as they do in C. The fact that the return type of the method is a vector isn't going to change anything.

My guess is that the statement is there entirely so that the coder could add a breakpoint inside the if (I guess either the debugger they're using doesn't support conditional breakpoints, or the coder didn't know about them). The "a++" line stops the compiler from warning you that the variable is unused.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Coding: Fleeting Thoughts

Postby jaap » Tue Aug 27, 2013 8:14 am UTC

PM 2Ring wrote:In C, a is obviously local to the block. And we expect the same to be true in C++. So is this just crazy code, or does it actually do something useful in C++?

It's crazy code, for sure.
The reason for it that comes to mind first, is that it is just bogus code which is useful for setting breakpoints in during debugging (though any good debugger should be able to set a conditional breakpoint that only halts when start>finish).

Any other reasons for it would have to be very obscure, like some compiler problem, or an extremely bad hack to fix some memory problem (e.g. the routine might overwrite data outside the bounds of an array in the case where start>finish, and by adding this code it is the local variable that is overwritten...). In any case, this code should be redundant.


Edit: Ninja'd. Anyway, I'd probably replace them by an assert that start<=finish.

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Tue Aug 27, 2013 8:29 am UTC

Thanks, phlip & jaap.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 2 guests