[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
/dpt/ - Daily Programming Thread
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 255
Thread images: 36
File: 436.png (130 KB, 640x400) Image search: [Google]
436.png
130 KB, 640x400
Old thread: >>54534082

>he fell for the kys meme
>>
>>54539924
First for SML
>>
Recursion was a mistake.

Around stacks, never relax!
>>
requesting the "dat goy" meme
>>
fags are bad and should feel bad
>>
>>54539924
Alright, let's continue this
>encapsulation
>not a meme

>inheritance over composition
>>
>>54539966
>not waifu2x
nice false flag

>>54539978
kys
>>
>>54539984
>kys
kys
>>
>>54539984
>>54540026
I wish bunnyman would wordfilter kys to something more fun like kimochi
>>
>>54539972
this
>>
reminder that the main trap poster, the actual tranny, samefags

>>54538088
>>>54534005
>>>54534027
>>
File: Programming-Projects-for-N00bz.jpg (311 KB, 1261x1000) Image search: [Google]
Programming-Projects-for-N00bz.jpg
311 KB, 1261x1000
If most of these are beyond my comprehension of how to start them and create a working solution in any language, should I just kill myself now?
>>
>>54540133
>how do i google
>>
>>54540120
Fuck off, nobody gives a shit.
>>
>>54539966
get on your knees, Hime
>>
>>54540133
Yes, those are all easy. The title should be:
/g/'s Programming Projects if you want to be a codemonkey
>>
>>54540133
No you start with the easy shit.
Try these. I've ordered them in my guess at difficulty:
>FizzBuzz
>Count Vowels in a String
>Reverse a String
>Password Generator
>Linked List
>Sorting Algorithm
>Triangle Number Algorithm
>N Queens
>>
>he fell for the you need math for Haskell meme
This shit isn't even hard
http://www.vex.net/~trebla/haskell/prerequisite.xhtml
>>
>>54540193
Learning any language isn't difficult

The difficulty is in using it to its full extent
>>
>>54540193

Using only the math terminology described in that link you have provided, describe what a monad is.
>>
How do I learn C, /g/-chan?
>>
>>54540272
Read a book and write a lot of code. And by a lot, I mean A LOT. Until you get comfortable with it. Then proceed to the next part of the book.

Don't give up or you won't accomplish shit, ever. Don't expect results immediately. Keep trying, keep googling, keep being hungry for knowledge.
>>
>>54539924
What are you listening to while programming?
What are you programming?
>https://www.youtube.com/watch?v=pa14VNsdSYM
>https://www.youtube.com/watch?v=agrXgrAgQ0U
>implementing Braintree payment in my website
>>
>>54540272

In a trial by fire. If you succeed the trial by fire, you will know C, and be allowed to learn other programming languages, and eventually call yourself a programmer. If you do not succeed the trial by fire, you should immediately stop all programming (don't even learn JavaScript), and find another profession. Maybe Graphic Design or Law.

In all seriousness, read this:
https://thepiratebay.org/torrent/9394908/C_Primer_Plus_6th_Edition_Dec_2013
>>
>>54540323
mhm mhm, do you have any book recommendations?
>>
>>54540328
>What are you listening to while programming?
Super Mario RPG OST

>What are you programming?
This shit >>54540166 because I'm a fucking faggot.
>>
>>54540338
Just pick whatever, really, the book is going to teach you how the language works and how you write it, but it's up to you to learn it.

You won't learn just by reading it, you learn by practicing.
>>
>>54540335
>>54540365
Sounds good, thank you!~
>>
Is there a quick way of checking if a file exist.
Trying to open it with ifstream then closing it is the only idea I have to try this but it seems like itd take forever.
>>
>>54540375
You should post your language for questions like these
>>
>>54540375

In what language and what operating system? I/O is usually operating system specific and varies in implementation between programming languages.
>>
>>54540328

While programming, I typically listen to long 1-2 hour mixes on youtube of some sort of electronic music, such as electro-swing.

I'm not programming anything right now. I'm actually about to head to bed. Tomorrow, I will be programming an FFT in Java, and likely regretting not doing this earlier.

>>54540375

https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform

>>54540398

Well, considering he said "ifstream", I'd say there's a very high chance he's talking about C++.
>>
>>54540410
>Tomorrow, I will be programming an FFT in Java, and likely regretting not doing this earlier.
That sounds very interesting. Night pal
>>
>>54540102
Scala's type system is inherently unsafe and is dynamic to a certain extent (i.e. downcasting is allowed because type information is stored at runtime, even though it may be unsafe to perform)
>>54540094
there's no distinction between classes of bugs in most cases. any bug can be offset to the type checker. for example, if my application needs to verify that URLs are properly formatted but dont have access to a dependent type checker (which would allow all classes of errors to be offset to typechecking), i can still get most of the safety by defining:
-- Doesn't expose the constructor for Url for added safety
module SafeUrls (Url, toUrl) where

-- The type that all URLs must be passed in
newtype Url = Url String

toUrl :: String -> Maybe Url
toUrl str = if checkUrl url then Just (Url str) else Nothing

then I can define functions in terms of this URL type:
httpGet :: Url -> IO String

so when I call httpGet (or another function that requires me to pass a URL), the only way to get the string into that form is to explicitly verify that the URL is correct. if i forget to do that, then I get a type error and there's no real way of cheating it here.
another example of this concept could be units of measure or keeping track of permissions for a file through the type
>>
>>54540133
>>
>>54540428
Nice blogpost, but none of this says anything about implementation bugs, which I've found to be the majority of bugs in personal and professional work projects. In any case, lack of type checker never felt constraining to me, even after using static typed languages for about a decade and a half more
>>
>>54540166
#include <stdio.h>

int main(int argc, char *argv[])
{
int a, e, i, o, u;
a = e = i = o = u = 0;

while(*argv[1]++)
{
if (*argv[1] == 'a' || *argv[1] == 'A') a++;
if (*argv[1] == 'e' || *argv[1] == 'E') e++;
if (*argv[1] == 'i' || *argv[1] == 'I') i++;
if (*argv[1] == 'o' || *argv[1] == 'O') o++;
if (*argv[1] == 'u' || *argv[1] == 'U') u++;
}

printf("a: %d\ne: %d\ni: %d\no: %d\nu: %d\n",
a, e, i, o, u);
return 0;
}


how do you reverse a string tho?
iterate backwards and put char in a buffer/print it?
>>
>>54540449
>how do you reverse a string tho?
The easiest naive way to do it is to use a queue.
O(n) running time and space
>>
>>54540449
anon, that's very very ugly. you can do better.
>>
>>54540445
what kind of implementation bug would not be reduced by using this kind of strategy?
the only really common cause for bugs other than type errors (or what could logically be made type errors) is bugs arising from mutable state or like array indexing
>>
>>54540473
make me feel bad and post your 1 line haskell version~
>>
>>54540328
Currently listening to some classic mgs themes.

I just finished converting my voxel renderer from opengl 1.0 style immediate mode to highly advanced bleeding edge opengl 1.5 style vertex buffer objects to get a speedup somewhere greater than 25x. So much fucking code. At least vim and its macros made it much less painful.

I need to unfuck the order I'm rendering vertices (some are clockwise some are counterclockwise) in though so I can use face culling. I also wanna add support for rendering multiple vbo's and using multiple spritesheets.

Eventually I need to make vbo recalculation occur on a separate thread so that mutation to the voxel grid during rendering doesn't cause massive fucking lagspikes
>>
>>54540449
Yeah. Temporarily write to a buffer string, then copy it back on the original string. Be careful about the \0 character, that shouldn't be reversed. Look up malloc and memcpy.
>>
>>54540338
'Pointers on C' if you want to learn it in depth. it's pretty long (~600 pages) but explores every nook and cranny of the language. I'm at the chapter about arrays and it just spend several sections on comparing the performance of pointers vs subscripts by analyzing the produced assembly code
>>
>>54540480
Implementation bugs like
>does this page redirect here
>do I get the right json data through my response using this request
>is this data calculated correctly
etc
>>
>>54540449
>code
You probably want to change those if statements in something more sexy.

Damn I wonder if there's some function that checks if a char is a vowel or not?
>>
File: folder.jpg (25 KB, 500x500) Image search: [Google]
folder.jpg
25 KB, 500x500
>>54540328
pic related
>>54540530
the data being calculated correctly is the only one that can't be easily encoded in a type (since it isn't a data structure). although if it's not simply pure arithmetic, having type safety narrows down the amount of ways you can use the data and verifies that you're not going to use the wrong one of two variables because of a typo. for json it could be verified to be in the right format whenever it is created (or received). for example I could have two separate types for the JSON received (one for success and one for failure) and then encode the result of the parser as Either JsonFailure JsonSuccess (or equivalent).
>>
>>54540410
Thats a really good way. Thanks.
>>
>>54540579
So basically type systems don't solve implementation errors, got it
>>
hey fuckers i know nothing about programming, but I just want to ask, why the FUCK aren't you programming a sex robot?
>>
>>54540621
Nice meme.
>>
reversing a string is pretty hard
fuck me
>>
>>54540648
what are you struggling on?
>>
>>54540664
reversing the string
>>
>>54540670
are you retarded
allocate memory
for loop
start at end character
go to 0
wooow
>>
>>54540680
i dont know how to use malloc so i would like to do it withotu it
>>
>>54540686
Doing it without malloc is much harder and malloc is mandatory for using C, so learn malloc.
>>
>>54540686
k
for loop
start at beginning character
store index character
swap index with end character - index
wooow
>>
>>54540686
you are not going to do it without it.
or maybe you could but it's going to be a pain lol

just listen to us, read up documentation for malloc. do you understand what it does?
>>
File: ashley benson1.jpg (555 KB, 1768x3000) Image search: [Google]
ashley benson1.jpg
555 KB, 1768x3000
how do you guys deal with the no gf situation? do you allocate time and energy toward finding/maintaining a relationship or do you go all out on the programming and animu?

i just went to get my mail. there were two female clerks, both fairly attractive. the one that didn't serve me was fucking adorable, cute as hell and had a nice upbeat demeanor and everything

i'm probably good looking enough to a girl like one of those. the super qt one was staring at my package (the mail) like she was reading my name off the address label...

but right now i don't need the instant gratification of sex or anything, i think i just want to be as productive as i can, get crazy rich and release some sweet games and reap the rewards later on
>>
>>54540712
>>54540705
>>54540698

#include <stdio.h>

int main(int argc, char *argv[])
{

printf("%s\n", argv[1]);

char *temp = &argv[1][0];
while(*temp != '\0') ++temp;
while(temp-- && *temp) printf("%c", *temp);
puts("");

return 0;
}


i did dun did it!!
>>
>>54540715
programming and memes are all you need to live a happy life
>>
>>54539924
>reposting forced memes from other websites as the OP image

Is /dpt/ truly the cuckiest general of them all?
>>
>>54540725
Wise words

"programming and memes are all you need to live a happy life" -anon
>>
>>54540579
My nigga

Anyone here have an actual job?

We fell for the redux meme.
I'm done with JS frameworks.
>>
File: 1462835753286.jpg (28 KB, 550x550) Image search: [Google]
1462835753286.jpg
28 KB, 550x550
>>54540716
Learn a real language
 
<?php
echo strrev("C++ is literal trash");
?>
>>
>>54540751
Python/Django dev here

We fell for the angular meme, now we use knockout.js
>>
>>54540328
Whatever I feel like.
My file manager.
>>
>>54540766
i want to learn php because you can shell script with it
>>
>>54540648
wat
#include <iostream>
#include <string>

using namespace std;

int main() {
string oString = "blah";
string rString = oString;
for (int i = oString.length() - 1; i >= 0; i--)
rString[oString.length() - 1 - i] = oString[i];

cout << oString << '\n';
cout << rString << '\n';
return 0;
}

>>54540766
wat
>>
>>54540715
I have a gf, but I'm, also into things other than programming and anime, and it helps that my gf is into anime too
>>
File: rooms coloured tiles.png (13 KB, 512x384) Image search: [Google]
rooms coloured tiles.png
13 KB, 512x384
>>54539924

Redoing the old dungeon editing system and am working in getting rooms being registerable again (does a floodfill form the doorway to figure it out). Now it shows coloured alpha tiles to show which belongs to which room when in this menu.
>>
>>54540796
loli lord pls leave
>>
>>54540782
So how long until I'm no longer so retarded to the point where I could have thought of this myself?
>>
>>54540853
Idk, hopefully under 3 months.
>>
>>54540767
It was angular vs backbone for us,

How is knockout working for you guys?

I've realized all JS frameworks sound amazing before your app starts to grow to the point that sequential programming wont cover all of your needs and you have to start doing asynch stuff.

>>54540778
python would be a better choice

>>54540766
PHP is trash. Started programming at 14 with C++, was introduced to PHP through web development. The language is, absolutely trash.

>>54540788
Where does one find a cute anime watching girl who codes?
>>
>>54540867
>>54540853
samefag
C++ std strings dont have null termintaors
>>
>>54540853
As soon as you can look at a problem as a sequence of solutions. In programming, sometimes a sequence is very simple. Sometimes it's very complex. But the key is to break it down..

Any complicated task can be broken up into a series of (relatively) simple subtasks.
>>
>>54540875
in my specific case, tinder.

I also had to teach her to code, but it was pretty easy
>>
File: new dungeon editor.gif (363 KB, 509x376) Image search: [Google]
new dungeon editor.gif
363 KB, 509x376
So once I get the basics of the dungeon editor back in, what should I work on for my loli kidnapping sim?

-optimize pathing system by creating a priority system/other shit
-add cops back in and work on their AI
-add in gifts and make that impact lolis moods and opinion of you
-add in a childhood simulation that makes lolis associate concepts together to make use of that concept system I talked about before
-work on stealth stuff
-post-kidnapping loli AI in general
-pre-kidnapping loli AI in general

>>54540843

Why?
>>
>>54540905
GOTY coming in!
>>
>>54540875
>How is knockout working for you guys?
Fantastic. We only ever needed 2-way data binding since Django covered every JS need that wasn't Ajax. In that regards, Angular was very bloated and very difficult to maintain

Why backbone? Heard it was great, but wanted to know your company's personal motivations
>>
>>54540716
#include <stdio.h>

int main(int argc, char *argv[])
{

printf("%s\n", argv[1]);
unsigned long int i;
char *temp = &argv[1][0];
i = (unsigned long int) temp;
while(*temp != '\0') ++temp;
i = (unsigned long int) temp - i;
char buf[i+1];
char *bufp = &buf[0];
while((temp-- && *temp))
{
*bufp = *temp;
bufp++;
}
buf[i] = '\0';
printf("%s\n", buf);

return 0;
}


it now saves the characters to a buffer!
>>
File: popup.png (42 KB, 512x384) Image search: [Google]
popup.png
42 KB, 512x384
>>54540918

GOTY 2023
>>
>>54540796
Omg you're the loli dev, I was looking for updates on /agdg/ but none ;_; glad to see you here. Your code is amazing haha
>>
>>54540948
Why don't you upload your code to gitgud.io or neetco.de? They don't care about SJW.
>>
File: can bouncing.gif (930 KB, 509x381) Image search: [Google]
can bouncing.gif
930 KB, 509x381
>>54540969

I have a thread up on /agdg/ now, but I'm looking for a new place since Jim (site owner) is being a complete idiot right now and mass-banning mods/anyone he disagrees with, and is being especially negative towards lolis.

>>54540974

I'm fine with the private repo for now. I don't think many people would want to contribute, and if they do they're welcome to contact me on irc.
>>
>>54540996
are your sprites censored?
>>
>>54540996
On /vg/agdg/ ? Can't find you, I must be blind lol. And yeah the public repo would be a good idea, no need to accept contrib or pull req, just a readonly thing could be cool. Some people could learn a lot from your code structure and all
>>
>>54540996
>I have a thread up on /agdg/ now, but I'm looking for a new place since Jim (site owner) is being a complete idiot right now and mass-banning mods/anyone he disagrees with, and is being especially negative towards lolis.
>being negative towards lolis
Are you really talking about cripplechan? Even 4chan, the North Korea of chans, accepts lolis.
>>
File: a month of pee.png (46 KB, 512x384) Image search: [Google]
a month of pee.png
46 KB, 512x384
>>54541016

No.

>>54541022

No, on the other chan's /agdg/ board.I do post on AGDG here on /vg/ but I haven't for a few days since I was banned until tonight for "loli/shota pornography" for posting pics/gifs here that didn't even s how any nudity...

I also post in the OC/drawthreads on /jp/ too
>>>/jp/15212758

>>54541037

I am. Most of the pedo mods were banned or left. Copypaste(HW) isn't running things anymore, it's the guy who was running 2channel when hiroyuki was selling the users data.
>>
File: 3da.png (866 KB, 680x869) Image search: [Google]
3da.png
866 KB, 680x869
Guys, I don't know what to program. hlep
>>
>>54541075
neural network for memes
>>
>>54541063
There's also lainchan, but I don't know if it's active anymore.
>>
R8 my Collatz

#include <iostream>

int Collatz(int);

int main()
{
int n;
std::cin >> n;
Collatz(n);
}

int Collatz(int n)
{
if (n == 1)
{
std::cout << '\n' << n << " ";
return 1;
}
else if (n % 2 == 0)
{
std::cout << n << " ";
return Collatz(n / 2);
}
else
{
std::cout << '\n' << n << " ";
return Collatz(3 * n + 1);
}
}


>tfw starting to grasp trivial shit
>>
>>54541107
uint64_t *ur_mom's_weight_in_tonnes_LMAO
>>
>>54541107
There is no point in all those returns

There is no point outputting n instead of 1 when n == 1

Newline braces a shit

other than that, it's alright
>>
>>54541107
>cout
Disgusting. Printf is all you need in life.

Also Egyptian braces for lyfe.
if (foo) {
}

master race
>>
>>54541170
Are you retarded? It's a recursive algorithm with a tridirectional branch. 3 branches 3 returns.
>>
>>54541170
uwot

>>54541172
What's wrong with cout?
>>
>>54541187
Why the fuck are you recursing when the whole thing returns 1?

It would make sense if there was some alternative condition, like where you keep track of calls, and return the number of calls, but what you're doing right now has the same effect as not having those returns
>>
>>54539966
keep overflowing the stack, hime, while I overflow your butt with my semen
>>
How come this is the daily programming thread and yet there's only one (maybe two) projects even mentioned?
>>
So, what separates a code monkey from a developer?
>>
>>54541202
Not him, nothing's wrong with cout, but printf is significantly faster, shorter to write and is still viable for these small applications
>>
>>54541222
idk what to code mane
>>
>>54541204
Because the recursion has side effects (printing to the screen) you tard.

Otherwise the function would just be one line
int Colltz(int n) { return 1; }


>>54541202
I'm not a fan of cin and cout. They look like another fucking language thrown in the middle of the code.
>>
>>54541238
console in console out. Wow, that's a whole new language embedded inside C++.
>>
>>54541222
Some of us only have time to program professionally, but still like to talk about programming and/or memes

>>54541238
>Because the recursion has side effects (printing to the screen) you tard.
>Otherwise the function would just be one line
>int Colltz(int n) { return 1; }
Wow you still don't grasp trivial shit
your collatz function is equivalent to
void Collatz(int n) {
if (n == 1) {
std::cout << '\n' << n << " ";
}
else if (n % 2 == 0) {
std::cout << n << " ";
}
else {
std::cout << '\n' << n << " ";
}
}


and it makes no changes to your main since you call Collatz straight out without setting it to a variable
>>
>>54541222
I mention what I'm doing. I don't know how to record webms so I can't post videos like lolidev guy does though and my source code is too large for screen shots.
>>
>>54541254
Shit, cut too much
void Collatz(int n)
{
if (n == 1)
{
std::cout << '\n' << n << " ";
}
else if (n % 2 == 0)
{
std::cout << n << " ";
Collatz(n / 2);
}
else
{
std::cout << '\n' << n << " ";
Collatz(3 * n + 1);
}
}


Not reformatting this shit again
>>
>>54541222
func (f *Filesystem) List(dirname string) ([]*File, error) {
absDirname := fmt.Sprintf("%s%s", f.conf.RootDirname, dirname)
dir, err := os.Open(absDirname)
if err != nil {
return nil, err
}
defer dir.Close()

infos, err := dir.Readdir(-1)
if err != nil {
return nil, err
}

var files []*File
for _, info := range infos {
file := &File{
Name: info.Name(),
}
files = append(files, file)
}
return files, nil
}
>>
>>54541230
passed highschool math
>>
>>54540948
I need this, where can I see more
>>
>>54541265
So, all you did was remove the return 1?
>>
>>54541265
The return is more idiomatic.
>>
>>54541277
Yes, I removed your unnecessary return calls, why you felt like including them when the whole thing resolves to 1, makes no sense

>>54541285
How so?
>>
>>54541291
It's more immediately obvious that the code is recursive in the tail position.
>>
>>54541265
Original collatzfag here. What are the benefits of doing it this way instead?
>>
File: sup g.gif (3 MB, 509x379) Image search: [Google]
sup g.gif
3 MB, 509x379
>>54541274

Why would you possibly want that?
>>
>>54541291
Wasn't me, but I feel like the return 1 definitely doesn't hurt and is for completeness because it's easier to see where the recursion stops.
>>
is beginners.re the way to learn about reverse engineering?
>>
>>54541063
Oh ok for agdg. Thanks
>>
>>54541316
No stack overflow
>>
File: Capture.jpg (105 KB, 909x908) Image search: [Google]
Capture.jpg
105 KB, 909x908
>>54541326
you know very well.
Also I applaud you for even attempting this, found the the thread on infinitychan now so I'm gonna check it
>>
>>54541349
Are you sure that code wouldn't be tail call optimized? I'm pretty certain at least gcc can do tco. And even then do void functions really not increment the stack?
>>
File: 1462661662603.gif (4 MB, 200x360) Image search: [Google]
1462661662603.gif
4 MB, 200x360
>>54540449
>how do you reverse a string tho
You divide the string in two parts and iterate for half of it, substituting
#include <stdio.h> 
#include <string.h>
void reverse(char *str)
{
printf("Normal: %s\n", str);
char temp;
int len = strlen(str);
int halfLen = len/2;
for(int x = 0,y = len-1;x<halfLen;x++,y--)
{
temp = str[x];
str[x] = str[y];
str[y] = temp;
}
printf("Reversed: %s\n",str);
}

int main(void)
{

char inputString[] = "topkek";
reverse(inputString);
return 0;
>>
>>54541374
I made that post without any coffee in my system

The benefit is that you make it immediately obvious that all you're doing is printing a collatz sequence.

Adding in those returns adds meaningless implications.
>>
>>54540463
>Queue
Stack anon. Surely.
>>
>>54540463

Why not just a loop that swaps the ith with the n-1-ith one for n/2 iterations?
>>
>>54541403
They have meaning. It's obvious it's tail-calling recursion. Just checked the assembly of a version with cout replaced with printf. It's taill call optimized:
collatz:
.LFB12:
.cfi_startproc
pushq %rbx
.cfi_def_cfa_offset 16
.cfi_offset 3, -16
movl %edi, %ebx
.p2align 4,,10
.p2align 3
.L2:
xorl %eax, %eax
movl %ebx, %esi
movl $.LC0, %edi
call printf
cmpl $1, %ebx
je .L3
testb $1, %bl
jne .L4
movl %ebx, %eax
shrl $31, %eax
addl %eax, %ebx
sarl %ebx
jmp .L2
.p2align 4,,10
.p2align 3
.L4:
leal 1(%rbx,%rbx,2), %ebx
jmp .L2
.p2align 4,,10
.p2align 3
.L3:
movl $1, %eax
popq %rbx
.cfi_def_cfa_offset 8
ret
.cfi_endproc
>>
>>54541451
So with void, it's not tail-call optimized?
>>
>>54541459
No they both are. But with the returning one, it's more readable.
>>
>>54541390
std::string flange="123456";
std::stack cocks;
for(int n=0;n<flange.size();n++)
{
cocks.push(flange[n])
}
flange.clear();
while(cocks.empty()==0)
{
flange+=cocks.top();
cocks.pop();
}
std::cout<<flange;


Didn't even test it. There are probably tonnes of errors.

Alternatively and much lazier.
std::string A, B;
A="123456"
for(int n=A.size();n>0;n--)
{
B+=A[n];
}
std::cout<<B;
>>
>>54541451
Here's the version compiled without -O2:
collatz:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
movl -4(%rbp), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
cmpl $1, -4(%rbp)
jne .L3
movl $1, %eax
jmp .L4
.L3:
movl -4(%rbp), %eax
andl $1, %eax
testl %eax, %eax
jne .L5
movl -4(%rbp), %eax
movl %eax, %edx
shrl $31, %edx
addl %edx, %eax
sarl %eax
movl %eax, %edi
call collatz
jmp .L4
.L5:
movl -4(%rbp), %edx
movl %edx, %eax
addl %eax, %eax
addl %edx, %eax
addl $1, %eax
movl %eax, %edi
call collatz
.L4:
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
>>
>>54541471
>it's more readable.
Depends on the person reading.

When I see those returns, it tells me something might be done with the return

When I see the void version, it tells me it prints the current number in a formatted way, the prints the next one recursively
>>
>reversing a string
Literally just
string = "hello"
reversed_string = string[::-1]
assert(reversed_string == "olleh")
>>
>>54541484
Seems really unnecessary to create two strings or involve STL in order to do a simple operation.
>>
>>54541523
>thinks having bloated built-in libraries doing basic shit, rather than your own efficient ones is a good thing
Even better, if you're dynamically linking, all the bloat you don't use is included too!
>>
>>54541552
>thinks reinventing the wheel is productive
top meme lad
>>
>>54541572
No, he simply thinks that hitting nails with an anvil is a bad idea, because you can you a hammer.
>>
>>54541572
>>54541523
>execution time: 5 sec
>>
>>54541390
who is this little guy, does he have a youtube channel? what's the story, why does he keep raging this hard
>>
>>54541604
So he thinks with retarded analogies. Good to know
>>
>>54541611
Google koksal baba senpai
>>
File: 1463090589368.jpg (159 KB, 800x567) Image search: [Google]
1463090589368.jpg
159 KB, 800x567
>>54541606
>tfw execution time is 0.003 seconds
>>
>>54541639
what a slut
>>
>>54541612
Not as retarded as actually being equivalent to what you're doing.
>>
Time to post my own:
void reverse(char * c) {
int len = strlen(c);
char * buff = malloc(len+1);
for(int i = 0; i < len; i++) {
buff[i] = c[len-i-1];
}
buff[len] = '\0';
memcpy(c,buff,len+1);
}

Now the question is.... Do you faggots know why this code is likely to segfault on modern machines when used by a noob C programmer?
>>
>>54541572
>Le reinventing the wheel is bad meme
>>
>>54541670
There is literally no reason to use a temporary buffer, and you leak memory every time you call that function.
>>
>>54541665
>not reinventing the wheel is retarded
top wew lad

>>54541674
>implying implications
top kek lad
>>
>>54541686
>implying implications
You're only supposed to say that when someone >implies.
Get your memes right, bud.
>>
>>54541681
Fair enough on the leaking bit.
void reverse(char * c) {
int len = strlen(c);
char * buff = malloc(len);
for(int i = 0; i < len; i++) {
buff[i] = c[len-i-1];
}
memcpy(c,buff,len);
free(buff);
}

>no reason to use a temporary buffer
I like the structure of the code this way more.

So why is it possibly vulnerable to segfaults?
>>
>>54541686
You're not reinventing the wheel here, because the operation is basic, it's not even a wheel, it's a paper plane, which you can easily do yourself to accomplish a task of flying from your desk to the floor, instead of using an F-35 to do the same.
>>
>>54541702
do len+1 and write a '\0'
>>
>>54541693
The implication was made implicitly

>>54541711
>my definition of reinventing the wheel is the true definition
top jej lad
>>
>>54541538
std::string Opfaggot(std::string A)
{
std::string B;
for(int n=A.size();n>0;n--)
{
B+=A[n];
}
return B;
}

int main()
{
A="123456";
A=OPfaggot(A);
}


Pretty sure his code was C anyway. There are easier ways than this to reverse a std string.
>>
>>54541702
>I like the structure of the code this way more
It's flat out less efficient.
It has to go over the entire string, and then a second time as it copies it.
Doing it in place only needs to go over half of the string.
void reverse(char *str)
{
size_t len = strlen(str);
for (int i = 0; i < len / 2; ++i}
str[i] = str[len-i-1];
}

>So why is it possibly vulnerable to segfaults?
Your allocation doesn't have space for the null terminator.
>>
>>54541718
Nope that's not the reason. The code as it stands works. If I did what you suggest the return would be an empty string: \0
>>
>>54541719
Now you're just baiting.
Here's your (You)
>>
struct Settings {
boot_rom: String,
}

impl Settings {
fn new<T: ExactSizeIterator<Item=String>>(args: T) -> Self {
if 2 != args.len() {
panic!("Invalid arguments");
}

let mut iter = args.into_iter().skip(1);

Settings {
boot_rom: iter.next().unwrap()
}
}
}

fn main() {
let settings = Settings::new(std::env::args());
}

#[cfg(test)]
mod test {
use super::Settings;

#[test]
fn check_settings_new() {
let settings = Settings::new(vec!("rustboy".to_string(), "boot_rom".to_string()).into_iter());
assert_eq!(settings.boot_rom, "boot_rom");
}

#[test]
#[should_panic(expected = "Invalid arguments")]
fn check_settings_new_not_enough_params() {
let _ = Settings::new(vec!("rustboy".to_string()).into_iter());
}
}


How can I make new() not be generic?
>>
>>54541732
the last char '\0'
>>
>>54541753
Holy shit senpai. For a second I thought you were reversing a string and almost had a heart attack.
>>
>>54541727
>efficiency arguments
boring.

>add space for null terminator
Your C wizardry is weak. Your code is also vulnerable to segfaults.
>>
>>54541753
Why would you want to do that?

>>54541769
>boring
You're an idiot.
>Your code is also vulnerable to segfaults
Let me guess, because there might not be a null terminator?
Fucking idiot.
>>
>>54541780
No it's because you don't know how C compiles. On modern computers for security and optimization reasons, constant strings are placed in read-only sectors of programs.

char * c = "string";
reverse(c);

segfaults
>>
>>54541552
this, and the moment you want something more complex than fizzbuzz, you're shit out of luck
>>
>>54541269
you should check dir.Close errors
>>
>>54541808
That has literally nothing do with with my function.
My function takes modifiable C strings. Pass it anything else, and you're not satisfying the precondition of my function, so my code doesn't make any guarantees about anything.
>>
>>54541766
Ha, no, just wrapping command line parsing into a function with unit tests.

>>54541780
Why would I want to not spend 6 years waiting for my code to compile? I see no conceptual reason why I can't just make Settings::new take a &[&str], but std::env::Args returns an ExactSizeIterator<String>. This makes the unit tests clunky as fuck.
>>
>>54541808
>char c[] = "string";
reverse(c);


runs just fine mi fambino
>>
Python or Ruby
if I want a entry-level job?
>>
>>54541855
Python
>>
>>54540375
Call stat
>>
>>54541847
Not standard C.
Compile with -std=c11 (or c89) -Wall -Wpednatic
>>
>>54541834
std::env::Args IS a struct. I tried compiling your code (I didn't try the tests though) with the function signature changed to
fn new(args: std::env::Args) -> Self {

and it worked.

>>54541876
What?
You clearly don't know C.
>>
>>54541884
Yeah but user code can't construct a std::env::Args so I can't unit test it.
>>
>>54539924

O SHIT ITS DAT BOI WADDUP
>>
>>54541876
It's clean on my terminal.

>>54541847
not bad ese
>>
>>54541876
I always compile my shit with c11 mi fambimbo
>>
>>54541884
>What? You clearly don't know C.
A string literal is a `const char[]`. Modifying a `const char[]` is undefined behavior. Many compilers type string literals as `char[]` for backwards compatibility with pre-standard C.
>>
File: thedreamers.jpg (148 KB, 1280x960) Image search: [Google]
thedreamers.jpg
148 KB, 1280x960
I am sending some data to server with post and json and based on this data server will send me 20 floats.

Is there a reason to send data from server to client with json instead of plain text in html and split it into array after?
>>
>>54540120
just throwing this out there, I'm the actual tranny and I am NOT the trap poster

I mean unless there are multiple actual trannies here but that'd be a bit weird

ps eveyone here should probably have 'tranny' and 'trap' filtered at this point so if you don't you should get on that
>>
>>54541891
What do you have against generic functions? Rust is full of generic functions.

>>54541913
>A string literal is a `const char[]`.
No it's not. It's just a char[]. You might be confusing the C++ rules with the C ones.

http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf
>§6.4.5 - String literals
>Page 71
>For character string literals, the array elements have type char
>>
>>54541915
json support

Also json is returned as a valid json structure, whereas you have to do your own checks on text/html

In any other case, plaintext/html is fine, especially if what you're doing can't be expressed in json format anyway
>>
>>54541915
plain text in body*
>>
>>54541917
post boipucci
>>
>>54541827
I understand dir.Close() returns an error, but I don't know how that handle it other than fail silently. Should I panic, propagate the error or do something else?
>>
>>54541938
Fuck, so I am.
Surely you still can't modify a string literal in C?
>>
>>54541974
You should panic if you are an application, propagate if you are a library.
Failures on close can't really be 'handled' by most code. Only critical things like init can (and should) really do much about them, but it's still not nice to panic another person's process.
>>
>>54541976
>Surely you still can't modify a string literal in C?
Yes, it's undefined behaviour, but it is noted as a common extension.
>>
>>54541994
Just tried it on clang. Segfaults without -fwritable-strings:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
char *str = "Fuck you";
strncpy(&str[5], "me", 3);
printf("%s", str);
return EXIT_SUCCESS;
}
>>
>>54541976
I initially said modern machines, because you can't these days. The literals are placed in read only memory. Of course old systems didn't have read only memory. Here's how a literal would compile
    .section    .rodata
.LC0:
.string "Hello!"
.text
>>
>>54542007
I meant to add: This is with -std=c11, -Weverything
>>
File: 1463198678174.jpg (47 KB, 692x960) Image search: [Google]
1463198678174.jpg
47 KB, 692x960
>Java
>>
>>54540157
Post some non-code monkey exercises
>>
>>54541987
Thanks senpai. I've changed the code to:
    defer func(dir *os.File){
err := dir.Close()
if err != nil {
panic(err)
}
}(dir)

I'll post a dump of my project once I cleaned it up.
>>
File: 150516-1242.png (655 KB, 4000x2560) Image search: [Google]
150516-1242.png
655 KB, 4000x2560
Just completed another cracking challenge, this time related to PCAPs. Onto the next..
>>
>>54540484
Here's my APL oneliner:

{+/⍵∊ 'AEIOUaeiou'}
>>
File: 1453653438419.gif (147 KB, 850x613) Image search: [Google]
1453653438419.gif
147 KB, 850x613
>>54542045
1) a) Make a chip-8 emulator

b) Then make games in its assembly. You may design your own high-level language, but it must compile to chip-8 instructions first

