LOL great. Boxenstein removed the actual post where I posted an updated transcript. Here it is anyways: http://codepad.org/hagC0IGQ
EDIT: I guess he just doesn't want drama on the sub. That's fine.
Wouldn't the easiest solution be to run LaTeX as a service on a sandboxed server?
You'd need to lock it down pretty heavily, but if it can be managed for C you can surely manage it for LaTeX.
I think you would get the best performance out of a tuple. e.g.
random.choice(('foo', 'bar', 'baz'))
A quick test seems to support this:
>test.py Three element list: 6.46300005913 seconds Three element tuple: 5.5640001297 seconds Three element string split: 8.19199991226 seconds
Nested floating divs, I'd imagine.
Example:
<html> <head> <title>Variable Height aligned crap</title> <style type="text/css"> .column { float: left; width: 100px; margin: 0px 5px 0px 5px; }
.height1 { height: 125px; border: 1px solid #000; margin: 5px 0px 5px 0px; }
.height2 { height: 150px; border: 1px solid #000; margin: 5px 0px 5px 0px; }
.height3 { height: 100px; border: 1px solid #000; margin: 5px 0px 5px 0px; } </style> </head> <body> <div class="column"> <div class="height1"> </div> <div class="height2"> </div> <div class="height1"> </div> <div class="height3"> </div> </div> <div class="column"> <div class="height2"> </div> <div class="height3"> </div> <div class="height1"> </div> </div> </body> </html>
Replace height1/2/3 divs with actual images.
Fluidity obviously wouldn't work with this, but if you're dynamically loading images, it's trivial to determine your rows based on a set number of columns.
In fact, I got bored. Here
But how would he use a for loop to access variables with numbers hardcoded into the name?
Only PHP can solve such a problem.
Edit: I even started the loop at 0 instead of 1, and PHP handled it gracefully
I made a small modification in the program. Added:
import multiprocessing
Changed:
class Worker(threading.Thread):
To:
class Worker(multiprocessing.Process):
And run the code:
python gildetector.py
2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] # of threads: 1, took 0.259523, effectively 1 cores # of threads: 2, took 0.273987, effectively 1.89442 cores # of threads: 3, took 0.28669, effectively 2.71571 cores # of threads: 4, took 0.298521, effectively 3.47744 cores # of threads: 5, took 0.465576, effectively 2.78711 cores # of threads: 6, took 0.522528, effectively 2.98001 cores Python is utilizing 3.5/4 cores Rejoice! You're awesome!
So I am awesome on CPython 2.7 too! Here run it yourself and see if everyone is awesome:
> A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").
This is actually false! The documentation lies. Numeric keys that fit inside an integer (or is it float?) on the current architecture will be cast to integers. But longer strings will not, as I describe in a recent thread.
Not only that, but creating an array with integer literals behaves differently than creating one with string literals.
$number_key_array = array( 12345 => "Foo", 123451234512345 => "Bar", 123451234512345123451234512345 => "Baz" ); var_dump($number_key_array);
$string_key_array = array( "12345" => "Foo", "123451234512345" => "Bar", "123451234512345123451234512345" => "Baz" ); var_dump($string_key_array);
Results in this output:
array(2) { [12345]=> string(3) "Foo" [-2147483648]=> string(3) "Baz" } array(3) { [12345]=> string(3) "Foo" ["123451234512345"]=> string(3) "Bar" ["123451234512345123451234512345"]=> string(3) "Baz" }
Two big "what the fuck"s there:
First that using any large integer literal as a key casts the key to INT_MIN
.
Second that explicitly specifying string keys casts only some of them to integers.
Here's the thing, if the function was properly implemented, the recursion would eliminate to a tail call. No matter how much tail your momma has, said function should be able to calculate it.
Now, it might overflow the bounds of a machine word, in which case...
Either way, ಠ_ಠ
Edit: I made an example. Here it is on codepad: http://codepad.org/6SGGSI2d. I haven't verified that the compiler is actually eliminating the tail-call. You'll note that I gave it some dummy values: I tried to use your actual mother, but she broke the array initialization mechanics in C.
#include <stdint.h> #include <stddef.h> #include <stdio.h>
#define SO_MANY_FATS 6
typedef uint64_t momma[SO_MANY_FATS];
uint64_t how_fat_is_she_helper(momma a_momma, size_t fat_count, size_t index, uint64_t so_far) { if (index >= fat_count) { /* As if this branch will ever be reached. */ return so_far; } else { return how_fat_is_she_helper(a_momma, fat_count, index + 1, so_far + a_momma[index]); } }
uint64_t how_fat_is_she(momma a_momma, size_t fat_count) { return how_fat_is_she_helper(a_momma, fat_count, 0, 0); }
int main(int argc, char * argv[]) { momma yo_momma = {1,2,3,4,5,6};
printf("Yo momma is sooooo fat: %llu!", how_fat_is_she(yo_momma, SO_MANY_FATS)); return 0; }
array(1) { ["42"]=> string(3) "wat" }
This should not exist. Look, it even says so in the documentation!
> A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").
The string "42" should be cast to the integer 42 when the array is created. If you create an array the 'normal' way, that's exactly what happens.
For some insane reason casting a stdclass to an array allows numeric strings to get into the set of keys, thereby unleashing Zalgo, the Nezperdian Hivemind of Chaos via inconsistency.
When you do a lookup like $x["42"], PHP says 'ooh, that's a numeric string, I should cast it before doing the lookup', casts it and finds nothing. $keys[0] also contains "42" and the same PHP-logic is applied.
Since no one else has used return-oriented programming yet on this thread, I guess I will:
char* slen_(char* s) { (&s)[6]-=5*(!!s); (&s)[7]+=!!*s; return s; } int slen(char s) { return slen_(s)-s; }
This super-not-portable code works on at least one compiler.
There is a difference:
C#
int x = 0; Console.WriteLine("{0} {1} {2}", x, x++, x++);
This writes 0 0 1 as you would expect from looking at it.
C (online compiler):
int x=0; printf("%i %i %i",x,x++,x++);
This will print 2 1 0 if it compiles at all. With strict mode (gcc with -Wall -pedantic -Werror -Wfatal-errors) it does not and prints:
> [Error] operation on 'x' may be undefined [-Werror=sequence-point]
In other words, if you use a different compiler you may see different results.
ProjectEuler.net is good fun. If you like fractals, fire up turtle! It's really easy (it was originally designed for kids learning Python) and lets you do some cool stuff. Here are some examples: pythagoras tree, fern.
#include <stdio.h> main() { int a,b,c; int count = 1; for (b=c=10;a="- FIGURE?, UMKC,XYZHello Folks,\ TFy!QJu ROo TNn(ROo)SLq SLq ULo+\ UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^\ NBELPeHBFHT}TnALVlBLOFAkHFOuFETp\ HCStHAUFAgcEAelclcn^r^r\tZvYxXy\ T|S~Pn SPm SOn TNn ULo0ULo#ULo-W\ Hq!WFs XDt!" [b+++21]; ) for(; a-- > 64 ; ) putchar ( ++c=='Z' ? c = c/ 9:33^b&1); return 0; }
Well, the binary listed underneath is the same as the hexidecimal numbers listed above.
I'm just assuming that it decodes using ASCII...
Converting direct to ASCII gives this mess: SìÂO,ðë×*M®f¸í!»<Q½He»¼k
Reversing the bits and decoding gives this bigger mess: ��FFl�FFF�l,&F����,FF�L&�LFll��&,�L�&F��f�L̜f,L�Ʀ�̬
​
I also wrote some code to test if the characters are just offset http://codepad.org/JJA4S9AR
That didn't seem like the right answer either. I'm curious to see what methods other people try.
What did everyone get their moms for Mothers Day yesterday?
My mom started freaking the fuck out when she saw I got her these special imported Swedish candles. They're beautiful
Long-time C++ programmer here. You don't need pointers or references to instantiate classes with virtual functions. I know of no relationship between these two concepts at all.
Fact is, if you use RAII, memory stays trim at all times. It only becomes an issue when you need to dynamically allocate objects, like when you are maintaining a pool. However, if the pool is well-encapsulated, RAII solves for that too.
Edit: For all of the discussions below around virtual functions, please study this, it explains how slicing works: http://codepad.org/lIuEh7t0
>AWS Graviton Processors a1.4xlarge instance. aarch64. Four quad-core clusters. 2 MiB shared L2/cluster, 32KB L1D$/core, 48 KiB L1I$/core. No L3.
>Those are Cortex-A72 cores.
>~ 2.3 GHz
>- SciMark http://codepad.org/wZe5SrjI
>- C-Ray http://codepad.org/OQDCkVna
>So finished messing around with that A1 ARM instance and I have some initial thoughts. Some very good, some bad. Just my initial experience based on totally incomplete data.
>Pro: everything just works. Literally. I used my unmodified deployment scripts I use to install a fresh Linode VPS for WikiChip to install and configure the servers. Everything just worked (minor config differences due to using RHEL on AWS and Fedora on Linode, but that's it).
>Initiating the Arm server is identical to an x86 one. For all practice purposes you can't even tell the difference.
>The con: it's too damn slow. It does well on the Phoronix Test Suite. It does poorly benchmarking our website fully deployed on it (nginx + php + MediaWiki and everything else involved). This is your "real world" test. All 16 cores can't match even 5 cores of our Xeon E5-2697 v4
>Wildcard: during my stress testing of nginx/php, php segfaulted. It did the same during some of the Phoronix tests. Maybe the Arm software stack is not fully ready or something I did. I did not bother to test it further so I left it out of the pro/con but it's worth noting.
>All in all: Amazon having Arm-based offering is a great first step, but it does not seem to be a particularly appealing one at the moment, (at least for me: especially since the cost difference is nonexistent if I was to match my existing performance.)
From David Schor of Wikichip
I just spent the better part of an hour writing a python program to turn any sentence into some combination of "nyoom nyoom nugget" http://codepad.org/35829AIK
yesterday my project was this shining example:
a: "who the fuck"
b: language!"
a: "qui diable"
b: "non!"
As /u/Danskheart pointed out, it really is trivial.
Firstly, it seems you're confused about your programming terms. "Cloud based software design" doesn't actually have a specific meaning and the issue here is not "cloud based" in any way.
I just wrote this: http://codepad.org/dWa7WLZH
I chose C++ as I know that what DE use. I've never used the C++ syntax until 15 minutes ago when I wrote that snippet.
In that snippet, I demonstrate a clear way to create a weapon class with a 2 dimensional array that stores the mod Id and the current rank. There's a little check in there to make sure the user doesn't input anything higher than the maxRank for the mod.
That's all there is to it, rudimentary coding. It doesn't take up any server room because you don't have to save more mods. All you have to do is register that the user has one mod, and that mod can be of any magnitude.
In fact, Warframe Builder has the functionality to increase and decrease a mod. It would be trivial to cap this based on how far a user has ranked it.
Now - I'm not saying that DE's code is this simple, of course, it isn't. What I am saying is it can't be far detached from this concept. At most, the user would have a mod object, and then we would actually add a proxy object to the loadout array to represent the mod with desired rank.
So now we know they're bullshitting us and you (hopefully) trust my judgement and experience as a developer, we can address the real reason why they don't do it.
It kills duplicates. Ever wonder why they don't add that QoL "Sell all but one" button? Because there is a plat economy based on these mods. If people don't have duplicates, they're not going to sell them. It is in DE's interest for these mods to remain spare in players hands to encourage the sale of Platinum.
Never forget that DE is here first and foremost to make money, and second to make a kick ass game.
+/u/compilebot C
#include <stdio.h> int main(void) { int c = 0; printf("%s\n", c == c++ ? "yes it is" : "no it isn't"); return 0; }
Edit: alright fuck you compile bot http://codepad.org/NUrMxi0M
The best error I ever encountered was when I made a typo in this typename. Yes, that's a legitimate C++ typedef.
Can't post it directly to reddit because "this is too long (max: 10000)"
This C code:
main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x =0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0; j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);}
You can run it with codepad
From Prof. Ken Perlin's website
No. In PHP, if a function returns void, you should expect var_dump to output NULL
. unset()
is not a function, it's a special case in the grammar. One of many, many special cases in the grammar.
Here's the first actual function I could find that is documented to return void, if you want to try it.
. . . and yet it's been there all the time.
It's an ASM by product of the most common means of implementing division that the remainder is carried through.
It's been part of C since K&R was a set of flimsy mimeographs handed about via sneakernet.
It's the div function family.
btw - here's an example I pasted to /r/learnprogramming a couple of days ago.
I wouldn't call that self modifying code so much as a segfault waiting to happen (I did convince g++ to compile something similar, and a segfault is exactly what I got).
Don't use floats to represent currency values.
Don't use floats to represent currency values.
This behavior isn't PHP-specific. It has to do with some values being unrepresentable in IEEE floating point. Python has the same problem, for instance.
For whatever reason, his e's are encoded with 2 bytes instead of 1. I honestly have no idea why, I don't know much about text encoding.
Your browser is displaying the double-byte letters as a different font, which is why they seem fucked up.
Proof: http://codepad.org/LruSb7Px
Weird "е": 0xD0B5 (Example: http://fonta.kayac.com/font/0xD0B5)
Normal "e": 0x65 (Example: http://fonta.kayac.com/font/0x65)
You'd be right -- it doesn't compile.
> This is a very remarkable piece of code.
Not really. If it worked, it would be remarkable. In this case, it's just bad code.
Edit: If you fix it so it does compile, it doesn't work.
I'm quite positive it's possible. A similar type of emulation has been done before, have a look at a portion of SKIDROW's source code for Prince of Persia: The Forgotten Sands (the one with always-online Ubisoft DRM): http://codepad.org/FhhVs5RK
The problem is Denuvo. Wouldn't modifying the games binaries to include the emulated code trigger Denuvo?
Good. The most important thing is to do a clean reformat from an up-to-date iso. Use the Windows Media Creation Tool to get the .iso, and then use Rufus to "burn" it on to an USB stick. You don't need a product key for the installation (you can skip when the installer asks), you can activate Windows at any point after the installation. If your disk has partitions on it already, remove them all and create new ones. This will delete everything on the disk.
The next thing to remember is: Less is more. Windows usually knows what it is doing. Most programs that promise to "optimize" your system do more harm than good. Prefer scripts and portable programs (programs that don't have an installer). The integrated anti-virus (Windows Defender) is fine for most people, unless you tend to run things you shouldn't.
The only drivers you usually should manually install are for your GPU, download them directly from the chip manufacturer's website. (Nvidia, AMD or Intel).
The one thing you probably should disable is GameDVR, this can actually have a performance impact. Just copy this into a .bat file and run it as administrator: http://codepad.org/T7YFTc6k
switch
can't be used in C like that. It'll just try to jump to case 1
everytime. And I suspect that all the case ___
need to be known at compile time (edit: yep http://codepad.org/CZPShbee).
Besides even if what you're suggesting works, 1) it's too much work to keep defining flags and macros, 2) a switch is just a goto anyway. It's a lot of extra code with no upside.
You could use getchar()
to read one character and then check what has been entered. Here's a slightly more extensive version of your program: http://codepad.org/XMOK475V
Some notes:
Do not use gets()
, for this reason (from its manpage):
> Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
You will notice that I used sizeof
. This operator returns the size of a variable, i. e. how many bytes it can store. It comes in handy when using function like fgets()
that need to know how large a buffer is.
The strrchr()
bits in my code kill the trailing newline that fgets()
adds to the input it reads. In C, strings are terminated with a null byte, so we just put one where the newline is (sttrrchr()
returns a pointer to the last occurrence of a character in a string or NULL if it isn't found).
Never do something like printf(my_data)
! my_data
can contain conversion specifiers (like %s) and an attacker could use them to gain access to sensitive data that your program keeps in memory. Not important for a small test program like this one, but important for other projects. Use printf("%s", my_data)
instead.
#include <iostream> #include <cstdlib> #include <time.h> #include <cmath>
int main() { srand((unsigned)(time(0))); for(int i=0; i<10; i++) { int x = rand()%26; cout<<(char)(x+97)<<endl; //sleep(1); } }
Here ya go. I made a few comments on your code. Didn't change anything though. I'll leave that to you.
While I can't speak for everyone, I don't think your questions are really a problem. This subreddit is here for answering questions. Basic questions can be handled by people with basic knowledge and tougher ones can be answered by people with a more complex understanding of Python.
If you run it through g++ -E
to expand the macros, you get this.
He seems to basically be compressing conditionals which expands out to patterns like:
{ enum { i = (some computation) }; if(i) { do_something(); } }
Edit: Removed irrelevant question about use of enum; too early in the morning and I'm being derpy.
Edit 2: There seems to be a file on his website that describes something about the opcodes which might be relevant to this.
> Your pronounceable passwords are easier to crack, in reality, than non-pronounceable passwords, given the same password length.
Fixed that for you.
It's not really a fair comparison though; perhaps a person can remember more characters if it's made easy to pronounce.
I scratched together this, yielding an estimate of 7.6 bits of entropy per digraph (depends on the algorithm of course). Randomly selected letters is only 4.7, so you would need about (4.7*2/7.6) or about 25% more letters in digraphs to be equivalent to entirely random letters. For the 96 printable ascii characters (6.5), it's almost 1 to 1; to equal 6 random ascii characters, you'd need about ((6.5*2/7.6)*6) 10 characters of weighted digraph selection.
So, then, the question then is really a matter of which is better:
edit: formatting
To prove I can do more than sit back and throw bombs, here's how I'd design the Java API, in a way that meets the author's requirements.
Rather than the silly fold pattern, you pass in an interface full of callbacks, that are invoked at proper times. This permits elimination of several classes (like TakenBack
), and eliminates the weird dependency on fj, and becomes a lot more readable too.
For what it's worth, I wrote up a quick Monte Carlo simulation to brute-force it, and I get 0.059% - 0.065%, which is basically the right number albeit slightly high. Also, it's possible (likely?) that i have an off-by-one error somewhere, and I don't entirely trust the RNG. So as far as I'm concerned, you're probably right, and even if you aren't exactly right, you're probably pretty close to right.
Not only javascript but C++ would also gladly join to the comma party (as long as you declare the variable):
int myArray[5] = { 5, 6, 8, 7 };
std::cout << myArray[1, 2] << "\n"; // prints 8
Not a single warning. http://codepad.org/kO5v317g
Exactly! That is Montgomery Reduction. Here's proof: http://codepad.org/E9oexooE
It's pretty standard optimization, and it is part of OpenSSL: https://github.com/openssl/openssl/blob/master/crypto/bn/bn_mont.c
Here's a good explanation how it works: ftp://ftp.rsasecurity.com/pub/pdfs/tr201.pdf
See page 46, 3.8 Motgomery's Method and page page 57, 4.2 Improving Montgomery's Method.
That website is very easy to automatically use with selenium. Check this sample code:
from selenium import webdriver
browser = webdriver.Firefox() browser.get('http://codepad.org/')
browser.find_element_by_xpath('//input[@value="Python"]').click() browser.find_element_by_xpath('//textarea[@id="textarea"]').send_keys('Write here') browser.find_element_by_xpath('//input[@value="Submit"]').click()
And here how to get each DOOM element's information with Chrome: Screenshots
Why not just go all the way and do something like this?
Constructors and destructors are cool. My knowledge of C++11 is pretty much nonexistent (I've been living in Pythonville), but I'm sure you can do even better.
Hm, it doesn't work for you then. The whole idea was to print PI (3.141) using the "circle body" function.
There's this hint which may suggest as to why it does not work correctly.
edit: after applying the mentioned fix it seems to work http://codepad.org/s3TuvNHf
Programmers sometimes accidentally turn small negative numbers into very big positive numbers.
Non-ELI3 example:
Click here to see it in action
That code basically says "X is a number. Set x to be -2466. Y is a positive number. Set y equal to x. Print y". The result is 4294964830.
You're correct. You can swap them like this:
#define true 0 #define false !true
But then true becomes an integer, not a boolean.
Edit: if you want them both to be actual booleans, you can define true as !!0
Here's some general techniques that can provide insights:
Run time backwards. Instead of the ball being fired horizontally and then asking when it lands on earth, imagine the ball being fired at some angle (what angle?) from earth, and then asking how long until it reaches the apex of its parabola.
Change reference frame. Instead of the ball flying through air, imagine the ball rolling across an elevator floor, while the elevator accelerates upwards at g. How far does the ball get before it reaches the top floor?
Here's a fun problem that can be easily solved using these techniques: you are standing at the edge of an elevator shaft, about to jump down onto the elevator below. Right before you jump, you can push a button that will make the elevator go up at a constant rate, or a button that makes it go down at a constant rate. Which button should you push (if any) to minimize the impact of your fall?
Edit: I wrote up two approaches here for those who are interested.
It's worth noting that, while Haskell (with appropriate language extension pragmas) supports this sort of thing, you get an unresolvable error once the types do in fact unify. eg: http://codepad.org/v0RLon89
So what you’re gonna want to do is look up the defense values of different armor sets and compare them to the attack ratings of different weapons at different levels. The defense vs. AR function for DS1 can be read here: http://codepad.org/FqnBrhc3
You can look up the defenses for every enemy and boss and armor set on wikidot. Keep in mind that every level adds something to your defenses irrespective of your particular stat or armor. Play around on soulsplanner, as it can give you both defense and attack ratings. Then just plug those into the function above (for split damage weapons you calculate phys. AR against phys. Defense & elemental AR vs elemental defense independently, then sum the two values together to see about how much damage you’ll do with a single swing).
I had a look at the assignment spec. It doesn't seem too bad, but there is a lot to take in. Read through it slowly and carefully. Talk to your tutors about it.
If there are things you're confused about, I can probably suss them out for you. I don't have access to the supplied code though, so you may have to put up code snippets on codepad to show me what you're on about.
secondsDigit1 = seconds / 10 secondsDigit2 = seconds % 10
This produces two negative numbers in C. Depending on how modulo is defined, it might not work in all languages. (I think some definitions of modulo would always give a non-negative result, so in the case of -47 it would be 3, because you can add 3 to -50 to get -47).
Actually, in C "null" isn't defined as a keyword or a value. You only have NULL, which is a preprocessor constant representing the null pointer (remember that identifiers in C are case-sensitive, even elements defined by the pre-processor).
So even this define wouldn't, ahem, break the marvelous URL embedding feature of C. It's a very robust language after all!
edit - a demonstration: http://codepad.org/3N7itEtl
I can't see how any of this works. It appears I have not been coding for too long or the whole world is hallucinating. It doesn't actually delete anything, it doesn't even affect the pointers already there in the list, to the best of my knowledge it just runs over the list dragging a few extra pointers with it. I ran through it with pen and paper to no avail. I don't have a C compiler here. I wonder if I can use of those online C environments...
EDIT: Well it seems I'm one of the aforementioned morons though I still haven't for the life of me worked out where the trick is. :-(
Trying to procrastinate studying for Statistics so I wrote you a program instead
Feel free to change stuff and it will automatically calculate how far you should run at whatever load you want for howeverlong you choose. Changable values have green comments after them.
Hm, your code doesn't have a main function! You declare one (which isn't needed, by the way), but never define it.
Try this: http://codepad.org/IbSFlOuN
I took the liberty to clean up the indentation, too.
The changes do this:
Line 9: declare the init_board function, that takes a tictactoe_board pointer as an argument. This is needed because we call the function "before" it's defined (the definition is below main()).
main(): Create a board on the stack, and pass it (as a pointer; & is the address-of operator) to init_board.
I'm not sure exactly what has been covered by the lesson you're at; ask again if this isn't clear. :)
#include <stdio.h> int main(void) { printf("Hello world!\n"); int i = 0; while (++i <= 70) { printf("%d\n", i); } printf("Goodbye world!\n"); return 0; } codepad
It nearly worked for me (python 2.7), I did a few changes to the base code. I have a few general advices though.
I rewrote a little bit your code with a dict, an no recursive functions.
I also use the keyword 'in' to test if a key is in my dict.
And finally, I recommend you to read DiveIntoPython, there are a lot of good advices and explanations about standard stuff, like the comprehension list or dict.
Good luck :)
The code is very hard to read - indent by four spaces so that it's formatted like code, or use a service like codepad.
If I had to take a wild stab in the dark, I'd worry that you were forgetting to reset some variable back to zero for each line of stars.
You don't necessarily need someone to tell you the answer to this. It sounds like your second star is in the wrong place. By executing each line of code by hand yourself you can trace where your second star is being drawn and you can see why the values are wrong.
I think OP is actually right. I wrote a trivial program with some basic assumptions to test this out.
I assumed that the probability of drafting the first golden card was 100%, and that the probability of drafting each subsequent copy (golden or not) was an additional probability p. For example, with p=0.1, you have a 10% chance to draft a duplicate, and a 1% chance to draft a triplicate. I don't think the specific probabilities are important, just that they are reasonable approximations.
The probability that the opponent's collection has 2 golden cards is q.
I then varied p and q in the range [0.1,0.9] for p and [0.1,0.9] for q, and simulated guessing using the golden method versus the opposite strategy. See the results for yourself.
Edit: I changed to a simulation that allows for no golden cards in the collection in addition to 1 or 2. This didn't change my overall conclusion though.
Read the sidebar for how to post your code. Alternatively, upload to http://codepad.org/?lang=Python
I'm not going to critique your actual code until it is more readable, but as for your algorithm, I think you would do better to include dipthongs (e.g. ou
) as vowels and digraphs (e.g. sh
) and blends (e.g. pt
) as consonants. I recommend this because words aren't really strings of letters, but strings of syllables, which can be more closely estimated than simply in terms of vowels and consonants.
As an example, just alternating consonants and vowels will always produce words like Pokawy
or Renika
, which tend to have a very distinctive and somewhat artificial sound (although words generated this way can be very similar to those of the native Hawaiian language), while including dipthongs, blends, and digraphs can produce words more along the lines of eptia
or temmish
.
That being said, this still isn't a great system. Of course, depending on what real-life language you are trying to emulate (if any) your system is going to have to be different. But even assuming you're trying to make English-sounding words, improvements can certainly be made. For example, the frequency of certain sounds coming after others more closely matches those from a dictionary. But those innovations are up to you to implement, should you desire. You could even look into having suffix and prefix generators, really the possibilities are endless.
This might be useful: http://school.judsonisd.org/webpages/cbianco/readinghelp.cfm?subpage=23376
No, every kernel zero's memory before giving it to a new process. It's been standard for decades. The catch is it's only zero when that memory is mapped into your process. This does not mean that malloc will always give you zero, since it's quite likely that malloc gave you back memory that you had previously freed which will not have been zero'd (can't leak your own sensitive data to yourself, after all)
You can trivially check this if you have a C compiler handy, just run this: http://codepad.org/X9eaOa00
main() { printf("31 == %d\n", 31); printf("031 == %d\n", 031); printf("31e0 == %0.f\n", 31e0); printf("031e0 == %0.f\n", 031e0); printf("0x31e0 == %0.f\n", 0x31e0);
return 0; }
Output: 1 31 == 31 2 031 == 25 3 31e0 == 31 4 031e0 == 31 5 0x31e0 == 31
in this case, it's identical. any modulo which is a power 2 number can be replaced by ANDing with an appropriate bitmask ( the modulo less one)
see here for a demonstration of the equivalence of %256 and &0xff: http://codepad.org/wn0GXZH5
First of all, that code is actually only valid in C, not C++. Second, not all compilers work with it, because it relies on two minus signs that come together through a #define to compile as the -- operator.
However, there's a second version, which should always work, as /u/stollgrin said: http://codepad.org/s3TuvNHf
This code prints pi to 3 decimal places. If you're interested, this is basically how it works:
I see you've edited the wikipedia article titled XOR cipher to include a link to your program. Might that be a conflict of interest?
Edit: Here's a link to the source code, as it seems to not be available via your sourceforge link. As /u/Bottled_Void points out, this will have problems with files starting with the ~ character.
hope this helps, i wouldn't comment the "use strict" or "use warnings", it's helpful to force you to keep your code functional and clean,
Note: i did some some quick tricks to clean up your code... but not sure what you're wanting to do with it? (you initialize it so that your $ini, or my $SIR[2] is gonna be 5 all the time...)
edit: and ya, that for loop which infects inside is not gonna be executed as a consequence.. since you never get $population{$in}{'infState'} = 1;
> Are semicolons annoying to type? Probably, I got used to them. But the alternative to semicolons is making line endings significant.
Why would that be necessary? It is not true in Lua.
local x local y x = 4 y = 5 print(x) print(y) print(x + y)
↓
4 5 9
Yeah it's undefined behavior. I had to play around a bit to get a demonstration of it breaking, but here's some code where a pointer's pointed to value changes out from under you: http://codepad.org/r8k7eq1i
You could use dynamic memory yes.
Edited for clarity.
There's an interesting template trick to create the optimal (or near-optimal, not sure) run-time power code for any integral power known at compile-time. I wrote it awhile ago, and you can see it here: http://codepad.org/8S7mQqKa
I've tested it in GCC and VS, and both will optimize to a clean disassembly of fmul over and over again (for Power<997>, it does 15 fmuls).
You could also expand it to do negative powers, or add a type parameter so it's not just for doubles.
This is straight from the site: >codepad is an online compiler/interpreter, and a simple collaboration tool. >Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email.
Wow. You have got to be kidding me. You didn't even answer my question.
I shouldn't reply to you any more, but to prove I know what I'm talking about and to help you learn (though I'm starting to doubt you will no matter what I try), here is your code as ported to C++. The only thing I have done to the algorithm is make the appropriate type changes. It produces something close to the answer, but not exactly it, because you don't include 2
in your total as you should.
The core algorithm is still O(n^2)
and as such is really slow. You should research and implement a proper sieve. Hopefully you can find someone else willing to help you with that; I sure as hell won't.
Microcontroller doing a 32 bit LFSR as fast as it can, lowpassed at 20kHz.
Here's code for a PIC since that's apparently what you have
Be it known that the PIC assembler is the worst assembler I've ever used.
I was bored and made what I think is a somewhat robust Card
class (sadly without any documentation / comments):
At the bottom is a print of information about the Ace of Spades and then an example of the constructor raising an exception in a small attempt to help prevent invalid Card
s. Feel free to use and customize it to better fit your needs :)
And, of course, if you have any questions about it, I'm glad to try and answer them (and there are plenty of other nice people that are much more knowledgeable than I around here).
Edit: New paste with a couple minor tweaks (consistency/accuracy, not functionality).
I made a few changes with comments. Hope it helps.
Also I noticed you put a \n at the end of every print. I'm not sure if you're aware that print will put a newline in for you so you'll actually be getting two newlines.
Ultimately it's because 0.1
cannot be exactly represented in binary while 1.5
can. The addition with 0.1
, which is actually slightly larger than that, makes your loop exit an iteration earlier than you would think. Run the following and you'll see. I also included the return that you left out :).
#include <iostream> using namespace std;
int main () { float a; a = 1.1; cout.precision(10); while (a <= 1.5) { cout << a << endl; a = a + 0.1; } cout << a << endl; return 0; }
Welcome to the joys of floating point math.
Actually, here is the codepad link to the above code.
* Clarity
Did this in Python. There was pretty much only one way I could imagine a recursive algorithm, and it looks like the right one. http://codepad.org/JMt9E13T
########### > # # ### ### # # # # # # # # # # ### # # # # # # ### # ### # # # # # # ### # # # # # > ###########
You are correct in your realization. However, I think an example with a string larger than 1 character would highlight this a little better:
l = [1, 2, 3, 4]
l[1:3] = 'hello'
print(l)
p = [1, 2, 3, 4]
p[1:3] = ['hello']
print(p)
yields:
[1, 'h', 'e', 'l', 'l', 'o', 4] [1, 'hello', 4]
note: I ran this with whatever version of python they use at codepad, but it should work fine for 3.x
It seems like you're thinking of #define as a variable instead of a preprocessor value. Everything with a # in front of it is parsed by the compiler and only its value ends up in the final compiled code. Consider the following example:
#define STUFF 1
#ifdef STUFF #define MY_DEFINED_NUM 10 #else #define MY_OTHER_NUM 5 #endif
void main() { printf("%u\n",MY_DEFINED_NUM); printf("%u\n",MY_OTHER_NUM); }
Notice there will be an error generated by the second printf. This is because at compile time the compiler saw that STUFF was defined, parsed the #ifdefs, and saw that MY_DEFINED_NUM was defined and completely ignored MY_OTHER_NUM. In the rest of the program, every time the compiler sees MY_DEFINED_NUM, it will replace it with 10. Effectively after the preprocessor has run your source code will look like this to the compiler:
void main() { printf("%u\n",10); printf("%u\n",#undefined#); //<-ERROR }
So don't think of preprocessor directives as creating or changing variables, they are part of the compile-time configuration of the code.
See my point bellow, if the ldiv function call is inlined (depends on compiler) and you only do this operation repeatedly then compared to an unoptimized compiler you would save a lot of cycles (potentially twice as fast). If the compiler does this optimization then the inlined ldiv function call might be a bit slower compared to the optimization by compiler (but only a few clocks). If you really must know what additional instructions are added when inlining ldiv just compile a simple test prog and disassemble.
Edit: it was kind of interesting for me to check and my findings are:
code here: http://codepad.org/uqxt73H1
Conclusions:
The difference is your functions that use the built in run much worse than O(n), given that:
So, these functions:
function distill($array, $keys) { return array_intersect_key( $array, array_flip($keys) ); }
function distill($array, $keys) { return array_intersect_key( $array, array_fill_keys( $keys, NULL ) ); }
Has to run O(n) on keys twice, meaning it runs in O(2n).
These functions:
function antidistill($array, $keys) { return array_diff_key( $array, array_flip($keys) ); }
function antidistill($array, $keys) { return array_diff_key( $array, array_fill_keys( $keys, NULL ) );
Runs in the same polynomial time (O(2n)) because array_diff_key having the same polynomial time as array_intersect_key.
So, the compelling argument is that your supplied solution runs in O(2n) while the other, more explicit method runs in O(n). The source for those functions, if you want to verify, is here.
Well, I still have a lot of polishing to do on Beast. I want the first release in Boost to be the best it can be. I'm writing a TON of examples right now. This is a rough guide to all of the different sample programs that will appear in the library: http://codepad.org/gzDctWtV
During the formal review, a common theme was that users wished Beast would do just a little bit more (i.e. not have so many "out of scope" items). Originally, the http::file_body
was out of scope but I was convinced that it should be part of the library. Especially because I was able to optimize it to use the native Windows and Linux facilities for transmitting files with a minimum of kernel transitions (calling ::TransmitFile
and ::sendfile
respectively).
So I will be adding a few goodies to make things just a little bit easier for users. A solid uri parser is on the list (I've already done some work on that).
Once that settles down then yes HTTP/2 is a planned feature and I will also write new libraries that build on Beast. For example we could use a solid HTTP client, a C++ version of curl, or a C++ version of Requests for Python. Unless someone beats me to it (hopefully)
Of course, this is entirely unnecissary since ->
is automatically "chained" in C++ if the return value is not a pointer.
i.e. See this (horrible, quickly written) example. Note that the line c1->value();
ends up calling a::value()
"through" the intermediate b
object.
One day in class the prof announces that he found code online on Pastebin for the project and he was incensed. Wasn't your year. I don't remember exactly what it was but I remembered I had shared chunks of code either from projects or labs with friends via pastebin in the process of explaining how some functions I wrote worked.
Holy shit did I panic. I got the two links that I had sent to my friend and tried to delete them, hell I even paid $2 or something to that amount for pastebin pro so I could get it deleted at the front of the queue. I was paranoid and I constantly searched for lines of my code on google which would bring up the pastebin link, and of course would bring the link higher up in the search results which led to more panic.
My friend didn't copy my code, but I was scared that since it was indexed on Google someone could have searched for lab help and copied it.
In the end they were gone, nothing of consequence happened, and I learned a few lessons:
It's best to just explain how to do things at a conceptual level instead of sharing, but I mean sometimes people just don't get it and they need to look at actual code to understand how things work.
EDIT: I ought to mention that the the prof found whole files for the project on pastebin whereas the ones I had put up were significantly truncated. Maybe that was a big difference. Just googling let's say the instructor comments at the top of the project files would've brought these pages up.
The correct answer for the sequence HTTH (or equivalently THHT) is actually 18 flips (Here is an empirical result from a short code snippet to prove it: http://codepad.org/GFvQKqqr), and here are some of the other results :
> HTTT: 16
> HTTH: 18
> HTHT: 20
> HHHH: 30 (the easy case to derive)
Intuitively, depending on what the target sequence is, the number of possible ways that the non-target sequences can "overlap" with itself without generating the target varies slightly, but enough that you get different results for the expected number of flips needed.
A fairly elegant way to load new maps is as a 2d array (list of lists) like you have, but wrapped in a class so that you can access tiles with a method such as map.get_tile_at(x, y) rather than needing to use primitive accessing. As for loading from file, it's rather simple since you have most of the code there. I made a little template here: http://codepad.org/CQxdnfSU which should hopefully be fairly easy to implement.
As for breakable tiles, the way I do it is to have a break_tile_at(x, y) function in my map wrapper class which just rewrites the tile at whatever position to set it to air (or rubble, or anything you want) and then just call that when the user tunnels.
Level transitions are as simple as replacing the 2d array in the map wrapper and re-rendering the map. You will also have to update the player's position so that it makes sense in the context of the new map.
I didn't look through your code much because it's quite messy so I don't know how you're handling transitions, but the way I usually do it is by storing map names a things like 4_5.txt, 4_6.txt, 3_6.txt so that the numbers correspond to x and y coordinates on a "super-grid" of maps and simply change one of the numbers in the filename when I reach the edge of a map, then setting the player's position to be on the other side of the screen. Otherwise, you can store portal locations for things like houses and caves in the map .txt file on the first line and skip that line when reading characters into the map in memory or have a separate file that stores map portal data that you load once at startup.
If you want confusing code, take a look here.
Look at the code and then scroll down and look at the output.
Then afterwards get the explanation on the author's blog.
To anyone wondering what is this about: you just comment out the block-comment closing delimeter with a inline-comment. You can also comment out the opening-delimeter ( like so: http://codepad.org/H7xTw5zD ) but now we're just getting silly ...
You can think of string as containing the memory address of the "H", so the code will work.
Generally speaking, an array name (like "string" in this case) is usually converted to a pointer to the first element of the array.
However, there are subtle differences, which will be expounded on later.
When you create a pointer, you are creating a special kind of variable that can hold (within reason) any memory address you wish. You can add to it, subtract to it, you can work with it in unique ways, and so on.
There are times you might want to re-assign the value of a pointer, and you can do that. You cannot however do that with an array name.
for example:
// You cannot do this
char my_array[] = "Hello"; char my_other_array[] = "World";
my_array = my_other_array;
You cannot do that with arrays, but it is trivial with pointers.
This behavior in Microsoft VC++ compiles some valid (though tricky) programs incorrectly. As Kranar rightly notes, it's "friendly" -- many programmers expect C++ to work this way, and I don't blame them.
Take this program. GCC prints "global::f()" while VC++ prints "Base<T>::f()".
> will it get confusing for larger programs?
No because you will be splitting up programs into several dozen functions normally. Generally unless you are doing something quite memory management-sort of intensive or initializing a complex structure you will probably only end up with none to five local variables. If you have a complex allocation you should make it a separate function.
Here is a writeup of the same program 'how I would do it.'
It is a little hairy with all the comments so here is a 'clean' version without:
If you look carefully, each function is a single 'thought' that I added to do one specific thing. I don't have a bucket function where I throw every piece of functionality. I can look at any function and figure it out in less than a second for some of them, and for others a few seconds (well just goofy_password() because I never do that sort of pointer arithmetic with strings in that particular format).
Here's a distilled, not entirely chronological, version of how I thought through the problem.
Consider the system as a set of concentric squares around (0, 0)
. Each square has numbers in the range [(2n - 1)^2 , (2n + 1)^2 - 1]
, where n
is the index of the square and n > 0
. For any coordinate pair (x, y)
, n = max(|x|, |y|)
.
So now that we have a way to determine the range of numbers for any pair (x, y)
, we need a way to select into that range, which means the result is equivalent to adding an index to the minimum value in that range.
If we serialize the coordinates into the order we want them to align with the values, we have a sequence like this
(n, 0), (n, 1), ... , (n, n), (n - 1, n), (n - 2, n), ... , (-n, n), (-n, n - 1), (-n, n - 2), ... , (-n, -n), (-n + 1, -n), (-n + 2, -n), ... , (n, -n)
Let's use i
for the index we want. Given the above, we can see that for n = 1
, if (x == n)
then i = y
. Similarly, if (y == n)
then i = 2n - x
. Following on, if (x == -n)
then i = 4n - y
. Lastly, if (y == -n)
, then i = 6n + x
. These conditions work in general, but only when applied in reverse order, and require a bit of adjustment as n
gets bigger.
So were can outline our function (in C++) as
int spiral(int x, int y) { if (x != 0 && y != 0) { int n = max(abs(x), abs(y)); int min = pow(2n - 1, 2); int i = get_index(x, y, n);
return min + i; }
return 0; }
With get_index
written as
int get_index(int x, int y, const int n) { int ret = 0; if (y == -n) { ret = 6*n + x; } else if (x == -n) { ret = 4*n - y; } else if (y == n) { ret = 2*n - x; } else { ret = y; } return ret + n - 1; }
Here is the code above demonstrated on codepad.
It works fine here: http://codepad.org/2JDwyYjY
It is possible that optimizations are occuring that prevent the destructor from being generated or called if you are doing this test in release mode.
>But this sort of issue doesn't seem like the one I typically have when programming.
In C and C++ missing semicolon can be a bitch if it missed at the onf the file especially if you never met error like that before
//person.h #ifndef HEADER_PERSON #define HEADER_PERSON class Person { int age; public: Person(int age); } #endif
// person.cpp #include "person.h"
Person::Person(int age) //<--cryptic error message here { this->age = age; //offtopic: I hate initialization lists and want them to die, they are ugly }
Error as cryptic as it could be:
> Line 8: error: new types may not be defined in a return type
Fortunately, compilers now produce better error messages:
a.cpp:9: error: new types may not be defined in a return type a.cpp:9: note: (perhaps a semicolon is missing after the definition of `Person')
Swing does all of its work on a single thread, the AWT Event thread, this includes handling things like mouse clicks and key presses. It also handles the drawing of components, like your Snap
component. You might be seeing the problem here... If you tie up the event thread with an infinite loop and a sleep, thing like your mouse listener will never fire.
Typically what you do is have a thread updating the game world and calling repaint on the main component at suitable times. Here's an example I wrote up for another redditor.
You shouldn't be overloading paint if you don't know exactly what you're doing, either. PaintComponent is a better choice. See this post for some links regarding custom painting in Swing.
Put simply... it won't work as you might expect it to.
Here's an example of what I mean:
Basically two class hierarchies, one with a virtual method and one without. The one without a virtual method carries no polymorphic RTTI, and so using typeid on it does not give you the 'true' type but rather the type that's resolved at compile time, no overhead required. On the other hand, the hierarchy with a virtual method will carry polymorphic RTTI (stored in the class's v-table), and so using typeid on it does yield the derived type.
It's also worth noting that dynamic_cast does not properly work on classes without at least one virtual method as well.
Not quite the same. %s is printf
formatting. Yours is string concatenation.
name = "Mark"
print "Hello %s Smith" % name
print "Hello " + name + " Smith"
> Hello Mark Smith
> Hello Mark Smith
Name: EnergyIsland
Comments: You run an island's energy program. I've been learning programming and thought this game jam would be a good challenge as I work through "Learn Python the Hard Way."
Package: Haven't quite learned how to package things nicely with py2exe or something similar yet. But, the source code is here if you have a Python interpreter. I'm using Python 2.7.1. Didn't get to a game end condition so you'll have to force quit :).
Team: Me with helpful tips from bombita.
and to round that off,
BSD radixsort man page
BSD radixsort source page
these implement Mcillroy's radix A & B variants, his C variant, the American Flag sort discussed here has source given in the PDF you referenced. Here is the untested but OCR "corrected" form of that source on Codepad.
> The trick here is that a bug and a defect, while commonly used to mean the same thing, really aren't.
They are. End users care about crashes, not about specifications. If software crashes ungracefully due to incorrect user input, it's a bug.
Also this test is still a bad one as it doesn't cover (INT_MIN, -1) which also crashes.
> the specification says it shouldn't be allowed
Unless you are writing some low-level stuff, there is chances are specifications will not explicitly say "check divide by zero" or "don't format the hard drive with UUID 250c80cf-69f3-4e70-baa1-899e7183a16b".
In a safe language, yes -- or, not even an exception. Perhaps a hard stop.
In C/C++, nope. It just blindly proceeds with the truncated value, or worse. You can try this out yourself:
// input: int x = 2000000000; int y = x * 2; printf("%d times 2 is %d\n", x, y);
// output: 2000000000 times 2 is -294967296