Programming Thread

Share what you're working on now and give any ideas for some good long ish programming projects (more than just making a calculator or something)

Other urls found in this thread:

wiki.python.org/moin/IntegratedDevelopmentEnvironments
benholland.me/assets/2011/11/masonry.jpg
elpy.readthedocs.io/en/latest/ide.html#interactive-python
dspguide.com/
spacemacs.org/
github.com/faissaloo/ECOE
github.com/cppit/jucipp/releases
github.com/Irabor/infinity-dl
accu.org/index.php/journals/c362/
youtube.com/watch?v=5Z1gfgM7kzo
github.com/faissaloo/l-nano
twitter.com/SFWRedditVideos

#Data-driven fizzbuzzfor s in open("data.txt").readlines(): print(s)

q

w

e

r

t

y

u

i

o

p

l

k

j

h

g

Will you quit spamming for a get?
Holy fuck

I made a quick program that takes a string containing a huge list of names, turns it into a list, sorts the names in alphabetical order, then writes the names to another file, one name per line.
Probably my first self-made program.
Where should I improve?
names = """AsherBrendanMaddoxSergioIsraelAndyLincolnErikDonovanRaymondAveryRylanDaltonHarrisonAndreMartinKeeganMarcoJudeSawyerDakotaLeoCalvinKaiDrakeTroyZion"""listnames = names.split()sortnames = sorted(listnames)print sortnamesfilememe = raw_input("Filename here:")zod = open(filememe, 'w')zod.seek(0)zum = '\n'zod.write(zum.join(sortnames))zod.close()

in python btw

Use python 3.x instead of 2.x

Then rewright it in C
Then asm

Wish I understood what I was looking at ITT. This looks more complicated than trying to decipher moon runes. I'm such a tard hurrur

Have your program ask the user if they want the names sorted in ascending or descending order. Once you've got that working, have your program ask the user how many names should be written to the output file after sorting.

Meant to post this in the shell scripting thread, but it applies here too.

names = """AsherBrendanMaddoxSergioIsraelAndyLincolnErikDonovanRaymondAveryRylanDaltonHarrisonAndreMartinKeeganMarcoJudeSawyerDakotaLeoCalvinKaiDrakeTroyZion"""zod = open(input("Filename here:"), 'w')zod.seek(0)zod.write('\n'.join(sorted(names.split())))zod.close()

names =
open(input("Filename here:"), 'w').seek(0).write('\n'.join(sorted("Asher Brendan Maddox Sergio ... Troy Zion".split()))).close()

doesn't work nigger, don't you think I tried that first?

AttributeError: 'int' object has no attribute 'write'

It's better if the names are listed one per line due to how easy it becomes to copypaste.

Can you guys explain me how a class works?
Right now it seems to be like a function that's used for more functions, but it can't be that simple can it?

TBH just "\n".join(sortnames).

Also there's no point in making listnames, just assign to sortnames and the call sort() (which should be faster anyway since it doesn't need to allocate a new list).

But when I tried to sort it without setting it as a list it sorted out the letters individually instead of the words.

What if my name is 寿 or André?

Then I tell the gook to fuck off
Then I tell the spic to fuck off.
I haven't thought of a way to sort those moonrunes yet, I don't think it should be needed though.I didn't bother with "´", "^" and "~" because I'm using Powershell and it cannot even display those right

from random import randintclass Humanoid(object): """This is a human""" arms = 2 fingers = 10 def __init__(self): self.wuzKang = False self.iq = randint(95, 140) self.shitposts = 0 def __repr__(self): return 'A Humanoid' def shitpost(self): self.shitposts += 1class Nigger(Humanoid): """AYO DIS BE A KANG""" def __init__(self): self.wuzKang = True self.loot = 0 self.iq = randint(0, 30) def __repr__(self): return 'A Nigger' def steal(self): print('gibs me dat') self.loot+=1 def riot(self): print('AYO TRAYVON N SHIT NIGGA') def loot(self): self.loot**2 def chimpout(self): print('AYO AYO WE WUZ KANGS N SHIT') def complain(self): print('shiiiiet')john = Humanoid()jamal = Nigger()print(john.arms, jamal.arms)print(john.iq, jamal.iq)

meant for

No I mean after you split it into words.

sortnames = names.split()
sortnames.sort()

They group together related data. They also usually have related functions. E.g.class Vector(object): def __init__(self, x, y): self.X = x self.Y = y def Length(self): return (self.X**2 + self.Y**2)**0.5

Burger education. The Spanish translation for Andrew is Andrés, André is French.

autismo so big he can't even take a joke.

I was just pretending.

h-haha
m-me too!

Check for a FileNotFoundError or similar when opening the file. This will teach you error checking and try statements.

Longer-term, you should start to use command-line arguments with the argparse module instead of user input for the filename.

It's also good practice to keep everything in a function, like main() or something. When you want that function to run when the script does, use:

if __name__ == "__main__": main()

But you haven't really done anything wrong, except maybe for using Python2 over Python3. As far as I know Python2 is slowly being phased out.

Thanks for the help guys, I tried a bunch of these.
Can you guys give me an idea of something that uses more Try...Except and classes?I want to hone up on these.