2) a) Make a virtual machine according to the specs at challenge.synacor.com (you can put anything in the email field)

b) Finish all its puzzles

3) a) Create your own sound format, and a program which runs it which accepts cmd-line options for playing sound in various ways

b) Write music in it
>>
>>54539924
>>54542038
i like this meme
>>
>>54542102
>blondes
Platinum master race.
>>
>>54542102
Go away, you fucking avatarfag.
>>
>>54541987
This is the wrong approach.
You should panic when you're dealing with a programming error and propagate if it's not clear yet.
In that case, it may still be a user error.
If you're using functions in your application then the situation whether something is a programming or a user error may change depending on use case, if you always panic you're trashing reusability.

>>54542071
func foo() (val int, err error) {
defer func() {
if cerr := dir.Close(); cerr != nil {
err = cerr
}
}()
}
>>
>>54542174
Right now, I only panic when the web server is unable to start or stops.
>>
>>54542174
Also, there is one exception to this rule:
If it's trivial for the caller to check whether the input is correct then you may panic instead of erroring as well.
Array indeces are an example for such an exception, bounds checks as well.
It's trivial for the caller when both of the following are true:
- duplicating the check is very cheap (once in the function and once in the caller)
- the parameter cannot change its value between the caller check and the function check (shared resources and external resources for instance)
>>
>>54542222
Error handling at the highest level is debatable.
At the highest level you are not deciding how your caller will work with the error, but how the error is displayed to the user.
If you're fine with your users seeing a stack trace in addition to a clear error message then that's fine, although I've personally found it to be relatively annoying when using server applications that constantly spam stack traces.
>>
>>54542271
Right now I simply display the error to the user as plain text with status code 500 in case of a recoverable error. I'll eventually display a human readable error message to the user like 'unable to connect to the database'.
My biggest priority is to get all the features working and after that I'll start making the front end look nice along with proper error messages.
>>
complete newfag here, making a simple binary to base10 converter in c++
any of you senpaitachi able to tell me how to use positions in values, google is being a cuck and not helping
>>
>>54542401
12345 % 10 = 5
12345 % 100 = 45

12345 % 100 / 10 = 4
12345 % 1000 / 100 = 3
>>
>https://my.mixtape.moe/olsfsd.tar.xz
I finally got my file manager to list files and directories.
Anyone care to do a code review?
>>
>>54542420
cheers mynignog
>>
File: 1451683583776.gif (2 MB, 400x600) Image search: [Google]
1451683583776.gif
2 MB, 400x600
>>54540484
Not very elegant 2-liner
from sys import argv

print('\n'.join('{}: {}'.format(k, argv[1].count(k)) for k in 'aeiou'))
>>
>>54542648
Stop avatarfagging.
>>
File: 1451754656609.png (14 KB, 418x359) Image search: [Google]
1451754656609.png
14 KB, 418x359
>>54542721
No problem
>>
>>54542648

            foreach (char c in "aeiouy")
Console.WriteLine("{0}: {1}", c, test.Count(ch => c == ch));


:^)
>>
>>54542751
Easter?
>>
>>54542759
>y
>>
>>54542767

Sometimes.
>>
is the register keyword even used by modern C compilers anymore or do they omit it completely?
>>
>>54542819
Pretty sure it's obsolete.
>>
>>54542759
>muh warmongering MS puppet
>>
>>54542827

That's me. :)
>>
>>54542841
Why MS?
>>
>>54542906