So a class is like a Dictionary, but more in depth.
Did I get the right idea here?(I already understood the general syntax)

Made this the other day to pseudo randomly fill my screens with image slideshows. Run it in a directory with images. Requires feh. Tested on Xfce. At the bottom of the script is where you put in your screen dimensions.
What can I improve?

#!/usr/bin/env python3import argparse;import random;import subprocess;import timeparser = argparse.ArgumentParser()parser.add_argument("-r", "--recursive", default = False, action = "store_true") #look in subdirectories for imagesparser.add_argument("-d", "--delay", default = .01, type = float)parser.add_argument("-D", "--duration", default = 7, type = float)parser.add_argument("-x", "--maxXtiles", default = 7, type = int)parser.add_argument("-y", "--maxYtiles", default = 5, type = int)parser.add_argument("-w", "--white", default = False, action = "store_true")parser.add_argument("-f", "--fill", default = False, action = "store_true")args = parser.parse_args()feh_command = "feh -xzq" + ("r" if args.recursive else "") + " --zoom " + ("fill" if args.fill else "max") + " -B " + ("white" if args.white else "black") + " -D " + str(args.duration) + " -g {}x{}+{}+{} &"class Box: def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = hdef recursive_cut(box, boxes): h_check = box.w > 2 * args.min_width v_check = box.h > 2 * args.min_height if (h_check or v_check) and (min(box.w / box.h, box.h / box.w) < 5 / 8 or (1 - (box.w - args.min_width + box.h - args.min_height) / 2 / (args.max_average_dif))**1.5 < random.random()): if v_check and (box.h > box.w or not h_check): cut = random.randint(args.min_height, box.h - args.min_height) recursive_cut(Box(box.x, box.y, box.w, cut), boxes) recursive_cut(Box(box.x, box.y + cut, box.w, box.h - cut), boxes) else: cut = random.randint(args.min_width, box.w - args.min_width) recursive_cut(Box(box.x, box.y, cut, box.h), boxes) recursive_cut(Box(box.x + cut, box.y, box.w - cut, box.h), boxes) else: boxes.append(box)def do_screen(x_res, y_res, x_offset, y_offset): args.min_width = int(x_res / args.maxXtiles) args.min_height = int(y_res / args.maxYtiles) args.max_average_dif = (x_res - args.min_width + y_res - args.min_height) / 2 boxes = [] recursive_cut(Box(x_offset, y_offset, x_res, y_res), boxes) for box in boxes: subprocess.run(feh_command.format(box.w, box.h, box.x, box.y), shell=True) time.sleep(args.delay)# change these to fit your screens' windowable areas# e.g. do_screen(1920, [1080 - taskbar height], 0, 0) would be if you had a# single 1080p monitor with a taskbar at the bottom of the screendo_screen(1547, 900, 53, 0) # this is for a 900p screen with a taskbar on the left of width 53do_screen(1920, 1080, 1600, 0) # this is for a 1080p screen sitting to the right of the 900p screen