C# is really good. Also, I like to play [spoiler]computer video games[/spoiler] and Linux is just barely catching up on that front.

>inb4 QEMU passthru
>>
Is there a more elegant way to do this?

# Remove URLS and @ mentions
text = re.sub(r"(?:\@|https?\://)\S+", "", tweet.text)

# Remove double quotes
string = text.replace('"', '').replace("'", '')

# Remove additional spaces
string = ' '.join(string.split())
>>
File: tag.jpg (44 KB, 312x322) Image search: [Google]
tag.jpg
44 KB, 312x322
>>54542919
>MFW they're finally adding safe pointers in C# 7
>>
>>54542919
You can still use Windows (so you can play games) and write code in non-MS languages. I think you can get a version of the JDK for Windows these days
>>
File: 1388986880234.png (588 KB, 1440x810) Image search: [Google]
1388986880234.png
588 KB, 1440x810
>>54542939
>>
>>54542906
He doesn't like freedom.
>>
>>54542938
C++ has had safe pointers for a while now.
>>
>>54542971
C++ will never be as comfy and easy going as C#, so who cares.
>>
>>54542759
("aeiouy".ToCharArray().ToList<char>()).ForEach(c => Console.WriteLine($"{c}:{test.Count(ch => c == ch)}"));
>>
Finally got the fucking one-liner

If only python's lambdas were more flexible

print('\n'.join('{}: {}'.format(k, l.count(k)) for l in [input()] for k in 'aeiou'))


There's still probably a more elegant way of doing this
>>
>if i put all this code into one line to make it completely unreadable and hard to understand people will think i'm cool
>>
File: retarded compiler.jpg (111 KB, 1233x678) Image search: [Google]
retarded compiler.jpg
111 KB, 1233x678
Hey /g/ Just reinstalled codeblocks (the version with mingw) And I can't see anything even if I compile the Hello World example. what changed in Codeblocks ? How do I fix this ? I get no errors .
>>
>>54543069
>implying it's about being cool
Trying to abuse a language as much as possible is a fun challenge on its own
>>
>>54543073
Create test 3.
>>
>>54543124
Thanks , a real advice would be more helpful.
>>
So I'm programming an Arduino here and I'm reading voice to text output with Bluetooth.

If I say "test" I get "116 101 115 116". What would be the cleanest way of converting these ASCII numbers to actual characters in a string?
>>
I need help with this python script. I want it to have basic signature checking function, like an AV. It's supposed to open all directories, then sub-directories, and then at last open the files to create a MD5 checksum for scanning. I'm pretty much stuck:
 import os
import hashlib


database = raw_input('>')