So, the one of the last exercises of "learn python the hard way" is making a text adventure, which I'm doing.
However, I've stumbled into a piece of code that just won't work, and I've no idea why, could anyone help me?
[code]
class Tavern(Scene):
def enter(self):
global stole_tip
print "You wander into the tavern, you can see a maid delivering drinks with a tip bursting out of her pocket" #works
actionwew = raw_input("What will you do?")
if "exit" or "leave" in actionwew:
print "You leave the tavern"
elif "distract" in actionwew:
print "You distract the maid somehow, she now has her back turned to you, what will you do?"
global gold
global stole_tip
actionwew2 = raw_input("What to do with the maid?")
if "grope" or "rape" or "molest" in actionwew2:
print "The maid feels your soft hands swiping through her tender cheeks, she quickly slaps you and when she realizes that you're a member of the monastery, she quickly spreads word of your unpure deeds through the town"
print "You lose"
exit(1)
elif "tip" or "coin" or "steal" in actionwew2 and stole_tip == 0:
print "you swipe away the maid's hard-earned tip, getting yourself a gold coin!You quickly leave the tavern, as to not to rise any suspicion"
gold += 1
stole_tip += 1
return "thetown"
else:
print "If you don't know what to do, you should exit this place"
actiontav = raw_input("What will you do?")
[\code]
((For reference, return "thetown" will send you to the class town that's also part of the game, just not posted here))

Anyways, when I try to type in any action in this class(doesn't matter what it is, from "exit" to just a blank space) it prints me "You leave the tavern" and an error comes up.

So, the one of the last exercises of "learn python the hard way" is making a text adventure, which I'm doing.
However, I've stumbled into a piece of code that just won't work, and I've no idea why, could anyone help me?
class Tavern(Scene): def enter(self): global stole_tip print "You wander into the tavern, you can see a maid delivering drinks with a tip bursting out of her pocket" #works actionwew = raw_input("What will you do?") if "exit" or "leave" in actionwew: print "You leave the tavern" elif "distract" in actionwew: print "You distract the maid somehow, she now has her back turned to you, what will you do?" global gold global stole_tip actionwew2 = raw_input("What to do with the maid?") if "grope" or "rape" or "molest" in actionwew2: print "The maid feels your soft hands swiping through her tender cheeks, she quickly slaps you and when she realizes that you're a member of the monastery, she quickly spreads word of your unpure deeds through the town" print "You lose" exit(1) elif "tip" or "coin" or "steal" in actionwew2 and stole_tip == 0: print "you swipe away the maid's hard-earned tip, getting yourself a gold coin!You quickly leave the tavern, as to not to rise any suspicion" gold += 1 stole_tip += 1 return "thetown" else: print "If you don't know what to do, you should exit this place" actiontav = raw_input("What will you do?")
((For reference, return "thetown" will send you to the class town that's also part of the game, just not posted here))
Anyways, when I try to type in any action in this class(doesn't matter what it is, from "exit" to just a blank space) it prints me "You leave the tavern" and an error comes up.

actually means
Which is obviously not what you meant
Is always true and that's why it always exits the tavern no matter what you type.
You meant

There's some other ways to do it in python but they are more complex and the book will probably show you them later.

For literal exit/leave:
if actionwew in ["exit", "leave"]
Fuzzy:
def fmatch(y, xs): return any(y in x for x in xs)if fmatch(actionwew, ["exit","leave"]

OK, you asked for it:
Cross-platform audio player, with full feature parity with foobar2000.
Written in Rust (maybe also C and/or Swift parts, where necessary). With optional GUI, which attaches to a headless server.

However, I guess, nobody would bother, this is not even close to an easy problem.

Thanks for the help guys.
I took a day to answer because codemonkey didn't want me to post.

Can I post here now?

I wanted to into ROM hacks. Not necessarily making my own hacks, but playing some. The problem is that all patchers are for Windows only, use a GUI or are for antiquated operating systems and have no source code. My choices are either to run LunarIPS through Wine or write my own, so I decided to write my own, Unix style (CLI, redirection, terseness).

I just finished the diff part of the package, making it all complete. I can now apply patches, inspect patches and produce patches. The diff tool is not perfect yet, the patches are 100% correct but don't have optimal size. I'll have to figure out the underlying math first, it's a non-trivial task but I have a good idea.

Well fuck. I'm working on just that: A graphing CAS system.

>heh I'm surprised the generals hater hasn't shown up to dump on you are thread yet OP.

Could anyone help me with a small problem that I got?
Let's say that I want to check if a variable has one value contained within a list, how can I do it?

Example, if I do this:
zuz = ["jej", "kok", "meme"]action = raw_input()if zuz == action: print "it works"else: print "it doesn't"

It will always return "it doesn", and if instead I do this:

zuz = ["jej", "kok", "meme"]action = raw_input()if zuz in action: print "it works"else: print "it doesn't"

It will return an error that says "Traceback (most recent call last):
File "testest.py", line 5, in
if zuz in action:
TypeError: 'in ' requires string as left operand, not list"

because you're comparing a string to the reference to the array. you need to crawl through the array or use a standard function that checks if the array contains a thing

i could explain in a detail but you're writing in python so why even bother

Do you mean:
if action in zuz: instead?

zuz is a list, like your shopping list. Would you say 'Is my shopping list on onions?' or 'Is 'onions' on my shopping list?' Clearly the latter. That's the mistake you are making with the list and string.

First is comparing apples and oranges, just "expand" the second and see why it's wrong:
action = "fef"if zuz in action -> if ["jej", "kok", "meme"] in "fef"if action in zuz -> if "fef" in ["jej", "kok", "meme"]

Also in as a function would kind of look like this:
def is_in(needle, haystack): for elem in haystack: if needle == elem: return True return False

Thanks guys, I thought about it hastily and the idea to check the other way went past me for some reason.
Thanks again.

noice class example

#include#include#includeusing namespace std;class Human{ public: int arms; int fingers; int iq; int shitpostCount; int loot; virtual void shitposts()=0; virtual void display()=0; virtual void steal()=0; virtual void riot()=0; Human() { int arms = 2; int fingers = 2; }};class Nigger:public Human{ public: Nigger() { loot = 0; srand(time(NULL)); iq = 0 + ( rand() % ( 50 - 0 + 1 ) ); shitpostCount = 0; } void steal() { cout

Made a program that outputs a picture of a sine wave in Perl. I learned Perl myself, so I'm not sure if I'm following any proper standards. How did I do? #!/usr/bin/env perluse strict;use warnings;use GD;# Defining variablesmy $pi = 3.14159;my $width = 800;my $height = 300;my $ylocation = $height / 2;# Defining subroutinessub degree_sine { my $input = shift; return sin($input / 180 * $pi);} # Defining picturemy $image = new GD::Image($width, $height);my $white = $image->colorAllocate(255,255,255);my $black = $image->colorAllocate(0,0,0);# Drawing picture$image->fill(0,0,$white); # White background$image->line(0, $ylocation, $width, $ylocation, $black); # Black line through centrefor (0..$width) { # Sine wave $image->setPixel($_, $ylocation - degree_sine($_) * $ylocation, $black);}# Output pictureopen my $output, ">", "output.png" or die "Couldn't output picture";binmode $output;print $output $image->png;

Forgot the output

Thanks for reminding me again user why C sucks. I've been able to bask in glorious C++ for so long now I had forgotten ehh.

Whatever you are doing user, keep it up. That's some of the most readable Perl I've ever seen. Please don't fall into the typical Perl-think that the terser, the better.

Yours looks good!

what

Just a tip:

loot = loot * 2;
should probably be
loot *= 2;

What's your best/preferred IDE?
I'm looking for the best Python IDE.

vim

I use Emacs, but anything should work as long as it doesn't constantly crash or interrupt you.
wiki.python.org/moin/IntegratedDevelopmentEnvironments has a list of different Python-specific ones, but you should use something more general first so that you don't have to rely on the IDE.

What do you recommend for general coding?

Emacs is best for features, and you can use it like Notepad so it's easy to learn. It uses a mode system, so you put it in Python mode for python code and it sets everything up to make it easier. There are modes for just about anything out there.
Vim is really good as well, but it's got more of a learning curve to it. GVim is a graphical application, and Vim and NeoVim are terminal-based. They focus on speed, and you can be ridiculously fast at coding if you use it enough. They have less features than Emacs, but are still good enough that most editor arguments are Emacs vs Vim.
If you're on Windows Notepad++ is pretty good. On Linux it's equivalents would be Gedit, Kate and Geany. They're simple, no-frills text editors, and they just colour the text to make things easier to read.

I'd go with Emacs or Notepad++/Kate/Gedit to start off

says the one who gets dubs

Im writing a program that predicts the amount of people that will hop on an urban public bus at each stop through its run using statistical data and simulation with a model that uses pseudorandom generators. With that, it also calculates its delays for each stop and makes estimations of its geographical position for every moment of its run.

Would be cool if it would stagger images in columns as well. Not just form one horizontal line of them. Sort of like: benholland.me/assets/2011/11/masonry.jpg

Neat idea though!

It's readable, that alone is a miracle, but why aren't you using GNU Octave for this sort of stuff? Qalculate can plot basic stuff too.

On that subject what recommended reading is there for DSP stuff? I'm aware that my DFT is not skipping the mirrored half. Also >DFT >not FFT

use

Emacs + elpy will do you right for Python, I guess. Apparently it provides a REPL like Lisp gets.
elpy.readthedocs.io/en/latest/ide.html#interactive-python

Emacs is multiplatform. It's your home away from home when forced into proprietary shitware.

Tagging porn beautiful examples of Asian artwork.

All that's missing is the file system layer, which is very important since
Firefox can't into shell scripting.

Also on the the todo list:
+ Add concrete data types to the parser so, for example, one could search for files that were tagged within the last week
+ Make it possible to load variable definitions from a file, rather than having to define them on the command line each time (so, for example, the program will know what the fuck you're talking about when you tell it to look for the best grill)
+ Sanic speed

Free DSP book, covers a lot of stuff
dspguide.com/

don't forget to check out spacemacs
spacemacs.org/

gives you great defaults out of the box, includes some very useful plugins, and makes adding language support much more straightforward

I've been working on this in terminal object editor for Game Maker/ENIGMA, it's my first C project, please tell me how bad the code is.
github.com/faissaloo/ECOE

you're a hell of a lot smarter than i was at 15. interface looks super nifty, not familiar with ENIGMA or Game Maker. from a cursory glance your code looks fairly clean and well organized (not a fan of globals however they only appear to be referenced in main.c, could you make them static?). looking at main i see an event loop that could be moved into its own function, along with a drawing block, an input handling, and a constant initialization block. 771 line functions make my eyes glaze over

hate to be a debby downer, but your website looks like flashy ass

Aww, thank you.

Many of them are used outside of main and may need to be in future (and I would need to do that anyways to listen to your next suggestion)

Ok thanks, I'll start working on these ASAP.

I know, I made it when I was like 12 and I have a new one almost ready that I made from scratch (pic related), I just need to get all the parts for the server I'm going to put it on.

For the record, the copypasta in that screenshot is just placeholder text for the template, I'm not actually going to put it on my site in case anyone was wondering.

Dark blue with black background does not really work but apart from that your site looks fine

Hiroshima Nagasaki decided to block my IP range from halfchan. I'm not even banned, just blocked unless I pay up for a pass (won't do).

...so I can no longer post in /dpt/ except maybe from my phone.

So how does Holla Forums's programming threads compare? It's been a while since I've posted in here.

How to compare:
Step 1: Turn on tree view.
Step 2: Go through all the top level posts.
Step 3: Realise that /dpt/ is crap and so is halfchan.

Please don't.

Two actually, a friend of mine does PR (he also owns a tech blog that's garnered some attention) and some pre-release testing/criticism for me (we used to have another developer but timezones and his schooling became an issue). This is specifically for the games I write, my personal projects don't go on here.

How's this? I decided to make some other adjustments

the fuck are you doing here faciallube

Wait, what are you doing here? I didn't know any of you browsed Holla Forums.
Which one are you? The mod who got triggered because I made a joke about America? Or one of the few who weren't ban-happy pissbabies because I posted too much on a dead forum?

Meh. What did Burgerland ever do for Nihon anyway, outlander?

If you use a programming IDE on Linux, what do you use /programmingthread/?

Here's mine:
github.com/cppit/jucipp/releases

...

#!/usr/bin/env python3def main(): names = """AsherBrendanMaddoxSergioIsraelAndyLincolnErikDonovanRaymondAveryRylanDaltonHarrisonAndreMartinKeeganMarcoJudeSawyerDakotaLeoCalvinKaiDrakeTroyZion""" file = open("sorted.txt", "w") file.seek(0);file.write("\n".join(sorted(names.split("\n"),reverse=(True if str.lower(input("Ascending or descending order? (A/d) ")[:1])=="d" else False))));file.close()if __name__ == "__main__": main()

Anyone know a good resource for learning Java?

The bottom of a Clorox bottle.

N00b here. Learning python; wrote something useful besides and hello world script . Anyone wants to try it out?

Forgot to add: You can use it on 4chan, 7chan and hispanchan

post it

IIRC, Holla Forums on allows 40 lines

here: github.com/Irabor/infinity-dl

Just made this. Print consecutive lines of "*" and the mirrored counterpart.
I wonder if mksh actually does tail call optimization, but I guess not, since it run like shit.
Anyway, have fun, use the "show" function to control how many time it loops.
#!/bin/mkshfunction star { printf "*"; }function stars { [[ $1 -le $2 ]]&&return;star;stars $1 $(($2+1)); }function space { printf " "; }function spaces { [[ $1 -le $2 ]]&&return;space;spaces $1 $(($2+1)); }function stspl { stars $1 0;spaces $2 0; }function spstl { spaces $1 0;stars $2 0; }function line { [[ $1 -le $2 ]]&&return;stspl $2 $(($1-$2));spstl $(($1-$2)) $2;echo;line $1 $(($2+1)); }function linei { [[ $1 -le $2 ]]&&return;stspl $(($1-$2)) $2;spstl $2 $(($1-$2));echo;linei $1 $(($2+1)); }function show { [[ $1 -le $2 ]]&&exit; line 40 0;linei 40 0; show $1 $(($2+1)); }show 10 0;

You could combine most of those functions that scrape different chans and make it much cleaner and easier to maintain, you're repeating a lot of code.

Classes:

It's hard to shoehorn classes into a program so simple. Try writing an phonebook instead, and have each person in the phonebook be a class with two attributes (name, phone number). Make it so that doing str(person) formats it in a nice way for displaying to the user.
No need to do file I/O for this one I guess; you already can do it and that's not the focus.


try/except:

Take input from the user for each phonebook entry. Make the person class throw an exception at construction time (i.e. in __init__) if there is any non-digit character in the phone number other than the leading "+" and any spaces.
Make a method to get the country code from a phone number (e.g. return "GB" if it starts with +44). It should throw an exception if the phone number doesn't start with "+" or if your code can't work out what country it's from.

The exception when creating the user should be caught while asking the user for input (so you can tell them they fucked up).

After taking a few inputs, you can display the contents of the phonebook, showing each person's name and phone number, with the country code indicated after the phone number in parens or something. If you can't determine the country code, don't indicate it.

AS A BONUS - an exercise in breaking your program a little:
Add an infinite loop to your country code determining function, so that it freezes your script. When you run your script, hitting Ctrl+C should quit it, NOT simply proceed to the next item on the list. If it doesn't quit on Ctrl+C, your except clauses are too broad.
Similarly, try accessing a variable that doesn't exist within that same function (remove the loop, that test is done). If you don't get a stack trace with a meaningful error message, again your except clauses are too broad.

There's a chance you'll have no problem with the above, but I have seen many instances where new python programmers write far too broad exception clauses and don't realize how difficult it makes handling actual exceptional situations.

I don't know how useful those would be to you but maybe it's practice nonetheless.


- pep8
- Cut down on the inline conditionals in the command line. It's made the line very long.
- Don't use "args" as an implicit global variable. If you need to hide variables to share between invocations of recursive_cut, use a class and make recursive_cut a method on that class.
- Don't use shell=True. You don't need that shell. If the "&" is all you wanted it for, use Popen instead of run.
- Use lists for command invocations rather than strings.
- The condition in recursive_cut should probably be a function in its own right.

You should use more classes. Every decision should be a class. That way you don't deal with the mess of "actionwew" and "actionwew2", and you don't have the problem of falling past the end of the conditions if you do something unknown to the maid. Use those classes as a kind of finite state machine.


my $input = shift;
I'd recommend using @_ here. The first reason is that it's basically the standard to have an argument list assigned from @_, and the second is that it's slightly faster :^)
Other than that: passes my review but I'm no expert.


mksh doesn't have a builtin printf. Either use dash or replace your printfs with "print -n" (mksh specific). You'll notice that with that change alone your script runs about two orders of magnitude faster.

If you run it in dash, removing the nonstandard parts ("function" and "[["), it runs even faster.
#!/bin/dashstar() { printf "*"; }stars() { [ $1 -le $2 ]&&return;star;stars $1 $(($2+1)); }space() { printf " "; }spaces() { [ $1 -le $2 ]&&return;space;spaces $1 $(($2+1)); }stspl() { stars $1 0;spaces $2 0; }spstl() { spaces $1 0;stars $2 0; }line() { [ $1 -le $2 ]&&return;stspl $2 $(($1-$2));spstl $(($1-$2)) $2;echo;line $1 $(($2+1)); }linei() { [ $1 -le $2 ]&&return;stspl $(($1-$2)) $2;spstl $2 $(($1-$2));echo;linei $1 $(($2+1)); }show() { [ $1 -le $2 ]&&exit; line 40 0;linei 40 0; show $1 $(($2+1)); }show 10 0;
But there's more to do there. I'll leave you with these minor changes, and you can pick up from them how you want if you want:
#!/bin/dashset -fIFS=stars() { i=$1; while [ $i != 0 ]; do printf \*; i=$((i-1)); done; }spaces() { printf %\*s "$1"; }stspl() { stars $1;spaces $2; }spstl() { spaces $1;stars $2; }# rest of the script as above...

Thanks for the mksh and dash tips. I was trying to just use recursion to do this, but using loop iteration and combined to your others suggestion, it runs much faster.

Writing an MPEG decoder in C. Mostly pretty straightforward, since the spec is easy to read. Got the parsing stage done, so now I'm starting work on decoding.

Doing a simple motion prediction.
bin/motion-prediction -t 300 test/rambo_* out.pfr; bin/motion-prediction -d test/rambo_1.pgm out.pfr out.pgmSSE2 support enabled8924/9180 (97%) blocks matched.8924/9180 (97%) vectors found.
Works pretty well, when you consider that out.pfr is 42KB and rambo_2.pgm is 1.7MB.

Since I don't think it deserves its own thread what online repos do you guys use for group projects? Github is obviously shit. Is Gitgud any better?

New Overload #133 is now out. Includes a nice article on programming your own scripting language in C++ allowing keywords any language.

accu.org/index.php/journals/c362/

Bitbucket?

Neat. Optical flow field?

I stopped programming completely for like 5 months, and even before that I only programmed for half a year so I wasn't an expert to begin with.

So now I'm going back looking at my old and big project and I have no idea if I should completely rewrite it so I can refresh my skills, or take my time reading it again for like a week or so and make use of the already done work. Which actually took me like 3 months to write back then...

I forgot most of the functions from the language I know and how most of my project works, do you think that it's worth it to try and re-read it and keep working on it again? What would you do? I'm rusty as fuck

Ehh, depends. IMO, if I felt I was in need of refresher in algorithm design, then I would probably skim the codebase to remind myself what it was in the first place, then rewrite it all from scratch.

If, on the other hand I actually wanted to get the project up and running then ofc it's better to relearn what's already done and start there.

I need a refresher in algorithms, but then again I wrote so many functions in 3 months, it's a game by the way....

I really just meant the mental process of devising algorithms to solve problems more than the formal study of the discipline, IE, a course on it.

Having to solve how to do something mechanically is always a great mental exercise, and you'll get just as much benefit rewriting your work from scratch--and with less friction--as working on a given random problem.

OTOH, if getting the [game] running quickly is more important, then take a week or so to relearn your past work, and dive back in on making forward progress.

Just my subjective view user. I generally have at least 2 or 3 different smaller personal projects going apart from professional work, simply as a way to keep stretching my mind and skills.

With personal work you have complete freedom to do what you see fit, from minor optimizations to full on rip-and-replace. It's a nice feeling tbh.

Yep this is what I meant, how to get into the mindset of making algorithms again, I can't learn things mechanically at all, I'm terrible at that. I'm just gonna try a week of looking up everything I did, and maybe I can continue my progress.

The main thing is just to get back in the game and keep growing as a good creative dev yea? Good luck user.

Would probably be better written as
how to tell a mindless machine how to mechanically perform some logical task.

Skill at doing this is one of the things that sets great programmers apart--they have to actually solve things.
:D

You're so right about this, I just want to get back into being creative and program, I felt like complete shit for the past 5 months for not doing anything. And it's kinda hard to start up again. Thanks for the encouragement, I'll get back to it.


Oh I thought by 'mechanically' you meant to learn something step by step without actually understanding it, I'm bad at memorizing things for the sake of it so this is why I said I can't do shit mechanically. But you were saying about having a clear understanding and then step by step writing it for the computer, if I'm not mistaken.

I miss the feeling of programming something, it was so great when you implemented some bullshit thing that it took you an entire day to write and it just worked or when you solved something when you were stuck on it for a week or two, felt like cumming.

Yup that's the size of it.

youtube.com/watch?v=5Z1gfgM7kzo

Then get back in the game user! What language/platform/OS do you work in?

Steve Jobs didn't program.

Actually, he did early on.

Besides, did you have a point?

After installing gentoo, I realised that compilation absolutely rapes my CPU temperature. Here is my solution, a thermal throttling script

#!/bin/bashfunction gettemp { #get CPU temperature cat /sys/class/thermal/thermal_zone2/temp}function log { echo $(date +%T) $* >> /tmp/psmanager.log}function setpmax { #set max p-state, as a percentage. Lower number = greater throttling echo $1 > /sys/devices/system/cpu/intel_pstate/max_perf_pct}function ohfuck { #CPU temp is above panic temperature, throttle completely cat /sys/devices/system/cpu/intel_pstate/min_perf_pct > /sys/devices/system/cpu/intel_pstate/max_perf_pct }function decrementpmax { #decrease p-state unless it is already at the minimum value if [ $pmax -eq 21 ]; then log pmax already 21, doing nothing else ((pmax--)) fi}#minimum p-state hardcoded to 21, which is the minimum p-state value from /sys/devices/.../min_perf_pct at the time of writing#p-state minimum should not change (I think). It is hardcoded so that, if it ever does increase, CPU will not unthrottle without warning function incrementpmax { #increase p-state unless it is already at the maximum value if [ $pmax -eq 100 ]; then log pmax already 100, doing nothing else ((pmax++)) fi}pmax=75 #inital p-state is 75% of max power, i.e. throttled to 75% desiredtemp=70000 #70 degrees celcius panictemp=80000 while true; do #if CPU temp is less than desired temp, throttle less. If CPU temp is greater than desired temp, throttle more. If CPU temp is above panic temp, throttle completely cputemp=$(gettemp) if [ $cputemp -lt $desiredtemp ]; then incrementpmax log pmax $pmax, TEMP $cputemp LT desiredtemp $desiredtemp, attempting to increment fi if [ $cputemp -ge $desiredtemp ]; then decrementpmax log pmax $pmax, TEMP $cputemp GE desiredtemp $desiredtemp, attempting to decrement fi if [ $cputemp -ge $panictemp ]; then log pmax $pmax, TEMP $cputemp GE panictemp $panictemp, panicking ohfuck fi setpmax $pmax sleep 1done

Any thoughts as to how I could improve it?

Now that I can't say, I'll get mauled by Holla Forums for obvious reasons lol

Javascript/node.js/Windows then?

make -l

working on this

Can't you just set the thermal trip point to 70 and let the CPU do this itself?

Nah, look at he artifacts. Basic SAD comparison with diamond search.

Console-output chess in C++.

It looks nice at least.

Either that or installing thermald would've worked, but where's the fun in that? Whole point of it was to familiarise myself with p-states and get some bash practice in

making a 2d platformer where you shoot bitches in C. been implementing the latency compensation, message ordering, etc for the last few weeks. it supports cuckdows and gaynix

why would you choose a functional language over an OO one for a game?

windows and a game engine

lulwut

Cool. If you used a character other than /, then it might be easier to read the piece designations at a glance. Maybe try using a dot instead user?

I don't know. It looks kind of ugly that way.

Maybe try going all out and use box drawing characters + different background colours? Maybe # for the borders and just using different backgrounds for the cells could work; no need to fill them with . or / or anything

Programatically is there any difference when working with tcp sockets as opposed to udp sockets? I'm talking C# specifically.

udp needs more setup and taking care of the packets by yourself, but if you want to make games or stream content you can't avoid it

could you point me to any tutorials or anything?

I just threw ncmpcpp out of the windows when I realised that mpc could do everything I wanted, and that it was fun to script it.
function mpc-add-random-album(){ 1=${1:-1} mpc list album | shuf | head -n $1 | tee >(while read -r i; do echo Album \""$i"\" added to playlist.; done) | xargs -I{} mpc findadd album '{}'}function mpc-del-album(){ if [ $# != 1 ] then ALBUM="$(mpc -f "%album%" playlist | uniq | tail -n 1)" else ALBUM="$(mpc -f "%album%" playlist | grep -i ".*$1.*" | uniq | tail -n 1)" fi mpc -f "%position% %album%" playlist | grep -F "$ALBUM" | cut -d ' ' -f1 | mpc del echo Album \""$ALBUM"\" removed from playlist.}function mpc-watch(){ watch -n1 -t 'mpc status; echo; mpc -f "%artist% -[ (%date%)] %album% - %title%" playlist'}
In my .zshrc and I have everything I want. If only cmus had random album.

If you insist, but I think this is a heavier solution in the sense that it keeps reconnecting to mpd's socket and keeps re-running the status process even when no changes have been made.

The difference is negligible since the database is kept in RAM and the said database is flatfile.
On the other hand, ncmpcpp fucking depends on boostbloat.

Whoops, correction, it uses sqlite now.

Forgot to do a sed "s/'/\'/g" before the xargs.

I'm going through someone else's x86_64 assembly right now and I made this regexp to deal with some of their noob-isms:
Find & replace:
mov[ \t\r\f](r.*),.*0
With:
xor $1, $1

Be careful, because xoring a register with itself alters eflags

I hate boost and wish it'd die already

You should've written in a way that's readable for yourself later down the line, as well as whatever other people happen to stumble upon your code.
This means:
- Consistent style
- Clear names, comments wherever needed
- Write a comment at the start of each function detailing it's function. If you go full retard, include parameter explanations and examples.
- Consustent use of whitespace to separate different parts of code.

The earlier you start doing this, the easier it will be later on. I know it's hard to start doing, and I also forget to do it properly from time to time, but it's a real useful habit.

Can't seem to post my code in this thread. Is this working?

I have an SQL query that returns 1 if a set is in a set of sets or 0 otherwise.

CREATE TABLE foo ( a INT);CREATE TABLE bar ( a INT, b INT);

I can't post the query, just the table creations.

I think SQL queries are censored or something. I can post anything but my SQL code right now, it seems.

To circumvent the sql injection prevention prevention, upload your query to some pastebin thing

2d rpg with guns and magic and cool story/lively environment/NPCs (tbh more story than game, it's like a book)

The person who wrote the code didn't even write anything that relied on flags from anything other than cmp (I literally found them doing dec and then checking for 0 with cmp) and I've tested it to check and I should be fine. The code is horribly disorganised and was really badly commented so I have to figure out how they're actually doing everything (it's a shell written in assembly).

sounds cool user.

One word
Clang
Format

OK, so maybe that's two words but you get my point.

A command line tool to take sin(x) or cos(x) and represent a given positive integer exponent of it in canonical form. i.e.
$ canonical sin 10cos(10x)-10cos(8x)+45cos(6x)-120cos(4x)+210cos(2x)-126------------------------------------------------------ -512
I've written it in common lisp, and hope to expand it to a general computer algebra system capable of up to A2 futher maths. It was mostly just experimentation with string concatenation as well as being an A-level revision exercise.

Has anyone else experimented with building a computer algebra system before?

If you're an A2 student, exams are fucking over mate (after tomorrow anyway). Why are you bothering? Doing maths at uni?

Try 16chan

I've got an exam tomorrow and a couple next week, one of which is FP2, which requires the expression of these functions in canonical form.

While I'm not doing maths at uni (if I get my firm), I will likely be taking maths modules, and studying subject matter that is mathematically dense.

Oh, thought after tomorrow it was only physics. Fair enough

I am working on an imageboard in Go. In the vein of Holla Forums.
So far it'll handle 2.5k requests a second while rendering a board with 20 threads each with 6 replies.
Gonna memcache the most viewed threads and some other things that don't require an SQL lookup every request.

You should learn to do it yourself you lazy faggot.

I'm dealing with a 2 item nested list in python.

What I need to do is for every instance of the x[1] in x, I need to append x[0] to another list and sort it.

ex; output
[['2000', 2], ['11', 2], ['11', 2], ['10003', 4], ['22', 4], ['123', 6], ['1234000', 10], ['44444444', 32], ['9999', 36]]
ex : expected output

[['11', 2], ['11', 2], ['2000', 2], ['22', 4], ['10003', 4], , ['123', 6], ['1234000', 10], ['44444444', 32], ['9999', 36]]

shit = [['2000', 2], ['11', 2], ['11', 2], ['10003', 4], ['22', 4], ['123', 6], ['1234000', 10], ['44444444', 32], ['9999', 36]]sorted_shit = sorted(shit, key=lambda x: (x[1], int(x[0])))
A few things to say about this:
- The fact that you have to do this in the first place is a red flag, because fixed-length lists of mixed types are a common antipattern used when someone doesn't have a clue about how to use classes. In other words, whoever generated that list is making things difficult for themselves by sticking to only the most basic concepts of Python rather than using the language to its full capabilities.
- ...though sorted() is a pretty common function so I'm going to guess you're not completely fluent in python, which might explain that.
- There are numbers coerced to strings there. Why?
- What do you need it for? (Sorting might not be the best solution, depending.)

Extremely ameteur over here. I still dont even fully get the lambda function, but will try this out.
I think i'd get banned if I posted the source code that produced this mess.

.sort(), I'm familiar with and use in the code, the way I was thinking I was going to have that work was take Take List 1, For every matching value, sort again and add to List 2 for printing.

x[0] being in string is simply a requirement of the codewars kata

The key= argument to sorted() describes how the sort function sees each element in the list. The lambda given to it just does a simple-ish conversion on the list items, turning ['2000', 2] into (2, 2000). Then the default sort function takes care of the rest.

Spoken like a true amateur.

But on what hardware specs?

I recently programmed my nanomachines to self assemble and form letters. Pic related 1.
Each main robot produces around 10 small units with their own sequence of instructions. The whole code is graphically represented with my AI system. Pic related 2.
But I wanted the robots to start from outside the screen, so I had to add around 30 "move forward" instructions before the actual sequence. It was easier to inject the instructions directly in the DNA, so I end up with weird towers. Pic related 3.

That's no big deal though, because the DNA injection is done procedurally (the start of each sub DNA is automatically detected and receive the DNA injection). This way I can work with the 2D view from pic related 2, instead of working with the 3D view from pic related 3.

The pros:
- it looks good
- the cube can come from outside the screen
- the moves can be horizontally flipped, so the final letter itself can be horizontally switched (and face the screen or not)

The cons:
- each letter has to be programmed separately
- each letter move sequence has to be reviewed frame per frame
- several rows of letter ("G O D I S" and "A C U B E") need delayed starts (or else there would be collision)

I don't intend to make an A star pathfinding version for this purpose, as it's prone to errors, or at least serious delays in the making of the structure.

Interesting project user.

>>>Holla Forums

I added line numbering to Nano because I badly needed it.
github.com/faissaloo/l-nano
Enable with one of the following in your .nanorc:
Decimal:
set linenumbers
Hexadecimal:
set linenumbers

That image makes me feel like I need to grow a dank beard and dye it all blue.
Is this how the SJWs get you?

Oops, just realised, hex is:
set hexlinenumbers