files_to_be_scanned = open("output.txt", "w,r")
# root prints the directories from specified path
# dirs prints the sub-dirs form root
# files prints all files from root and directory
for root, dirs, files in os.walk("./"):
for name in files:
# write all files to output text for later scanning
files_to_be_scanned.write(os.path.join(root, name))
# write new line after each file
files_to_be_scanned.write("\n")
with open(os.path.join(dirs, name), "r") as checkfile:
# reading the contents of the file
data = checkfile.read()
# pipe contents of file for checksum generation
md5_returned = hashlib.md5(data).hexdigest()
# if the files checsum matches any of those in cvd
# the message infected! is displayed, otherwise clean. is displayed
if aline == md5_returned:
print "Infected!"
else:
print "Clean."
>>
File: tree.png (88 KB, 200x200) Image search: [Google]
tree.png
88 KB, 200x200
I took this from wikipedia, you've probably seen this
this picture contains a cat

'Image of a tree with a steganographically hidden image. The hidden image is revealed by removing all but the two least significant bits of each color component and a subsequent normalization. The hidden image is shown below.'

https://en.wikipedia.org/wiki/Steganography

visit the page to see how the cat is supposed to look like

i'll post what i get below, would be nice if someone cared to tell me what i might be doing wrong
>>
File: cat.png (14 KB, 200x200) Image search: [Google]
cat.png
14 KB, 200x200
>>54543159
obviously something went wrong
does anyone see anything immediate or should i post code, if anyone is interested
>>
>>54543029
"aeiouy".Select(c => $"{c} : {test.Count(ch => ch == c)}").Foreach(Console.WriteLine);


I'm using one very generic extension method which isn't included in the core libraries unlike the Linq methods, (Foreach is an extension method that works on any IEnumerable). So I don't know if this counts, but it's bretty clean.
>>
>>54543178
definitely looks like a cat to me m8, you sure you didn't leave the image out in the sun too long?
>>
File: better_cat.png (19 KB, 200x200) Image search: [Google]
better_cat.png
19 KB, 200x200
>>54543221
is how he's supposed to look like
>>
File: 1458932507099.jpg (15 KB, 386x386) Image search: [Google]
1458932507099.jpg
15 KB, 386x386
>>54543159
>>54543178

shit's interesting, have codez?
>>
>>54543144
I'm a retard.
>>
>>54543157
We didn't help yesterday and we're not going to help today.
>>
>>54543243
yes
here, i know this should be done in C with the bit operations etc, also faster, but i'm just practicing
import Image
import ImageFilter


im = Image.open("tree.png")
size = im.size

def find():
for x in xrange(size[0]):
for y in xrange(size[1]):
pixel = im.getpixel((x,y))
pixel = map(lambda color: normalize(get_old_val(get_last_bits(convert(color))), 3, 255), pixel)
im.putpixel((x,y), tuple(pixel))

def convert(number):
vals = [128, 64, 32, 16, 8, 4, 2, 1]
num = [0]*len(vals)
for i in range(len(vals)):
if number>=vals[i]:
num[i] = 1
number-=vals[i]
return num

def get_last_bits(binary_number):
return binary_number[len(binary_number)-2:]

def get_old_val(last_bits):
return 2*last_bits[0] + 1*last_bits[1]

def normalize(val, oldMax, newMax):
if val == 0:
return val
return oldMax*newMax/val


find()
im.show()
#im.save("cat.png")


for each pixel in the tree pic, it takes the last two bits after converting the color into a binary number,
then converts the last two bits into a decimal,
then normalizes this decimal to a 255 color scheme
outputs pic

i think i'm losing info in the normalize operation where i go from a (0 to 3) scheme to a (0 255) scheme
>>
>>54543157
If you can't indent, or use functional programming where it's suited, you don't deserve help fampai
>>
>>54543073
you need to output a newline otherwise the stdout buffer won't be flushed
>>
>>54543307
>not just using the pillow library
lad
>>
>>54539924
pretty new to programming, any advice on learning c?
book recommendations?
>>
>>54543317
Thanks ! This solved my issue. Has this method been in the past too ? I don't remember being forced to use endline. Or this happens only in C and not in C++ ?
Thread replies: 255
Thread images: 36

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.