lainchan / λ
The Beginner's General
cond · 2017-07-24 21:18
hey /λ/
so my board has a joke that involves bumping a thread on the first day of every month. i wrote a shell script to do the task, but i can't figure out how to post images, and i dont want to have to rely on remote
the portion of relevant code is curl --form "file=@image.jpg" http//******
I always get one of two errors, seemingly at random:
>{"error":"Caught fatal error: Class 'CurlFile' not found in<strong>\/srv\/http\/post.php<\/strong> on line 1040"}
or
>curl: (26) couldn't open file "image.jpg
ive read through the man page and it looks right to me, and ive also seen examples where it was used to upload images for a post. can anyone point me in the right direction on what I'm screwing up??
pic unrelated
λx.x · 2017-07-28 19:21
This is the Beginner's General for beginners' questions.
If you have a simple question and a suitable thread doesn't already exist, just post it here and someone will probably try to answer it for you.
Remember to do some research before asking your question. No one wants to answer a question that a simple search can already resolve.
null · 2017-07-28 19:22
>>2657
How old is the particular standard? Is it K&R C, ANSI C, C89, C99, or something else?
What are the compiler issues? They could be normal messages.
Windows only supports C89 fully, from what I know, but I've also read they're working on this in recent years.
Moore · 2017-07-28 19:29
>>2657
The C language was standardized in 1989 (called ANSI C).
If your book was written before 1989 (unlikely), then consider switching to another one. Otherwise, it is fine.
https://en.wikipedia.org/wiki/ANSI_C
>It all worked out under Linux but now I'm on my windows box and I got some compiler problems. After I looked it up I found out that the books i teaching me "old standarts".
The opposite is more likely, your code is using a newer standard and the Windows compiler is using an older standard by default.
The compiler should have an option to specify which standard to use. This is how you do it with GCC and Clang.
https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
Cereal Killer · 2017-07-28 20:29
I just finished reading the cygwin manual and I just started the gcc manual and I'm overwhelmed because I don't know what many of those options are even refering to.
Should i continue with all the gcc manual or what chapters should i focus in? So far C is my first language i want to get used to the proper tools.
cdr · 2017-07-28 21:22
What steps should i take for learning front end stuff and web dev? I was considering starting with the html,css,php, and mysql book, but would i be better off starting with something else? For background info, I have touched on python, am pretty familiar with java, and have been doing a lot of things with c for kernel modules (limited knowledge on that though, i'm not writing hardware drivers yet). I already know some fundamental html and css from years ago.
Nell · 2017-07-28 21:23
>>2669
You should focus on getting your code to compile and continue reading your book.
if · 2017-07-28 23:53
>>2674
I'm with this.
Though "old programming standards" is indeed an issue, the underlying principles are the same, and it'd be a waste to start all over again with new books each time the book you're reading turns out slightly inadequate. And they will.
You can always learn the new C style conventions and features of the newer languages, but meanwhile, you might get good practice in looking up your error messages in a search engine and applying the fixes, which is something you'll be doing for the rest of your life (if you keep using computers that is), instead of just relying on everything just working right away as it's given to you.
Aristóteles Amadópulus · 2017-07-29 00:03
>>2674
>>2676
Ah man I thought we were responding to >>2666.
>>2669
Don't read the gcc book, what for? It's huge, you won't remember the vast majority of it, and you won't be using any of it anytime soon or in the next 50 years for that matter.
You're better off reading the relevant section when you need some unusual compilation flags for whatever reason. If, however, you want to dig a bit into what happens when you compile with gcc I suggest you read a bit about the ELF format, linking, linker scripts, ELF header sections, and generally use tools such as gdb, objdump and readelf to understand a bit about your object files.
Maybe you want to read about dynamic linking and how compilers and the kernel handle that. Or what some symbols such as __start are for. Maybe even how your kernel schedules processes, pages memory space, and so on.
All that stuff is way more interesting and relevant to you than the details of gcc, moreso since gcc is kind of obfuscated to be fuarrrking hard to configure. And the manual is so dry you'll die from dehydration after 50 pages.
Lain Iwakura · 2017-07-29 00:10
>>2677
Addendum.
I don't know what you want either, but if you want a personal suggestion from me, check out the book from beginners.re it's entertaining and informative.
That (and the post before) is if you want to learn low level details of object files. If what you want is to be a good programmer (in whatever language) this is all mostly irrelevant. Or marginally so.
Jens Hansen · 2017-07-29 12:35
>>2678
>I don't know what you want either,
The original post was on another thread which hit the post limit.
He is trying to learn C and found that his code was working on Linux but not Windows and suspected the problem was to do with which specific C standard he was using vs. what the compiler was expecting.
Ivan Horvat · 2017-07-30 02:28
Would i be better off learning just JS, or should i primarily learn coffeescript or clojurescript?
Naomi Nascimento · 2017-07-30 02:59
>>2674
That is simple, I'm just concerned on the compilation and debugging process.
>>2677
>>2678
How it works isn't my concern now. Reading the manual has been tiresome and people here is right I should focus on learning C and consult the manual when a doubt comes to me.
>>2687
That's not me but does sound like something that happen to me.
byte · 2017-07-30 05:05
>>2695
Yes when I wrote that you learned the ELF format n soykaf I was lacking a lot of context about your problem. Never mind all that.
Ivan Horvat · 2017-07-30 08:10
>>2665
My book teaches C99, my compiler on Windows supported C89.
>>2666
Thank you, I figured it out :3
>>2676
Thanks for your answers, I was just confused and didnot want to learn "outdated" stuff.
>>2687
That was the problem.
Thanks you guys for all the answers, I will continue using my book even if it's not up to date. I'm learning C to prepare for University (where I will have to learn it). I will try to get the basic syntax and then look what they will teach me.
Thanks for your helpfull responses.
roll · 2017-07-31 23:17
>>2694
Learn Js from the output of coffee script.
list · 2017-08-01 20:09
I finally tried to compile a c program through cygwin with gcc
This program https://pastebin.com/gnkEarsE with the filename Text1.c
But I'm getting these errors
Text1.c:7:5: error: conflict for ‘getline’
int getline (char line[], int maxline);
^
In file included from /usr/include/stdio.h:29:0,
from Text1.c:4:
/usr/include/sys/stdio.h:35:9: note: the previews 'getline' declaration was here
ssize_t _EXFUN(getline, (char **, size_t *, FILE *));
^
Text1.c:11:1: warning. the return type is ‘int’ by default [-Wimplicit-int]
main()
^
Text1.c:31:5: error: conflict for ‘getline’
int getline(char s[],int lim)
^
In file included from /usr/include/stdio.h:29:0,
from Text1.c:4:
/usr/include/sys/stdio.h:35:9: note: the previews 'getline' declaration was here
ssize_t _EXFUN(getline, (char **, size_t *, FILE *));
^ I have no idea what these errors mean and people here may not be able to help me too much because I'm not using cygwin in english, I had to translate these error messages to post here.
Sabo Engle · 2017-08-01 20:26
>>2738
> Text1.c:7:5: error: conflict for ‘getline’
The error means a function with the name `getline` already exists. It is not in your code, it is in the C standard library (/usr/include/sys/stdio.h).
Try changing the name of your `getline` function to something different.
>Text1.c:11:1: warning. the return type is ‘int’ by default [-Wimplicit-int]
You did not put anything for the return type of your `main` function. `main` should always return `int`.
FILLER · 2017-08-01 23:30
>>2738
The name 'getline' is taken.
http://man7.org/linux/man-pages/man3/getline.3.html
>I'm not using cygwin in english
>previews
http://www.dictionary.com/browse/previous
Six · 2017-08-02 03:53
Can I use the Scheme books along with Haskell? Last time I read the SCIP the book didnt focus too much on the Scheme language.
Unnamed · 2017-08-02 10:07
>>2738
>https://pastebin.com/gnkEarsE
>arbitrary long imput lines
>#define MAXLINE 1000 /*maximum input line length*/
$ wget -O tbg 'https://lainchan.org/%CE%BB/res/2664.html'
$ wget -O tbgold 'https://lainchan.org/%CE%BB/res/2.html'
$ wc tbg*
0 3091 42921 tbg
0 31999 394426 tbgold
0 35090 437347 total
Nameless · 2017-08-02 10:12
>>2744
Which books in particular? While SICP is not about Scheme, it does lean on it heavily in order to teach a wide range of styles and techniques. So I would suggest against using a language that's strongly attached to a particular style, like Haskell is.
The later chapters will also be complicated to adapt without meta-programming.
Sipho Nkosi · 2017-08-02 19:37
>>2739
>>2743
I see now. That program was taken from R&K so it must be one of those programs that do not work with current standards, I see what tweaks can I do to it.
Thank you
>>2748
the threads 404
Cowboy · 2017-08-02 23:55
>>2749
>Which books in particular
Scheme books in general, I meant.
The thing is: as much as I find Scheme interesting, I will probably have Haskell as my main func-prog lang. I just wanted to read SCIP and other interesting scheme books since they will give a great programming knowledge.
If I read them using Scheme, will I be able to use the knowledge from books like SCIP to other languages or to my programming skills in general?
Torvalds · 2017-08-03 05:34
>>2757
It strongly depends on the book in question.
SICP is supposed to be a general foundation in computer science, so it's certainly worth reading even if you're not interested in Scheme. Something like The Little Schemer is much more 'about Scheme', but it's also an excellent introduction to recursion and a very enjoyable read in its own right.
Even if you plan to focus on Haskell in the future, I would suggest going through those books in Scheme, as the language lends itself very well to the lessons illustrated. Later when you understand the principles it will be easy to adapt them to other languages like Haskell.
Plus, learning new languages and exploring methodologies can never hurt as a programmer.
Bobby Newmark · 2017-08-04 19:32
Hi lainons, I’m currently running Anki on my version of linux (lubuntu) and while I can get the program itself to run, I can’t for the life of me get the audio to work alongside the flashcards. I’ve been trying to get Anki to run audio by getting it to utilise MPV for the audio side of things, but I’m not having much luck. I’ve installed the following addon calling “Anki MPV” : https://github.com/tsudoko/anki-mpv
For this to work you also need to install “pympv”: https://github.com/tsudoko/anki-mpv
The implementation of pympv is where I run into problems, if you look at the code in question it relies on a piece of code called “import mpv”, however, this code does not work. Running “import mpv” in python returns the value:
“Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mpv”
If I run Anki through the terminal, it launches but I receive the following error messages:
First error, shown in a popup window in the Anki program itself:
“An error occurred in an add-on.
Please post on the add-on forum:
https://anki.tenderapp.com/discussions/add-ons
Traceback (most recent call last):
File "aqt/addons.py", line 41, in loadAddons
File "/home/aholmes/.local/share/Anki2/addons/mpvaddon.py", line 6, in <module>
import mpv
ImportError: No module named mpv”
Error two, shown in the terminal:
“aholmes@Harpsichor:~$ anki
Unable to load library icui18n "Cannot load library icui18n: (libicui18n.so.48: cannot open shared object file: No such file or directory)"
QGtkStyle was unable to detect the current GTK+ theme.
Traceback (most recent call last):
File "aqt/addons.py", line 41, in loadAddons
File "/home/aholmes/.local/share/Anki2/addons/mpvaddon.py", line 6, in <module>
import mpv
ImportError: No module named mpv”
Can anyone competent in Python or general Linux troubleshooting give me a hand? I’m pretty new to the operating system, and even with the assitance of a computer science friend but have had no luck. What could be the issue here? Thanks lains.
McCarthy · 2017-08-04 20:37
>>2798
>import mpv
>ImportError: No module named mpv
Did you forget to run the setup.py that came with pympv?
Terzibashjian · 2017-08-04 20:43
Should I read the GDB manual or is there a better way to learn how to debug?
bit · 2017-08-04 20:58
>>2799
Damn, I'm a fuarrrking idiot. That having been said, the readme doesn't list any dependencies and after running setup.py I'm now getting the following message returned:
aholmes@Harpsichor:~/Downloads/pympv-master$ ./setup.py Compiling mpv.pyx because it changed. [1/1] Cythonizing mpv.pyx usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied
Donna Hawthorne · 2017-08-04 21:15
>>2801
./setup.py build
./setup.py install
Faye Valentine · 2017-08-04 21:34
>>2802
Thanks anon, I've done all that but now I'm running into syntax errors with file provided at: https://github.com/tsudoko/anki-mpv
The errors in question are the following:
aholmes@Harpsichor:~/.local/share/Anki2/addons$ ./mpvaddon.py
from: can't read /var/mail/locale
from: can't read /var/mail/anki
./mpvaddon.py: line 15: m: command not found
./mpvaddon.py: line 18: syntax error near unexpected token `('
./mpvaddon.py: line 18: `def mpv_init():'
This is what I get in the terminal, I'm pretty bewildered by it all since I'm not even a programmer, and the friend helping me isn't especially familiar with python. Is the code I'm using from github just fundamentally broken?
Masami Eiri · 2017-08-04 23:18
>>2803
The file from anki-mpv is called anki-mpv.py, I don't know how you arrived at mpvaddon.py. Regardless, you are trying to run a python script without a hashbang as a shell script, but the shell doesn't speak python. You are not supposed to run the addon file, just launch Anki again like in >>2798.
Eldon Tyrell · 2017-08-05 00:42
>>2804
I had changed the name, but the code in the file is identical to the code on github. Just to be sure, I removed my version with the different filename, redownloaded anki-mpv.py from github and placed it in the appropriate directory. However, if I now run anki from terminal, it still returns errors as previously, so I'm not sure where to go from here.
Do you think I should try opening anki-mpv.py in nano and adding a hashbang at the top of the file? Something like #! usr/bin/anki?
Here's the error in question:
Traceback (most recent call last):
File "aqt/addons.py", line 41, in loadAddons
File "/home/aholmes/.local/share/Anki2/addons/anki-mpv.py", line 6, in <module>
import mpv
ImportError: No module named mpv
Dujour · 2017-08-05 03:51
>>2806
>Do you think I should try [...] adding a hashbang
No. Forget about the hashbang, that's just the explanation for why it was the shell that tried to interpret the python script. Once you have copied it to the addons folder, your business with the anki-mpv.py file is concluded.
>ImportError: No module named mpv
If importing still fails, the pympv installation >>2802 probably didn't work. In >>2803 you said
>I've done all that
so if there were any errors, post them. If there weren't, see if importing mpv into a standalone python interpreter works.
Frank Garza · 2017-08-05 10:13
>>2810
Lain's issue involves the 2 series.
Case · 2017-08-05 15:37
>>2800
I would encourage defusing a binary bomb, it takes a good few days for a beginner (for all 6 stages I mean), and it's really interesting. It's entirely in GDB, so you'll learn all kinds of tips and tricks.
Here, there's a readme inside: https://a.safe.moe/SlxRY.zip
Start off with "gdb bomb", then set a breakpoint on something like "main". From there, step through and see if you can get the right password for each stage. If you get it wrong, you "explode" and it prints a message and exits. If you were in my computer science class, you lose a half a point every time you explode, but if you just set a breakpoint on the "explode" function you can never explode.
You can put the passwords you've figured out so far in a text file and run it with something like "r bomb solutions.txt", and it will skip over the sections you've already done
drop · 2017-08-05 15:46
>>2812
Sorry, I wrote "there's a readme inside" but I hadn't actually read it. The readme is only one line, but if you google "binary bomb" there's tons of help, and if you get stuck there's even walkthroughs
Bobby Newmark · 2017-08-05 17:29
>>2808
Sup lain, I tried reinstalling pympv but still no luck on that front. It's been pretty baffling because python has consistently managed import mpv, yet anki itself has failed to. I figure it's just some strange bug with anki, a friend of mine simply recommended installing mplayer instead of attempting to use MPV, and now the audio works like a charm. I guess anki-mpv is just bugged or something, oh well, got my program working now. Thanks for your time lain.
>>2810
Sorry modman, my bad. It is in fact python 2, to clarify.
Drano · 2017-08-05 19:23
please help.
i have this code for a textbox
Textbox.text= "title" & vbnewline & " information"
is posible change the font at the title?
Marly Krushkhova · 2017-08-05 23:25
>>2817
You can use the properties pane in the GUI editor in Visual Studio to do stuff like that.
Emmanuel · 2017-08-06 01:05
Hey,
I was teaching two friends of mine C because they are interested in programming.
I am no professional myself, though; I am only helping my friends because I've been doing this for a while longer.
So, I came across a weird thing that was happening while I was showing the dangers of integer division.
I was using the following code:
int a = 2;
int b = 5;
// this will cause integer division because we didn't typecast:
printf("%f\n", a/b);
// this will produce a correct result:
printf("%f\n", a/(float)b);
// this will again produce a wrong integer value (for demonstration purposes)
printf("%f\n", a/b);
The output of this was not what I expected, though.
Output:
0.000000
0.400000
0.400000
The first two results as I expected; however, the third one is weird; why did it give me the correct result?
I later tried something else to see what happens; I changed the value of b to 3 and kept the rest of the code the same.
The result was still:
0.000000
0.400000
0.400000
In the end, I decided to typecast b in the third call to printf, and I got a correct result:
0.000000
0.400000
0.666667
Case · 2017-08-06 02:20
>>2819
I am the person who posted this question, and I would like to add a few more details:
The compiler I'm using is gcc (c11).
Operating system: Linux Mint 18.2 (64-bit)
cdr · 2017-08-06 09:14
>>2819
This is more to do with CPU architecture than C.
On 64 bit Intel CPUs (like yours), functions arguments are passed by CPU registers (and then on the stack if there are not enough registers).
The key thing to know is that your CPU has different registers for floating point values.
So in the first printf your floating point register is 0.
The second printf, the compiler put the correct result into the floating point registers because you used the cast to float.
The third time is like the first, printf uses what ever is in the floating point register, which is still 0.4.
If you print a different floating point value between 2 and 3, you will so that the last one will repeat whatever is before it:
printf("%f\n", 666.0);
/ /=> 666.000000
printf("%f\n", a/b);
/ /=> 666.000000
There was a good article on lobste.rs a few months ago explaining exactly this but I can't find it now.
The Oracle · 2017-08-06 13:41
>>2822
Thank you so much for explaining it for me! :)
Von Neumann · 2017-08-06 13:48
>>2819
>>2822
That's really fuarrrking cool.
Technician · 2017-08-06 16:25
Learning Coffee Script with CoffeeScript in Action. I'm studying the JS output.
There is one thing I can't understand. Here are some pieces of code.
The first is from the REPL:
coffee> x for x in [1,2,3]
[ 1, 2, 3 ]
coffee> z = x for x in [1,2,3]
[ 1, 2, 3 ]
coffee> z
3
The other shows compiled JS.
x for x in [1,2,3]
z = x for x in [1,2,3]
^D
(function() {
var i, j, len, len1, ref, ref1, x, z;
ref = [1, 2, 3];
for (i = 0, len = ref.length; i < len; i++) {
x = ref[i];
x; /* that doesn't matter */
}
ref1 = [1, 2, 3];
for (j = 0, len1 = ref1.length; j < len1; j++) {
x = ref1[j];
z = x;
}
}).call(this);
The problem is obvious: where is the list constructed ?
I found that while doing this:
coffee> x for x in "hello world".split(' ')
[ 'hello', 'world' ]
coffee> z = x for x in "hello world".split(' ')
[ 'hello', 'world' ]
coffee> z
'world'
It is a matter of parenthesis:
coffee> z = (x for x in "hello world".split(' '))
[ 'hello', 'world' ]
coffee> z
[ 'hello', 'world' ]
So I repeat the question: how does a list comes out of a comprehension when we know that x+1 for x in [1,2,3] outputs [ 2, 3, 4 ] in the REPL but compile to the following ?
(function() {
var i, len, ref, x;
ref = [1, 2, 3];
for (i = 0, len = ref.length; i < len; i++) {
x = ref[i];
x + 1;
}
}).call(this);
Donna Hawthorne · 2017-08-06 16:32
>>2825
I just answered my own question sorry.
For those who are looking for the same thing.
z = (x for x in "hello world".split(' '))
console.log(z)
Compiles to:
(function() {
var x, z;
z = (function() {
var i, len, ref, results;
ref = "hello world".split(' ');
results = [];
for (i = 0, len = ref.length; i < len; i++) {
x = ref[i];
results.push(x);
}
return results;
})();
console.log(z);
}).call(this);
It's a matter of how you are using the comprehension:
console.log(x*x for x in [1,2,3])
Compiles to:
(function() {
var x;
console.log((function() {
var i, len, ref, results;
ref = [1, 2, 3];
results = [];
for (i = 0, len = ref.length; i < len; i++) {
x = ref[i];
results.push(x * x);
}
return results;
})());
}).call(this);
If you don't use the comprehension as a whole thing you'll end up just performing the given actions over each elements of the list without storing it anywhere.
Incognito · 2017-08-06 17:20
>>2812
>>2813
This looks like it is outside my learning area, I just want to know how to debug a C program.
Cat Mother · 2017-08-07 19:06
>>2827
gdb comes with builtin help for all comands, just type `help <command>` in gdb, for example `help bt`.
Start compiling the simplest programs and functions you can think of, like empty functions, simple loops, etc, compile them witth the -g option and open them with gdb: `gdb ./a.out`
The basic commands you'll be using are: list, break, run, continue, x, info registers, step, nexti, bt, disas. Again, use the builtin help to get to know them better. Some usage examples are: break main, list main, info registers, i r eip, x/10xw $esp (or $rsp on x86_64). Those should be good to get started.
Prerequisite knowledge is some basic understanding of assembly, stack frames, function prologues.
Or you could read beej's guide, though I haven't read it so I can't say if it's good.
queue · 2017-08-08 17:58
>>2831
>Or you could read beej's guide, though I haven't read it so I can't say if it's good.
Now this looks interesting and the guy also has a book on C, I'll give both a look
Crazy Jake · 2017-08-08 22:14
template<typename T, typename A>
void vector<T,A>::reserve(int newalloc)
{
if (newalloc<=this– >space) return; // never decrease allocation
vector_base<T,A> b(this–>alloc,newalloc); // allocate new space
uninitialized_copy(b.elem,&b.elem[this–>sz],this–>elem); // copy
for (int i=0; i<this– >sz; ++i)
this– >alloc.destroy(&this– >elem[i]); // destroy old
swap<vector_base<T,A>>(*this,b); // swap representations
}
This is an example from Bjarne Stroustrup's PPP2. Why does he copy from b.elem into this->elem, and then destroy the stuff in this->elem?
Pris · 2017-08-08 23:00
>>2844
It's in the errata:
http://www.stroustrup.com/4th_printing3.html
DEBUG-CONTENTS · 2017-08-08 23:12
>>2845 That's the wrong book, and the errata for PPP2 doesn't say anything about this. The reserve() shown on the page you linked is different from the one shown in PPP2 in other ways too anyway.
Is it safe to say this is an error in the book that was never added to the errata, and it should actually be something more like this:
template<typename T, typename A>
void vector<T,A>::reserve(int newalloc)
{
if (newalloc<=this– >space) return; // never decrease allocation
vector_base<T,A> b(this–>alloc,newalloc); // allocate new space
uninitialized_copy(elem,&elem[this–>sz],b.elem); // copy
for (int i=0; i<this– >sz; ++i)
this–>alloc.destroy(&this– >elem[i]); // destroy old
swap<vector_base<T,A>>(*this,b); // swap representations
}
Von Neumann · 2017-08-10 20:52
What are arguments on GDB? If I run one what happens to my program?
John Peters, You Know, The Farmer · 2017-08-13 06:04
Having a bit of trouble understanding when to cast malloc and when it's not necessary.
I remember in K&R they cast malloc whenever they used it, but I'm reading a Data Structures book and they have the following snippet of code for implementing a Stack:
struct Node
{
char Elem;
Node* Next;
};
typedef struct Node* PtrToNode;
typedef struct Node* Stack;
/* ... */
void Push(char X, Stack S)
{
PtrToNode Temp;
Temp = malloc( sizeof(struct Node) );
/* Rest of push */
}
I understand what the call to malloc does (allocates enough memory for a new Node, and returns where in memory that Node is, which is why we assign it to Temp), but I'm not sure if it's good form or not to cast it as follows:
Temp = (Node* ) malloc( sizeof(struct Node) );
Nobody special · 2017-08-13 07:27
>>2911
malloc returns a void pointer, which in C (but not in C++) can be implicitly cast to any other pointer type. Temp's type is PtrToNode which is just an alias for Node*, so it all works out. I personally never use explicit casts with malloc, they make the code more verbose which is a bad thing. They should be used if you want a C++ compiler to be able to compile your code, but I never found myself in such a situation (I speculate that may be the case when using MSVC, but I don't have any experience with it, so that's just a guess).
Also, a little tip, instead of writing:
Temp = malloc( sizeof(struct Node) ); write:
Temp = malloc( sizeof(*Temp) ); This is better, because everything will work properly even if the type of Temp changes. Basically, you can pass any expression, not just a type, to sizeof, and it will give you the size of the result of that expression. The type of *Temp is the type Temp's type is a pointer to, so it allocates the same amount of space as your code right now.
Also, a fact that isn't very well known is that parentheses with sizeof are necessary only if you're using it with type, so the above can also be written like this:
Temp = malloc( sizeof *Temp ); I never use it though, because I'm so used to sizeof with parentheses.
John Peters, You Know, The Farmer · 2017-08-13 14:57
>>2915
>Temp = malloc( sizeof(*Temp) );
Wow, I never even thought to do that, but that's amazing!!
So I guess it comes down to whether you want it to be an explicit vs implicit cast.
Thanks, Lain!
Hopper · 2017-08-13 20:10
>>2917
>So I guess it comes down to whether you want it to be an explicit vs implicit cast.
It comes down to weather one day you will migrate the code over to C++ or include it in a C++ project.
Nobody special · 2017-08-14 20:41
My question is about CoffeeScript.
$ coffee -ps
class Hello
constructor: ->
@text = "hello"
display: ->
console.log(@text)
update: (str) ->
@text = str
obj = new Hello
obj.display
The preceding input give me the following output:
(function() {
var Hello, obj;
Hello = (function() {
function Hello() { // instance of object function
this.text = "hello";
}
Hello.prototype.display = function() {
return console.log(this.text);
};
Hello.prototype.update = function(str) {
return this.text = str;
};
return Hello;
})();
obj = new Hello;
obj.display;
}).call(this);
I don't understand why does Coffeescript needs the this argument in the top-level function. Also what could it contains ?
Also here is an unrelated link that I've found useful minutes ago: https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work
Sabo Engle · 2017-08-15 03:59
>>2935
http://javascript.crockford.com/private.html
Molly Millions · 2017-08-15 05:36
To interpret >>2936 's link, basically there's an error in the ecmascript standard and using `this` inside your function would access the wrong `this`. Typically the way people get around it for an inner function is to write something like `var that = this` outside the function's scope and access the `that` object inside the function. However .call and .apply both let you specify an object that the inner function can access as `this`. It's bypassing the same error, just in a different way
Agent Smith · 2017-08-15 13:43
>>2938
I know it already. I don't understand why the CoffeeScript compiler needs to do this in this particular case.
Wirth · 2017-08-15 14:14
A question for those who read [u]The Little Prover[/u].
the theorem [/code]equal-if[/code] I can't understand what implies the 't in the else expression.
(dethm equal-if (x y)
(if (equal x y) (equal x y) 't))
Naomi Nascimento · 2017-08-16 01:07
>>2942
When x does not equal y, the theorem doesn't state any conclusion, so it verifies by default.
Unknown · 2017-08-17 16:35
I just switched to i3wm and everything is working fine except my volume buttons. I found online that I should add this script to my config file
# Pulse Audio controls
bindsym XF86AudioRaiseVolume exec --no-startup-id pactl set-sink-volume 0 +5% #increase sound volume
bindsym XF86AudioLowerVolume exec --no-startup-id pactl set-sink-volume 0 -5% #decrease sound volume
bindsym XF86AudioMute exec --no-startup-id pactl set-sink-mute 0 toggle # mute sound but it doesn't work, I'm still stuck on full volume. I thought since it's just executing a command I'd see what happened if I just pasted pactl set-sink-volume 0 -5% into the terminal and it gave me the error pactl: invalid option -- '5'
How do I fix this?
Jens Hansen · 2017-08-17 16:50
>>2960
here's mine. it modifies the controls on the alsa device bc i don't use pulseaudio for everything.
bindsym XF86AudioMute exec "amixer -q -D hw:PCH sset Master toggle"
bindsym XF86AudioRaiseVolume exec "amixer -q -D hw:PCH sset Master 5%+"
bindsym XF86AudioLowerVolume exec "amixer -q -D hw:PCH sset Master 5%-" obviously you have to replace hw:PCH with your own primary sound device. your pactl command is correct according to the man page... are you sure you didn't just paste it wrong into the config file? maybe you accidentally deleted the 0... idk.
Mentat · 2017-08-17 16:57
>>2960
>>2961
same user.. for troubleshooting, see if it works if you specify the exact dB value instead of an offset. i.e.
pactl set-sink-volume 0 1dB
or
pactl set-sink-volume 0 50%
also, make sure 0 is a valid sink. maybe try using its symbolic name instead.
Gyula Kovacs · 2017-08-19 13:29
I've been studying web development to try and get employed in tech ASAP.
I have a fair understanding of JS, CSS and HTML and have been studying Ruby/Rails as my backend language.
After looking at the actual job listings for my region I realized that aside from one or two front end aberrations every single posting was for PHP or .Net
Now I'm questioning whether I should quit while I'm ahead and resign myself to learning C# (PHP can gtfo) or double down on what I've been reading in the hopes of getting a job anyway.
Alternatively I could focus on front end stuff and aim for the miniscule number of jobs for that.
Any advice?
Jean Dupont · 2017-08-19 14:10
>>2961
>>2962
I figured it out, I had to do it like this
bindsym XF86AudioRaiseVolume exec pactl -- set-sink-volume 0 +5% #increase sound volume
bindsym XF86AudioLowerVolume exec pactl -- set-sink-volume 0 -5% #decrease sound volume not sure why it works or why it didn't work before but it seems to be fine now.
array · 2017-08-21 01:38
>>2982
I want to inform you that this has helped me with StumpWM. I never bothered configuring my sound buttons, largely as I never bothered to learn the right commands; I'd been using alsamixer to control my volume for a long while now.
To anyone else using StumpWM, these are the configurations I used; my only sink is zero, according to pactl list sinks:
(define-key *top-map* (kbd "XF86AudioRaiseVolume") "exec pactl -- set-sink-volume 0 +10%")
(define-key *top-map* (kbd "XF86AudioLowerVolume") "exec pactl -- set-sink-volume 0 -10%")
(define-key *top-map* (kbd "XF86AudioMute") "exec pactl -- set-sink-mute 0 toggle")
Sipho Nkosi · 2017-08-21 20:40
>>2981
That's too weak - experience by creating some websites or modify existing ones - good ability to get with that is to predict an output (style, alignment...) without testing and tweaking by 110hours.
Wirth · 2017-08-21 20:43
Also learn both c# and php if you don't know anything else - Ruby is worth learning (check http://cuba.is)
And don't forget to deepen your JS understanding with Node, NWJS, CoffeScript...
John Titor · 2017-08-25 07:31
I'm not very experienced with version control.
I was working on a fork of a Github repo to solve a couple of sizable outstanding issues, intending to ask for a PR when I was done.
In the meantime the main repo has been abandoned by the sole maintainer. I however intend to keep working on the code.
Should I keep my fork as a Github fork or should I move everything to a new independent repo owned by myself?
Jane Doe · 2017-08-25 23:39
>>3069
>RCPT: XXXXXXXXX@XXXXXXXXXXXXXXXX.onion
>221 2.7.0 Error: I can break rules, too. Goodbye.
It's "RCPT TO:", rulebreaker.
Apoc · 2017-08-31 08:09
>>3060
Ask the maintainer to make you a contributor
Vasya Pupkin · 2017-09-02 06:43
>>3141
Thanks, but in the end I just made a new repo under a new project name.
Honestly, since it's a small code base I'm very tempted to straight up rewrite everything from scratch more to my taste.
Arisu Mizuki · 2017-09-04 21:28
Bear this with me.
I was doing this exercise from the C Primer so I made this program
/*prints age and how many days is that*/
#include <stdio.h>
main(){
int usrage, daysmult, result;
daysmult = 365;
result = usrage * daysmult;
printf("How old are you?\n type it here:");
scanf("%d", usrage);
printf ("You're %d years old and that is %d days", usrage, result);
return 0;
}
I compiled it but when it runs it doesn't show the line giving the results, the program simply closes after taking the imput.
Now this is the dumb part: I'm on cygwin and I've tried compiling it with gcc and cc but I have no idea what's the differences between them. In both cases I have tried to debug them, the debugger does print the result line but doesn't take the numbers I give to it and only return large negative numbers.
I'm stumped on what to do now.
The Oracle · 2017-09-04 23:46
>>3215
1. You are giving scanf the (uninitialized) value of usrage. Where do you expect it to store the age it reads in?
2. You are computing
>result = usrage * daysmult;
using an uninitialized usrage, before reading it in.
Dujour · 2017-09-05 00:05
>>3215
Try referencing (i. e. getting the memory adress) of usrage like this:
scanf("%d", &usrage);
Also, as >>3221 pointed out, you need to read the input before computing the result.
Moore · 2017-09-06 21:57
>>3221
>>3223
That worked but the program now delivers 0 days or 365 days depending on how I tell it to calculate the result
/*prints age and how many days is that*/
#include <stdio.h>
main(){
int usrage, daysmult, result;
daysmult = 365;
usrage = 1; /*I'm probably not initializing this properly*/
result = usrage * daysmult; /*I tried changing the order of these several times*/
printf("How old are you?\n type it here:");
scanf("%d", &usrage);
printf ("You're %d years old and that is %d days", usrage, result);
return 0;
} The only thing I haven't tried is changing the order of the lines but I think that doesn't mean much in C
The Phantom Phreak · 2017-09-07 08:23
>>3273
>The only thing I haven't tried is changing the order of the lines but I think that doesn't mean much in C
It means very much in C. The statements in any function in your program are executed from top to bottom. This is what you're telling your program to do currently:
1. Declare variables usrage, daysmult and result. Any variable that hasn't been initialized (assigned to for the first time) has undefined value. This means it could be anything.
2. Assign value 365 to daysmult. daysmult now stores the value 365.
3. Assign value 1 to usrage. usrage now stores the value 1.
3. Assign value usrage * daysmult to result. result now stores the value 1 * 365 because usrage stores the value 1 and daysmult stores the value 365.
4. printf a string "How old are you?\n type it here:".
5. scanf a decimal number and store the result in &usrage. I won't go over why you need an ampersand in there, just know that it has to do with pointers. You will understand why it's necessary when you learn about them. For now, just keep in mind that any variable that you want to set through scanf needs to be preceded with an ampersand.
6. printf the string "You're %d years old and that is %d days" where the first %d is the value of variable usrage, which depends on what you entered before, and the second %d is the value of variable result, which is 365 as it was assigned previously.
7. Return 0 signifying successful program termination on most systems.
As you can see, you compute result before you set usrage to the correct value. C is an imperative language and it does what you tell it to do in a strict order. It's very important to know that. If it's the first programming language you are learning I strongly recommend you go over the basics of imperative programming one more time and make sure you have a solid understanding.
Masami Eiri · 2017-09-07 21:06
>>3286
I see now.
I changed the order of the lines and initialized usrage after its scanned and now the program runs as intended. thank you <3
Yes, C is my first language but before picking it up I had not read anything about imperative programming in general, I dunno if I should be concerned about that now.
J.C. Denton · 2017-09-08 11:38
Is it outdated as of 2017 ? I think of buying it.
https://www.amazon.fr/Linux-Programming-Interface-System-Handbook/dp/1593272200/ref=cm_cr_arp_d_product_top?ie=UTF8
Lady Jessica · 2017-09-09 11:15
Any good reads like K&R or SICP?
Preferably something about software structure and how to handle memory effectively.
nil · 2017-09-09 20:01
Can I get some feedback on this small program? Im convinced there is a more efficient way to do this. Any criticism is welcomed.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int find_largest_rep(int a[], int s)
{
int max;
max = a[0];
for(int i = 0; i < s; i++)
if(max < a[i])
max = a[i];
for(int i = 0; i < s; i++)
if(max == a[i])
max = i;
return max;
}
int main(int argc, char **argv) {
long long int user_num;
int digit;
int rep_digit = -1;
char str[100];
const int MAX_SIZE = 15;
bool valid_input = false;
bool digit_repeated[MAX_SIZE] = {false};
int rep_storage[MAX_SIZE] = {0};
while(!valid_input){
printf("Enter a number: ");
scanf("%lli", &user_num);
sprintf(str, "%lli", user_num);
if(strlen(str) > 10){
printf("The number you entered is too large\n");
continue;
}
else
valid_input = true;
}
while(user_num > 0) {
digit = user_num % 10;
if(digit_repeated[digit]) {
rep_storage[digit] += 1;
rep_digit = digit;
}
digit_repeated[digit] = true;
user_num /= 10;
}
int max = find_largest_rep(rep_storage, MAX_SIZE);
if(rep_digit != -1) {
printf("Repeating digits: \n");
for(int i = 0; i < MAX_SIZE; i++)
if(rep_storage[i] != 0)
printf("%d ", i);
printf("\nMost repeated: %d\n", max);
printf("Repeated %d times.\n", rep_storage[max]+1);
}
else
printf("No repeating digits.\n");
return 0;
}
push · 2017-09-09 20:20
>>3360
Forgot to mention, its a program to find any repeating digits in a number, how many times they were repeated and if there are more than two different repeating digits, which repeated the most.
Ex:
input = 777332
output:
Repeating digits:
7
3
Most repeated: 7
Repeated 3 times.
John Peters, You Know, The Farmer · 2017-09-09 20:50
>>2664
Small question on how doubles are represented:
So if I'm understanding correctly, the reason the "double precision" numerical type in C/C++ can have a much more dynamic range of numbers than a long int is that the bytes to the left of the "dot" in the representation refer to a power of two, not a value itself. (There are 11 bits in the exponent, so you can get values between approximately 2^(2^(10)) and -2^(2^(10)) ) -- what's called a biased exponent
My question is, how do you get a number like 15 for the non-fractional part if you're only storing the exponent?
John Peters, You Know, The Farmer · 2017-09-09 21:21
>>3362
>>3360
Okay, so I tried doing what you specified (save for the "If there's more than two digits repeated, find the max. My program always finds the most-repeated digit, and I'm also a bit more lax on the error-checking than you were), but I tried decomposing the main() function into several, smaller functions.
I used the "getchar()" method, not scanf to input the number, and stored it in a character array, which I then used to find the relative frequency of each digit.
Again, not exactly to your specifications, but wanted to show another way of doing it.
#include <stdio.h>
#include <ctype.h>
#define MAX_DIGITS 10
#define MAX_LENGTH 500
/* Keeps track of how often each digit appears , ex: how many
times '5' appears is the value of the entry at digit_frequency[5]*/
int digit_frequency[MAX_DIGITS];
void print_freqs(int input[MAX_DIGITS]);
void return_freqs( char* num_str);
int get_max(void);
int main()
{
char num_str[MAX_LENGTH];
char curr_char;
int index = 0;
/* Store all the numbers input into an array */
while( (curr_char = getchar()) != '\n' && isdigit(curr_char))
{
num_str[index] = curr_char;
index++;
}
num_str[index] = '\0'; /* Null terminator for string */
printf("Number input: %s\n", num_str); /* Echo back the input */
return_freqs(num_str); /* Find the frequency of each number */
print_freqs(digit_frequency); /* Print the frequency table */
printf("Most-Repeated Digit: %d\n", get_max()); /* Print most-repeated digit*/
}
void return_freqs(char* num_str)
{
int index;
char c;
/* Skip the sign */
( (c = num_str[0]) == '+' || c == '-')
? index = 1
: index = 0;
for(; index != MAX_LENGTH && (c = num_str[index]) != '\0'; index++)
digit_frequency[c - '0']++;
}
int get_max(void)
{
int temp, ind, curr_max = 0, curr_max_value = 0;
for(ind = 0; ind < MAX_DIGITS; ind++)
if(curr_max_value < (temp = digit_frequency[ind]))
curr_max_value = temp, curr_max = ind;
return curr_max;
}
void print_freqs(int input[MAX_DIGITS])
{
char* separator = " ";
int index;
for(index = 0; index < MAX_DIGITS; index++)
{
printf("%s%d", separator, input[index]);
separator = ", ";
}
printf("\n");
}
The Oracle · 2017-09-09 23:56
>>3366
Very cool, thanks for doing this.
Using a character array was a good idea, you dont have to worry about validating input or integer overflow like I did. Storing data in an array is much more straightforward and probably more time/space efficient than what I tried to do, I see that now. I also need to start making better use of functions instead of dumping everything in main!
John Peters, You Know, The Farmer · 2017-09-10 00:21
>>3369
Yeah don't mention it! the hardest part for many people learning to program is seeing how easy a language's features can make a problem simpler!
If you haven't already, I very highly recommend using Kernigan and Ritchie's "The C Programming Language" as a way to learn good programming style while also learning neat little shortcuts like "++" and the conditional operator [code] ( expr ) ? e1 : e2
Agent Jones · 2017-09-10 21:21
How do i post C language code here?
I suppose it would be easier to explain what I don't understand coding the problem.
The Plague · 2017-09-10 22:09
>>3387
(code)(/code) but with [...] instead of (...)
Frank Garza · 2017-09-10 23:12
Hey lainons, could some of you give me a little help? I don't know why
#include <stdio.h>
#include <stdlib.h>
#include "funcoesDeBase.h"
int main()
{
float x = 45;
printf("3.141592 = %x\n\n", 3.141592);
x /= 0;
return 0;
}
Why does this code prints 1? Wasn't it supposed to print the value in hexadecimal?
And what happens with " x/= 0"?
Nameless · 2017-09-11 00:03
>>3390
#include "funcoesDeBase.h"
Maybe missing brackets?
Naomi Nascimento · 2017-09-11 00:21
>>3391
What do you mean by missing brackets?
This is supposed to be related to how computer do binary operations i think.
Koos van der Merwe · 2017-09-11 01:40
>>3393
You quoted funcoesDeBase.h when you should have put bracket, like this:
#include <funcoesDeBase.h>
Boole · 2017-09-11 03:00
>>3394
Please don't sound confident if you're not sure what you're talking about. You can use quotes around an include to include a local header. And if it doesn't find one in the current directory, it will function just like <> would have. See https://stackoverflow.com/questions/3162030/difference-between-angle-bracket-and-double-quotes-while-including-heade#3162067 .
>>3390
Looks like you're looking at some examples of undefined behavior.
First of all, %x is a specifier to print *unsigned ints* in hexadecimal. You're passing in a float. Looks like providing a value that doesn't match the type specifier isn't illegal, but causes undefined behavior. Refer to man 3 printf for details.
x /= 0 divides x by 0. As you probably know, division by 0 is not defined in the realm of math, and neither is it defined in the C spec. Try this:
printf("%f %f %d %d\n", 45.0 / 0, 0.0 / 0, 45.0 / 0, 45.0 / 0); On my machine, each thing printed is different.
Please remember to compile with -Wall and always pay attention to any warnings the compiler yells at you. Google them if you don't understand them.
Linda Lee · 2017-09-12 00:10
>>3399
T. Hanks, anon. You really helped me today.
Mentat · 2017-09-12 21:16
#include <stdio.h>
int main (void)
{
for (a=0;a<9001;a++)//this works
for (a=0;a<9001;a+1)//but this doesn't
return 0;
}
Why is that?
Guthrie · 2017-09-12 22:43
>>3446
a++ is short for a+=1 or a = a + 1 NOT a+1.
Turing · 2017-09-13 21:15
Anyone knows if this returns me "too much recursion" because javascript soykafs itself doing recursive proccesses or it is my code that keeps repeating itself and never returns anything? im trying to make the "cons" and "list" functions from lisp in javascript.
function cons(a,b){
var newCons={value:a,
rest:b};
return newCons;
}
function list(){
var a=arguments, size=arguments.length;
function helper(count){
if(count==size){
return cons(a[count],null);
}
else
return cons(a[count],helper(count++));
}
return helper(0);
}
Morpheus · 2017-09-13 21:45
Sup Lainons?
I'm a first semester C++ student working on a problem, and I was hoping for some help.
I have to write a program that finds the square root of a large number as efficiently as possible, using the limited knowledge that we have gathered in our first few weeks, and the standard namespace.
The way I am trying to solve the problem is by taking the input number (for instance, 144) and dividing it in half until I either get the desired result, or get less than the result. If the result is less, then it sets that as the floor (lowest known guess) and the ceiling (highest known guess) and averages them, trying again and again until it produces the correct result.
Unfortunately since I'm only a couple of weeks into coding, this is way over my head. I've written something that should work, but doesn't, and for the life of me I can't figure out why.
Any help or input would be very much appreciated, thanks in advance lainons.
https://pastebin.com/dqdpv1Gh
Netrunner · 2017-09-13 21:48
>>3464
count+1 instead of count++
Elliot Alderson · 2017-09-13 22:56
>>3467
thanks mate
Crash Override · 2017-09-13 23:18
>>3470
Didn't think to use the code wrap, whoops.
#include <iostream>
using namespace std;
int main()
{
long sqrrootin, y, floor, ceiling, fcavg;
cout << "Input number to find the square root of ";
cin >> sqrrootin;
ceiling = sqrrootin;
floor = 1;
fcavg = floor+ceiling/2;
y = fcavg;
cout << "Input detected, calculating answer now..." << endl;
while (y*y != sqrrootin){
y = y/2;
cout << "Y is now " << y << endl;
while (y*y < sqrrootin){
floor = y;
fcavg = floor+ceiling/2;
y=fcavg;
cout << "fcavg is " << fcavg << endl;
cout << "floor is now " << floor << endl;
}
while (y*y > sqrrootin){
ceiling = y;
fcavg = floor+ceiling/2;
y=fcavg;
cout << "fcavg is " << fcavg << endl;
cout << "ceiling is now " << ceiling << endl;
break;
}
}
cout << y << endl;
cout << "Success! " << y << " is the answer!" << endl;
}
Colmerauer · 2017-09-13 23:24
>>3470
>>3474
And here's the output. It continues indefinitely until canceled.
Input number to find the square root of Input detected, calculating answer now...
Y is now 2
fcavg is 6
floor is now 2
fcavg is 5
ceiling is now 6
Y is now 2
fcavg is 5
floor is now 2
fcavg is 4
ceiling is now 5
Y is now 2
fcavg is 4
floor is now 2
fcavg is 4
ceiling is now 4
Y is now 2
Faye Valentine · 2017-09-14 00:16
>>3474
- You are using integer quantities.
- Division takes precedence over addition.
- Dump your homebrew math and use Newton's method.
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.7
Frank Garza · 2017-09-14 02:04
>>3478
Oh my god thank you Lain. A couple hours later and it all just came together.
Frank Garza · 2017-09-15 02:46
>>2664
objA.setMessage("I'm object A");
objA.getMessage();
Tyrell Wellick · 2017-09-19 01:53
>>2664
makes sense to be honest
Y.T · 2017-09-19 03:08
>>3585
If I'm not mistaken, the files specified in require are relative to the current file, not the directory from which node is ran. Does something like ../../controllers/todoController.js work?
????? · 2017-09-19 04:24
Small question on Haskell syntax:
I'm trying to write a function that calculates the mean of a list. Because the list has to contain numbers, I'm assuming the list has to be of type
Num a=> [a]
And because means can be non-integer values, the result has to be a floating point number, so it can be a Fractional b => b
If I'm understanding this correctly, that means the type signature *should* be
getMean :: (Num a, Fractional b) => [a] -> b
And the function itself:
getMean list = (sum list) / fromIntegral (length list)
However, when I put the type signature in, I get the error in pic related.
If it helps, this is the type that ghci believes getMean should be:
getMean :: (Fractional a, Foldable t) => t a -> a Where am I going wrong?
byte · 2017-09-19 14:45
>>3588
Num a is not needed for length, which is length :: [a] -> Int, but you already know enough to include it because it's needed for sum :: Num a => [a] -> a. In the same way, division is (/) :: Fractional a => a -> a -> a, so you need Fractional a, and since Fractional is a Num, you can dump Num a. Since length returns an Int, and Int converts implicitly to Fractional, the length can be immediately used as the divisor. You get getMean :: Fractional a => [a] -> a and no need for b.
If you want getMean to work on lists of non-Fractional, you'll have to either convert the output of sum to Fractional to use the built-in division, or define your own division by an Int.
The error you get comes from the type checker inferring the return type of getMean to be Fractional a because of (/) :: Fractional a => a -> a -> a, but you asserting it should be b, independent from a.
Acid Burn · 2017-09-19 18:56
When I try to go to localhost:3000/todo I get the error "Cannot GET /todo". I've had a similar error to this before and I solved it with putting a app.get to the file, but I have an app.get/todo already so I'm not sure why this isn't working. There are pictures of all the relevant files. Does anyone know what I can do to fix this?
????? · 2017-09-19 22:45
>>3591
Okay... I think I get it now.
Hopefully the explicit types become easier as I go on doing exercises in Haskell. Thanks a lot, byte!
The Plague · 2017-09-21 19:40
Lains, I have been offered money (which is needed atm) to make an app for mapping a certain kind of shop within cities and allowing users to find their nearest shop, and to then offer those users discounts on certain things if they have this app.
I bullsoykafted a little as I've never made an app, didn't think it would go anywhere but suddenly this seems to be happening.
I know Java, JS very well, SQL ok, and that's about it.
1) What language/tool/framework would Lain recommend to make my first phone app? Ideally it would run on android and iPhone
2) How similar is it to Java, will I get super confused or is it quite a logical step further?
3) Am I in over my head and should I make my excuses and pass the project on to someone else, or is this doable for someone with no experience with front end?
Thanks in advance,
A Lain in Pain
word · 2017-09-21 21:38
Have you asked them if you could make a web-app instead?
You seem to be more experienced with that and doing map stuff in the browser using Google Maps or OpenStreetMap is rather nice IIRC.
Apart from that, it really doesn't sound all that hard. You can do most of the map stuff using third-party APIs or libraries and the discount stuff should be really easy.
Nell · 2017-09-21 22:14
>>3626
Yeah I've made web-apps that use leaflet.js before so that should be easy enough, I think it's that they want to use location services so that the phone user can navigate around rather than looking at a map of the whole city if that makes sense
That's good to know though. Haven't quite got the hang of frameworks yet though played around with Play Java a few months ago. Will just have to find a good phone framework.
The bottom line is just "ask them" I suppose, I just wanna know what I'm talking about before I do
藤原純一 · 2017-09-21 22:49
If you need it be be cross platform then just use a framework like phonegap/cordova/whatever it's called now. You can build the app with JS that way and it'll run on android and iOS. It won't run as well as a native app but it'll work. There's plugins for that framework to get things like location.
Alternatively you could just make it a web app and have the mobile app display the web app in a web view.
Boris Grishenko · 2017-09-22 01:52
Its as easy as soykaf to make a web app that uses Google Maps in Android. You just drag the map widget on to your app interface in the UI builder. Programming the app to find something in Google Maps is nothing more than a couple of lines of code. A lot of beginners Android books will have a simple app that does exactly what you describe, its a no brainer to make.
Hong, Guil Dong · 2017-09-22 11:34
>>3629
thanks lain
Does any Lainon have a relevant pdf?
Kay · 2017-09-23 07:13
Can somebody translate this code into Bash?
#!/usr/bin/sbcl --script
(with-open-file (charge-now "/sys/class/power_supply/BAT0/charge_now")
(with-open-file (charge-full "/sys/class/power_supply/BAT0/charge_full")
(format t "~3$ %"
(/ (read charge-now)
(read charge-full)
1/100 1.0))))
Cutter · 2017-09-23 09:21
Can I implement a python algorithm in a website?
stack · 2017-09-23 12:57
>>3676
Search for the following:
1. reading files in bash
2. performing arithmetic operations in bash
Hint: you don't have to convert output to number in bash
>>3679
Yes you can, just translate it to JS, or any language that compile to JS or has an interpreter written in JS or any JS compatible language. There is CoffeeScipt that has a syntax not so different from Python/Ruby.
Or you can implement it in the backend (look at Django and Flask)
Pulse · 2017-09-23 16:18
Im currently working on a image board for school
>created about 3 boards
>Now i want to get into the posting stuff with SQL(backend)+archiving etc.
and good reads on this or a tutorial of some kind that could help me with this
Meddler · 2017-09-24 07:12
>>3688
Are you writing an imageboard from scratch, or using an existing open source imageboard?
Lukasiewicz · 2017-09-24 08:13
>>3364
15 = 1111 in base 2 (or 0xF in base 16). Therefore, it is 1.111000...0 * 2^3 in binary scientific representation.
The floating-point representation encode the absolute value of the number (here it is already positive), and add a sign bit.
Note that, in general, the integral part of the binary scientific representation is 1 (very small numbers (such as 0) are exceptions called denormalized numbers). Therefore, there is no need to remember the integral part of the representation (so for 15, we'll only remember the .11100...0 part).
In double-precision format, the mantissa is 52 bits long, so it is 111000...0 (there are 49 zeroes).
The exponent is 3, but actually it is biased by 1023 (that is, 2^10-1, because the exponent is 11 bits long), so you have 1023+3=1026 = 100 0000 0010 in binary.
The sign is 0 (15 is positive).
So the double-precision encoding of 15 is
0 10000000010 111000000000000000000000000000000000 in binary
or 0x402E000000000000 in hexadecimal.
For single-precision (float), the mantissa is 23 bits long, the exponent is 8 bits long and the sign is still one bit,
so the mantissa of 15 is 111000...0 (with 20 zeroes).
The exponent is biased by 127 (that is, 2^7-1), so it is 127+3=130 = 1000 0010 in binary, and the sign is still 0.
So the single-precision encoding of 15 is
0 10000010 11100000000000000000000 in binary
or 0x41700000 in hexadecimal.
For the encoding of -15, replace the sign bit with 1.
Roy Batty · 2017-09-24 09:49
>>3697
scratch, but its mainly for practise so it doesnt need to be ready be a certain point or be perfect
Naomi Nascimento · 2017-09-24 22:57
>>3700
What language or languages are you writing it in? Any preference in RDBMS (MySQL, SQLite, MariaDB, etc.)?
Linda Lee · 2017-09-25 01:41
Im interested in low-level graphical programming in C. I want to be able to open a picture and modify the RGB pixels or change the contrast, etc. I would prefer to do this without a library (or minimal library support), can anyone recommend any resources to learn this? Most C books briefly cover bitwise operations as it is, let alone bitmapped graphics. If anyone could point me in the right direction, I would be most appreciative.
Neuromancer · 2017-09-25 01:46
>>3720
I forgot to mention, I use Linux and have had trouble finding non-windows specific C graphics tutorials so any portable or Linux implementations are preferred.n
藤原純一 · 2017-09-25 05:44
>>3720
>>3721
If you want to do image manipulation without a library, I think your best bet is to learn the basics of BMP file specification (https://en.wikipedia.org/wiki/BMP_file_format). Don't learn about all DIB headers, the BITMAPINFOHEADER is probably the only one you will need, because it's chosen by GIMP when saving 24-bit BMP images (but remember to check "do not save colorspace information" in compatibility options, because it will use a different, more complicated DIB header otherwise). Here's a quick rundown about how to read binary files. The function you'd use the most is fread:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Open the file for reading in binary mode (that's what "r" and "b" mean).
FILE * fp = fopen("/path/to/your/binary/file.bin", "rb");
// Read one DWORD (four bytes). The arguments to fread are as follows: pointer to the destination,
// size of a single item, the number of items to read, and the file to read from. It returns the number
// of elements read, so if it's different than one in our case, then something went wrong i.e either we
// reached the end of file, or some other error occurred. feof will return true in the former case, and
// ferror in the latter.
unsigned int x;
if(fread(&x, sizeof(x), 1, fp) != 1) {
if(ferror(fp)) {
perror("fread");
} else {
fprintf(stderr, "reached the end of the file prematurely\n");
}
// Remember to close the file.
fclose(fp);
exit(EXIT_FAILURE);
}
// Now x is whatever was in the first four bytes of you file. Remember that the position indicator of the
// file has advanced, this means the you will get the next DWORD the next time you use fread in the same way.
printf("the first DWORD in the file is %#X\n", x);
// Remember to close the file.
fclose(fp);
return EXIT_SUCCESS;
} When processing a BMP file you will most likely read the first few bytes to check if it's indeed BMP, read a few more to check if the size of the file matches with what's recorded inside (the file could be corrupted otherwise), then check if the DIB header has the size you expect (40 in case of BITMAPINFOHEADER) and read the image's dimensions in order to be able to process it as a 2D object (also make sure that there is no compression, there are fields for that as well). Then read the array containing the RGB values and change them to your liking, finally open another file and write all of the information you read there, then write your new array of RGB values. If you have problems with something, feel free to ask for further help
Armitage · 2017-09-25 06:10
>>3718
SQLite would be best, writing the website in PHP,JS,html and some ruby
Emmanuel · 2017-09-25 21:42
I have a dumb problem
I have this program that is supposed to take a number and return its ascii value, Its really simple but I think my problem is that I don't know how to properly move the value around, just see:
/*takes number input and gives back the respective ascii character*/
#include <stdio.h>
int main(void)
{
int innumber;
char outletter;
printf ("type a number beatween 32 and 126 and get a character: ");
scanf ("%d", innumber);
innumber == outletter; /*I've also tried this line with only one equal sign*/
printf ("that is %c in ascii", outletter);
return 0;
} The program compiles and runs but after the innumber == outletter; it closes without giving back the desired output so I'm sure that sole line is my problem.
What do I do now?
Knuth · 2017-09-25 22:03
>>3723
Hey, thanks for the commented example. This is exactly what Im looking to do, thanks for pointing me in the right direction.
>>3742
With scanf, you want to store the user-given number in the memory address of innumber, so it should look like this:
scanf("%d", &innumber);
the & is the address of operator.
Second, == will return either 0 or some undefined behavior because outletter has not been initialized yet so comparing it with innumber will yield weird results. You are on the right track, you can assign ints to chars without casting so you dont even really need a char variable.
If innumber is 65 for instance,
printf("%c\n", innumber);
will print 'A', no casting necessary.
but if you want to assign outletter to innumber, it needs to be the lvalue in an assignment statement:
outletter = innumber;
printf("%c\n", outletter);
Undisclosed · 2017-09-26 19:25
>>3743
It works now, thanks you.
I always forget the '&' when using scanf and I need to keep in mind the lvalue and rvalue.
>so you dont even really need a char variable.
How would that work? I mean what would the program look like without a char variable?
Void · 2017-09-26 21:28
>>3742
>printf ("that is %c in ascii", outletter);
On this line, `%c` converts a number like 97 into the a character like "a". So use innumber.
printf ("that is %c in ascii", innumber);
Some extra things to note.
In the C programming language, the datatype char is actually a number. The only difference between char and int is that int can usually hold bigger numbers.
Additionally, when you write a character in single quotes like 'a', the C compiler automatically converts that into the corresponding ASCII code like 97.
These are all equivalent.
char my_letter1 = 'a';
char my_letter2 = 97;
int my_letter3 = 97;
int my_letter4 = 'a';
Roger Pollack · 2017-09-27 17:49
What is a good book/course where you actually build something and learn on the go starting from beginner?
Undisclosed · 2017-09-27 18:01
>>3791
you could start with the introduction to computer science course from Udacity, it introduces you to python while building a web crawler.
In my opinion the CS50 courses on yt are also very good for starting out.
Unnamed · 2017-09-30 05:14
Someone in #lainchan showed this example of Lisp behavior being a reason they think it's "soykaf".
> (define x 4)
> (define (f y) (+ y x))
> (f 3)
7
> (define x 5)
> (f 3)
8
Why would you be against this? This seems like the type of behavior you'd want from using a global variable. If you didn't want F to be modified, shouldn't you use a LET for data?
Acid Burn · 2017-09-30 09:31
>>3848
Say I have my own code, which:
1. define's a variable called x, which I use for my own purposes
2. calls to function y, which is in an external module you have written for me
Function y will not act the way I anticipate. To figure out why, I will have to read the entire source code for the module that function y lives in. In doing so, I will discover that function y depends on a define'd variable named "x", and that by using my own define'd variable named "x" I am disturbing y's behavior.
The solution will be to rename my own define'd variable to something that is not "x" and is also not used by any functions my code calls.
This is called dynamic code, and it does suck. The behavior of external code should not depend on the names I use in my code.
St. IGNUcius · 2017-09-30 09:38
>>3851
Whoops, it's actually called dynamic scope.
Also,
> This seems like the type of behavior you'd want from using a global variable.
This is the type of behavior you would expect from a global variable, which is why LISP was written this way. However, it is a real pain to keep track of all of the already-existing global variables that are being used - or might be used - by other code when your code is running.
Because any two programs could be running on the same computer, you would have to examine every program ever written before yours that is compatible with the same systems that your code is compatible with, and avoid define-ing any variables using the names that these programs already define.
Elliot Alderson · 2017-09-30 09:51
>>3848
Here's another example of why dynamic scope is like kicking dead whales down the beach.
(let [(x 0)]
(let [(f (lambda (y) (* y x)))]
(let [(x 1)]
(f 1))))
In a dynamically scoped environment, the result will be 1, because the "x" in function f will be the "x" defined in the last let statement.
In a lexically scoped environment, the result will be 0, because the value of "x" that existed in f's scope where it is defined is 0.
Lord Nikon · 2017-09-30 15:59
>>3854
Are there any Lisps with dynamically scoped let left nowadays though?
>>3851
>>3852
Modern Lisp dialects have modules/packages to remedy exactly that. It's possible to use them in Clojure, Common Lisp, and descendants of Scheme like Racket or Guille, however they may be called. x from a different package is not considered the same symbol you define in yours. Dynamic scoping is harmful in the way you described only in dialects where everything gets lumped into a common namespace.
null · 2017-10-02 13:31
How do I get into networks/securty? Ive heard python can be used for this and it would be very interested.
Any intro books/courses?
XERXES · 2017-10-02 19:25
>>3977
You could try Black Hat Python and Gray Hat Python.
They are more from the perspective of security professionals getting into programming than the other way around though. Python is an amateurish programming language after all.
Unknown · 2017-10-03 18:57
>>3992
I know what you mean, I started with C/C++ but I love how python is so concise and fast + its so universal.
Nameless · 2017-10-06 20:01
>holidays
>learned a lot about python
What would be a 1-2 week program that is useful and teaches me stuff? have been thinking about some auto writer for a website with selenium or maybe some script for data analysis but I cant make up my mind.Maybe I should also just start something
Emmanuel · 2017-10-07 04:02
Forgive me if this is dumb
/*takes name and sur name and prints it in the opposite order*/
#include <stdio.h>
int main(void)
{
char nme, snme;
printf ("Please type your name & surname:");
scanf ("s, s", &nme, &snme);
printf ("Hello %c %c", snme, nme);
return 0;
} I'm having trouble with the scan function and how to make it take a name properly. So far trying different variations it only prints 'hello' without the input names.
Wirth · 2017-10-07 05:19
So I've got this super fuarrrked up situation in a C++ class.
My prof wants me to use overloaded output to display a stack.
friend ostream & operator << (ostream & out, const CharStack & CS)
{
while(!CS.myCharacters.empty())
{
out << CS.myCharacters.top();
CS.myCharacters.pop();
}
}
Now in a perfect world this code would just straight up work and I could cout << CharStack (custom class) << endl; with no problem. That is not the case. Upon compiling I get pic related, which makes me believe that I can't just edit a const stack here and not edit the whole thing (unless I'm misunderstanding friend functions)
This has been pissing me off for a few hours, help!
Demeere · 2017-10-07 06:07
>>4136
ok so the `char` type is for literally one letter. If you want strings you have to declare a char array.
Also to read in a string from scanf you need to use %s, so change "s, s" to "%s, %s" in your scanf call
To print a string you also use %s, so change %c to %s (%c is for chars, remember a char is only one character at a time)
This is what it would look like
/*takes name and sur name and prints it in the opposite order*/
#include <stdio.h>
int main(void) {
char nme[100];
char snme[100];
printf ("Please type your name & surname:");
scanf ("%s, %s", &nme, &snme);
printf ("Hello %s %s", snme, nme);
}
That will crash if you enter more than 100 characters for either name, (or do worse than crash). You'll learn how to dynamically allocate strings and how to read strings safely later I hope.
Splicer · 2017-10-07 06:09
>>4140
So it looks like the const qualifier being discarded is the only error. If you compile with `-fpermissive` does it compile, and work the way you want it to? If it compiles but executes wrong, you probably have a bigger design issue than just a const
Technician · 2017-10-07 06:13
>>4145
Will try compiling. It probably will raise an error there since I'm popping elements from a stack embedded within a class. I need to read more on what the const qualifier does in that particular position. Is it just something to reeforce private data and keep it from being manipulated?
Spooky · 2017-10-07 06:19
>>4146
Doubleposting here.
It did compile with -fpermissive but I just segfaulted when that happened, figured something to that degree might happen.
Anonymous · 2017-10-07 06:38
And tripleposting.
Solved the problem. Now it's coming out backwards, but I just have to use a reverse function to get this going.
friend ostream & operator << (ostream & out, const CharStack & CS)
{
stack<char> tmp = CS.myCharacters;
while(!tmp.empty())
{
out << tmp.top();
tmp.pop();
}
return out;
}
fsociety · 2017-10-07 09:00
>>4148
> it's coming out backwards
Stacks are supposed to be First In Last Out. Think of a stack of plates, you need to remove all the plates on top to get to the first plate again.
>I need to read more on what the const qualifier does in that particular position. Is it just something to reeforce private data and keep it from being manipulated?
const comes from C so it has nothing to do with classes. When a variable is marked const it means the compiler will prevent you from changing it.
int a = 1;
a = 5; // ok
const int b = 1;
b = 5; // error, because b is const
William Holtzer · 2017-10-07 15:17
>>4152
C++ has done a lot more with const than C ever did, especially if you look at some of the new editions like std::experimental::propagate_const and the templates that can be used to modify the const-ness of a variable (const_cast included). Also, you can put const on a method signature to make it so that it can't modify the object it's called on, letting compilers generate much more efficient code.
I can't tell you more about what's up with the stack, but I can tell you that const has a lot to do with classes now.
Vasya Pupkin · 2017-10-07 15:27
I'm trying to get into GUI programming in lua as a complete novice baby begin. How do i do this
Random · 2017-10-07 16:39
>>4166
Interesting. I just wasn't applying the idea behind const in a broad enough sense. But using it to lock a variable from being edited is pretty cool.
Cowboy · 2017-10-07 19:33
>>4144
The confusion around the %c and %s probably happen between the different variations I tried on the scanf line and by focusing on that line i forgot to modify the second printf.
My book still hasn't taught me about arrays, it probably didn't expect me to do this exercise like this, I should re read the chapter and be concerned with arrays when its time
Thank you <3
Drifter · 2017-10-11 17:30
if I want to land a job as a data scientist what would be best to have on my CV?
>many projects on github,experiences I should gather, which libraries I should be confident in(except matplotlib) etc.
Jet Black · 2017-10-12 18:10
(ignore this line of text, just posting this because i posted this with a typo, deleted the post, wanted to post it again without the typo and the flood prevention system didn't allow me to post this)
what does it mean "other is undefined" in javascript? i was making a small game in javascript, solving specifically this problem of this book: http://eloquentjavascript.net/07_elife.html (scroll all the way down to the exercise called "artificial stupidity") and i made some methods that allow the critters to examine other critter's properties in the world, but when i run a turn the program just returns "other is undefined" even though i haven't defined a variable called "other" or something similar, these are my methods and critters:
.
function aroundObject(dir,View){
var directions2 = [], dir1 = dirPlus(dir,1), dir2 = dirPlus(dir,-1);
if(View.look(dir1) == " ")
directions2.push(dir1);
if(View.look(dir2) == " ")
directions2.push(dir2);
if(directions.length > 0)
return directions2[0];
}
PlantEater.prototype.act = function(View){
var space = View.find(" ");
if(this.energy > 60 && space && this.repCounter > 20){
this.repCounter = 0;
return {type:"reproduce", direction:space};
}
var plant = View.find("*");
var plantProps = View.examine(plant);
var plantEnergy = plantProps.energy;
if(plantEnergy > 10 || PlantEater.energy < plantEnergy){
this.repCounter++;
return {type:"eat", direction:plant};
}
var roundPlant = aroundObject(plant, View);
if(roundPlant){
this.repCounter++;
return {type:"move", direction:roundPlant};
}
if(space){
this.repCounter++;
return {type:"move", direction:roundPlant};
}
}
View.prototype.examine = function(dir){
var target = this.vector.plus(directions[dir]);
if (this.world.grid.isInside(target))
return this.world.grid.get(target);
};
the line of code that is returning the "other are undefined" is either :
var plantProps =View.examine(plant);
or
var plantEnergy = plantProps.energy;
(ignore this line of text, just posting this because i posted this with a typo, deleted the post, wanted to post it again without the typo and the flood prevention system didn't allow me to post this)
Nell · 2017-10-13 00:25
>>4329
1. How did you get an error without a line number?
2. You forgot to check
>var plant = View.find("*");
for null, i.e. no adjacent plants. You then give null to examine, look up null in directions, and give the undefined result to plus, whose parameter is called other.
Eldon Tyrell · 2017-10-13 03:37
>>4329
To let you know for the future, the flood prevention system only makes you wait a few minutes, so you could have simply waited a little before reposting it with corrections.
Nameless · 2017-10-13 23:19
>>4342
thank you a lot, i managed to fix the problem, i didn 't know that if you try to access a property of a null or undefined value, js would throw you an error and the reason i didn't knew that i because i assumed that when you try to do that, it would just throw you null or undefined, similarly to functions that return nothing (just like the examine method at the end of this post which returns undefined if dir doesn't exist).
answering to your first question, i ran this piece of code in the console:
for (var i = 0; i < 25; i++) {
valley.turn();
console.log(valley.toString());
}
this is my final solution if you are interested in giving it a look:
function PlantEater() {
this.energy = 20;
this.repCounter = 0;
this.health = 4;
}
function aroundObject(dir,View){
var directions2 = [], dir1 = dirPlus(dir,1), dir2 = dirPlus(dir,-1);
if(View.look(dir1) == " ")
directions2.push(dir1);
if(View.look(dir2) == " ")
directions2.push(dir2);
if(directions2.length > 0)
return directions2[0];
}
PlantEater.prototype.act = function(View){
var space = View.find(" ");
if(this.energy > 60 && space && this.repCounter > 20){
this.repCounter = 0;
return {type:"reproduce", direction:space};
}
var plant = View.find("*");
var plantProps = View.examine(plant);
if(plantProps){
var plantEnergy = plantProps.energy;
if(plantEnergy > 8 || PlantEater.energy < plantEnergy){
this.repCounter++;
return {type:"eat", direction: plant};
}
}
var roundPlant = aroundObject(plant,View);
if(roundPlant){
this.repCounter++;
return {type:"move", direction: roundPlant};
}
if(space){
this.repCounter++;
return {type:"move", direction: space};
}
}
var valley = new LifelikeWorld(
["############################",
"##### ######",
"## ##",
"# ## ##",
"# *O ## #",
"# *** ## #",
"# * ## #",
"# # #",
"# # #",
"# ## #",
"## ### ###",
"############################"],
{"#": Wall,
"O": PlantEater,
"*": Plant}
);
View.prototype.examine = function(dir){
if (dir){
var target = this.vector.plus(directions[dir]);
if (this.world.grid.isInside(target))
return this.world.grid.get(target);
}
};
Hopper · 2017-10-14 13:41
>>4352
>if you are interested in giving it a look
Delaying null detection and null proofing downstream methods will prove to be an unproductive approach as your code size increases. You will be better off and have cleaner control flow by handling the null case immediately after the invocation of the method whose contract naturally includes returning null, in this case the find method.
over · 2017-10-15 16:51
>>4361
Alright, i think i fixed it, added the code for the last exercise if you want to give it a look like last one:
actionTypes.attack = function(critter, vector, action) {
var dest = this.checkDestination(action, vector);
var atDest = dest != null && this.grid.get(dest);
if (!atDest || atDest.health == null)
return false;
atDest.health--;
critter.energy--;
return true;
}
function PlantEater() {
this.energy = 20;
this.repCounter = 0;
this.health = 4;
}
function Predator(){
this.energy=35;
this.repCounter=0;
this.health=4;
}
function aroundObject(dir,View){
var directions2 = [], dir1 = dirPlus(dir,1), dir2 = dirPlus(dir,-1);
if(View.look(dir1) == " ")
directions2.push(dir1);
if(View.look(dir2) == " ")
directions2.push(dir2);
if(directions2.length > 0)
return directions2[0];
}
PlantEater.prototype.act = function(View){
var space = View.find(" ");
if(this.energy > 60 && space && this.repCounter > 15){
this.repCounter = 0;
return {type:"reproduce", direction:space};
}
var plant = View.find("*");
if(plant){
var plantEnergy = View.examine(plant).energy;
if(plantEnergy > 4 || this.energy < plantEnergy){
this.repCounter++;
return {type:"eat", direction: plant};
}
}
var roundPlant = aroundObject(plant,View);
if(roundPlant){
this.repCounter++;
return {type:"move", direction: roundPlant};
}
if(space){
this.repCounter++;
return {type:"move", direction: space};
}
}
Predator.prototype.act = function(View){
var space=View.find(" ");
if (this.energy > 60 && space && this.repCounter > 20){
this.repCounter = 0;
return {type:"reproduce", direction:space};
}
var prey=View.find("O");
if(prey){
var preyProps=View.examine(prey);
var preyEnergy=preyProps.energy, preyHealth=preyProps.health;
if(preyHealth > 1 && ((preyEnergy - preyHealth) > 2)){
this.repCounter++;
return {type:"attack", direction:prey};
}
if((this.energy < preyEnergy) || preyEnergy > 7){//preyHealth<=1 is redundant
this.repCounter++;
return {type:"eat", direction: prey};
}
var roundPrey = aroundObject(prey, View);
if(roundPrey){
this.repCounter++;
return {type:"move", direction: roundPrey};
}
}
if(space){
this.repCounter++;
return {type:"move", direction: space};
}
}
var valley = new LifelikeWorld(
["####################################################",
"# #### **** ###",
"# * @ ## ######## OO ##",
"# * ## O O **** *#",
"# ##* ########## *#",
"# ##*** * **** **#",
"#* ** # * *** ######### **#",
"#* ** # * # * **#",
"# ## # O # *** ######",
"#* @ # # * O # #",
"#* # ###### ** #",
"### **** *** ** #",
"# O @ O #",
"# * ## ## ## ## ### * #",
"# ** # * ##### O #",
"## ** O O # # *** *** ### ** #",
"### # ***** ****#",
"####################################################"],
{"#": Wall,
"O": PlantEater,
"*": Plant,
"@": Predator}
);
Torvalds · 2017-10-17 14:50
is there a book like SICP for a more modern language? I dont think LISP has any great values nowadays or should I read it to get the lower level concepts(which comes with LISP)?
Joey · 2017-10-17 17:11
>>4397
>I dont think LISP has any great values nowadays
wrong
Dr. X · 2017-10-17 18:15
>>4397
I don't intend to break rule 3 and insult you, but I've observed that people who stylize Lisp as "LISP" tend to not have a mature opinion. If you've never tried Lisp, why do you have an opinion?
https://lainchan.org/λ/res/3.html
Lain Iwakura · 2017-10-17 20:16
>>4397
Watered down SICP for Python 3:
http://www.composingprograms.com/
push · 2017-10-18 19:26
Currently taking a computer engineering course that goes over the basics of assembly, usage of logic gates, etc. We're going to be using 32-bit x86 assembly and the university uses Windows; do any of you have any recommendations on good and actually targeted at beginners resources for this?
roll · 2017-10-19 08:14
>>4428
>e-book thread
>The_Elements_of_Computing_Systems__Building_a_Modern_Computer_from_First_Principles.pdf
Hope this helps
藤原純一 · 2017-10-20 02:02
>>4449
>Lisp had a garbage collector in the 60s
even in the 80s Lisp was not able to run on conventional computer hardware and they had to design 'Lisp Machines' with enough memory to run a garbage collector. The garbage collector on those old Lisps were so slow that they just had to turn it off and let it accumulate garbage while they were working and then they would let the garbage collector run all night because thats how long it would take
>Reference counting and garbage collection are forms of automatic memory management but they are very distinct concepts.
they arent distict concepts, automatic reference counting is a type of garbage collection and has been used in scripting language implementations
>>4464
I was referring to personal computer operating systems of the 70s and 80s, ie C64, Atari 800, IBM/MSDOS, Apple II, all of which were some hybrid of CP/M. Unix eventually caught on and took over the mainframe market but before that most mainframe systems were batch loader systems that ran a single program at at time.
Zero Cool · 2017-10-20 09:18
>>4465
>even in the 80s Lisp was not able to run on conventional computer hardware and they had to design 'Lisp Machines' with enough memory to run a garbage collector.
Wrong.
>1988
>Robby had two Motorola 68020 processors running vxWorks, each with (if memory serves) 8 MB of RAM.
>Both Robby and Tooth were programmed using Lisp. On Robby we actually ran Lisp on-board.
http://www.flownet.com/gat/jpl-lisp.html
>automatic reference counting is a type of garbage collection·
Fine. I was wrong about that. To my C++ trained brain, smart pointers and garbage collection could not be more different but reference counting dos seem to be considered a subset of garbage collection by most people.
>I was referring to personal computer operating systems of the 70s and 80s, ie C64, Atari 800, IBM/MSDOS, Apple II, all of which were some hybrid of CP/M. Unix eventually caught on and took over the mainframe market but before that most mainframe systems were batch loader systems that ran a single program at at time.
Before Unix, C didn't exist so this is completely irrelevant to your C bashing.
hash table · 2017-10-20 09:35
>>4472
>1988
>Robby had two Motorola 68020 processors running vxWorks, each with (if memory serves) 8 MB of RAM.
>Both Robby and Tooth were programmed using Lisp. On Robby we actually ran Lisp on-board.
I should have said late 70s, early 80s. When the 386 came out it instantly made Lisp Machines obsolete and created the AI winter as it gave access to Lisp to anyone and everyone could see that the promises about what Lisp would do for AI was 'emporor's new clothes'
Case · 2017-10-20 11:28
>im rather new
Is there a archive for this board?Where can I find it?
hash table · 2017-10-20 12:25
>>4465
>>4475
It might be worth reading some history behind these systems instead of just making it up. In a thread intended for beginners at that.
Lisp was first implemented on the IBM 704 in the early 60s, shortly after McCarthy's paper on symbolic computation. That's a 1954 machine with a whopping 4k words of memory.
It may not have been practical to run Lisp on conventional hardware at the time, but it was certainly possible and there were many implementations. Your comment about garbage collection `running all night' is completely absurd, there's nothing that makes it unique from any other computational process, nor is it especially time-consuming. In cases where GC is disabled it's typically to remove an element of unpredictability in the performance of a real-time system.
The Lisp Machines made that a non-concern by implementing GC in hardware using 36bit words and data tagging.
Those Lisp Machines become obsolete, more than any other reason, simply because people stopped buying them. Symbolics's heyday was in the mid-80s when money from the Strategic Defence Initiative was flowing thick and fast. A lot of sales came from companies interested in AI and looking to blow a lot of cash quickly, lest they have their funding reduced next quarter, and at $70,000 - $150,000 each, a Lisp Machine was a great way to do it. Once the funding dried up there were not many people left who could justify that price for a single-user machine, especially since more general-purpose computers had become significantly more powerful in the interim.
As for AI, while it may not have given us robotic assistants (nor will the current AI spring), it is useful for solving specific kinds of otherwise difficult problems, and in those areas it bore fruit. In fact, all of DARPA's decades worth of funding was repaid by a single piece of software. Please note, included in categories at the bottom of the article is `Common Lisp Software'.
https://en.wikipedia.org/wiki/Dynamic_Analysis_and_Replanning_Tool
cdr · 2017-10-20 15:19
>>I was referring to personal computer operating systems of the 70s and 80s, ie C64, Atari 800, IBM/MSDOS, Apple II, all of which were some hybrid of CP/M. Unix eventually caught on and took over the mainframe market but before that most mainframe systems were batch loader systems that ran a single program at at time.
yes, but your retarded assertion what that C has manual memory management and pointers because its just barely not assembly because it was made for operating systems that just loaded programs so it had to just control the system directly.
Thats obviously wrong. C is "low level" because its simple. Its a system that offers convenient abstractions and facilities for structured programming that youd have to do manually using the assembler, but in a simple way thats mostly just derived from the way the computer works, rather than trying to present a model of computation for you to interact with instead of the actual physical computer. Or thats how Id explain what it seems to me its ethos is, based on what its designers said about it.
Either way its just obviously stupid to say that its not GC'd and more abstracted because it was made for controlling the hardware directly on a non-multitasking OS that doesnt present any sort of interface.
Hacker · 2017-10-20 15:55
I've not yet participated in this C discussion, but I feel it necessary to stop bystanding.
The C language is certainly not how a computer actually works, even though the C language generally has a code density similar to an assembler language.
The C language not only hides stack operations that lead to local variables, but is incapable of taking advantage of any machine instructions that aren't part of a lowest common denominator without special compiler function support or a compiler that can detect when the instruction sequence would be valid, which is often done with looking for extremely specific textual patterns, as the C language makes it difficult to prove certain important characteristics of programs. In particular, I'm aware this is done for the Intel popcnt instruction.
As has been mentioned, garbage collection is older than C and ran on machines with less memory than C. The C language lacks decent metaprogramming, which is part of why such large compilers are used to optimize it. The C language is insufficient to communicate programmer intent to a level necessary for optimizations without deep compiler introspection. The Forth language, despite typically being based around a virtual stack machine, is closer to the hardware than C is, as detailed control of memory layout and whatnot is generally permitted and metaprogramming allows optimizations without a complex compiler.
Undefined behavior makes it easier in many ways to write an assembler program than a C program, as the assembler is rather simple and predictable, for most assemblers. Even experienced C developers, such as Linus Torvalds, often inspect assembler output from GCC and other compilers in order to make certain that the compiler isn't removing important code fragments, such as security checks, which happens often enough to cause real concern.
For a detailed discussion of garbage collection and also how this differs from automatic memory management, see this thread; remember that this thread isn't a C thread, so please don't bring this discussion there: >>914
Guthrie · 2017-10-20 20:45
>>4479
>C is "low level" because its simple. Its a system that offers convenient abstractions and facilities for structured programming that youd have to do manually using the assembler, but in a simple way thats mostly just derived from the way the computer works, rather than trying to present a model of computation for you to interact with instead of the actual physical computer.
What youre saying is sort of half true. C is a simple language that only has the most basic of syntax features. This is why it is the defacto language for implementing compilers, because more complex languages with higher abstracted syntax features will become a hidden part of the language it is implementing. But there are other languages that are as simple as C such as Fortran, but Fortran lacks the weak typing of C so its difficult to manipulate bits. Where you are wrong is saying that C offers the control of assembly which it does not. C is not any closer to assembly than any other compiled language, you can only give hints to a C compiler which a well optimized C compiler will usually always ignore.
dictionary · 2017-10-21 00:51
>>4486
>"C is not any closer to assembly than any other compiled language, you can only give hints to a C compiler which a well optimized C compiler will usually always ignore."
That's true, i didn't believe it until i learnt a bit of x86-64 asm and then read what gcc generates from c program. C/c++ compilers are really a thing, they're almost scary because i don't think i could write better asm even if i study two years
Dog./0r · 2017-10-21 19:10
Are there any books on the subject of file sharing? I'm particularly interested in the BitTorrent protocol and how metadata is stored on .torrent files
Koos van der Merwe · 2017-10-21 20:12
>>4489
read the spec:
http://www.bittorrent.org/beps/bep_0003.html
HELIOS · 2017-10-21 23:18
>>4486
I didnt say that C gives you the same control as assembly. Thats not what I meant by 'derived from the way the computer works' or . Perhaps I put it poorly. I was hopining calling it a 'system' and saying how it abstracted things youd do by hand in assembly would frame it so it would be clear I wasnt saying 'c is the lowest level language ever its just barely not writing binary xDD'.
Linda Lee · 2017-10-22 05:08
>>4481
>Undefined behavior makes it easier in many ways to write an assembler program than a C program, as the assembler is rather simple and predictable, for most assemblers. Even experienced C developers, such as Linus Torvalds, often inspect assembler output from GCC and other compilers in order to make certain that the compiler isn't removing important code fragments, such as security checks, which happens often enough to cause real concern.
Holy fuarrrking soykaf, it's true!
https://www.tripwire.com/state-of-security/vulnerability-management/compiler-undermining-secure-coding/
Does Rust avoid this problem? If they design their compiler with safety in mind, then it won't optimize away their safety designs... right? At least in theory?
Elliot Alderson · 2017-10-22 09:35
>>4497
>Does Rust avoid this problem? If they design their compiler with safety in mind, then it won't optimize away their safety designs... right?
C is unsafe because of lack of type checking, bounds checking and unsafe pointers. Rust has none of that and so its not something that gets optimized away.
Liet Kynes · 2017-10-22 15:31
>>4499
Try to read the post you are responding to first.
Agent Richard Gill · 2017-10-22 16:45
If you're interested: add letanguy4 on Telegram and say that you want to join the group.
Of course discussions would be free, without underlying goal.
We could have projects or something.
Also I'm thinking to make a small server with some services available for the said group.
Leto Atreides I · 2017-10-22 18:27
>>4504
We have #programming on our IRC server, irc.lainchan.org:6697
https://lainchan.org/irc.html
Aristóteles Amadópulus · 2017-10-22 18:34
>>4507
That is not the goal - I won't set or discuss a project with Appleman, lisp or barrucadu for example.
Not that I dislike them don't misunderstand me.
That's for the fun of it. It doesn't aim to replace #programming. Those two are different stuff.
Guthrie · 2017-10-22 18:42
>>4508
#programming has "free" discussion in regards to programming topics, so what point is there for your telegram group to exist? Not that there's a problem, but I find it odd not to centralize /lambda/ lainons around one IM service. Is #programming not for fun? Haha.
Nobody important · 2017-10-22 18:49
>>4509
Well lambda's users stay centralised over #programming - Do you really think someone would move out ?
Incognito · 2017-10-22 19:03
>>4497
For clarity, I'm the one you replied to.
>Does Rust avoid this problem? If they design their compiler with safety in mind, then it won't optimize away their safety designs... right? At least in theory?
I wouldn't know, but Rust is a bad language for many reasons.
As of the last C standard I checked, there's around two hundred cases of undefined behavior, which invocation in any form leads to a shattering of the entire program. This is why C is unsuitable and why it's not "one step above assembler" or whatever nonsense you may read. It's easier to write an assembler language program in many ways, as machine codes tend to be rigidly specified and your program won't be yanked out from underneath you.
Bobby Newmark · 2017-10-23 11:03
>>4511
>As of the last C standard I checked, there's around two hundred cases of undefined behavior, which invocation in any form leads to a shattering of the entire program.
I think you are overhyping this a bit.
For one thing UB does not "shatter" your entire program, compilers generally do something sensible. The problem is that whatever they do is not necessarily predictable at the time of writing the code.
Second of all, most C programs don't explicitly rely on UB on their happy paths. UB usually manifests itself in error conditions and corner cases.
Ideally all code would be have formal proofs and 100% test coverage and have zero bugs but in reality everything is a trade off.
From what I understand Rust does not have UB the same way C does but it still has the `unsafe` keyword because some types of problems like low level pointer manipulation cannot be guaranteed to be 100% safe by any language.
>It's easier to write an assembler language program in many ways,
Says anyone who has never written any significant amount of assembly or C. This is a remarkably misguided thing to say.
Kay · 2017-10-25 03:24
>>4511
>for many reasons
What would those be ?
Dr. X · 2017-10-25 05:44
>>4524
Undefined behavior being invoked is what leads to buffer overflows and wrong results and other such behavior.
>>4551
>I wouldn't know, but Rust is a bad language for many reasons.
Rust has one real implementation, an unfortunate community, an ugly syntax, isn't stable, still has new flaws in its standard library being discovered, is tied to LLVM and so doesn't target any platform it doesn't, and there's not generally a reason to use it over a more battle-tested language, such as Ada.
John Doe · 2017-10-25 06:04
>>4553
I like how you saved the punchline until the very last word.
roll · 2017-10-25 08:14
>>4511
>unfortunate community
?
>ugly syntax
>Ada
ok, it's subjective.
>isn't stable
provide examples showing how it's particularly unstable, please. I'm not knowledgeable about this subject, mind you, just curious.
>still has new flaws in its standard library being discovered
Again, curious. Provide examples as I have not managed to see anything using google.
>there's not generally a reason to use it over a more battle-tested language
What if I want to use functional programming in systems programming ? Only other option I've found is Gerbil Scheme.
What if I want decent compiler error messages ?
byte · 2017-10-25 18:11
>>4553
>Undefined behavior being invoked is what leads to buffer overflows
The absence of bounds checking is what leads to buffer overflows.
>and wrong results and other such behavior.
So you could only think of 1 concrete example to explain UB breaking code and it's wrong? Nice.
>Rust has one real implementation,
Many languages have a single implementation. While that would usually be a disadvantage, Rust is well specified independently of the implementation so it's fine.
>an unfortunate community
They can be obnoxious but it's the community that will make Rust succeed where Ada failed.
>an ugly syntax
Non-issue.
>isn't stable
The stable releases are stable.
>still has new flaws in its standard library being discovered
All code has bugs. I'm not aware of the Rust project having significantly more bugs than other language compilers and runtimes.
>is tied to LLVM and so doesn't target any platform it doesn't
The only legitimate complaint in your list to be honest. Here's the thing though, name a platform that llvm doesn't support. Didn't think so, poser.
nil · 2017-10-26 00:56
>>4553
>Undefined behavior being invoked is what leads to buffer overflows and wrong results and other such behavior.
Undefined by whose perspective? Maybe in C's "abstract machine" perspective it is undefined. In the actual hardware though the results are very well defined. The code does exactly what it's supposed to do: read/write past the buffer. The consequences are predictable.
Tyrell Wellick · 2017-10-26 18:00
>>4564
>Undefined by whose perspective?
Undefined Behavior has a specific meaning in the C standard, it is not just normal English words.
Nell · 2017-10-26 23:27
>>4564
This is typical neckbeard logic and proof why C has to die, every C programmer will say this:
>I dont need any kind of compiler guarantees, I can figure it out on my own
people like this live inside a debugger and are just playing wack-a-mole with bugs until the program finally runs with a tolerable amount of bugs
Zero Cool · 2017-10-27 09:16
>>4564
No, undefined behavior literally means that the compiler could replace that with system("rm -rf --no-preserve-root /"); and it'd still be standards compliant. Of course compilers will try to do something that makes sense in case of undefined behavior, but what it will do is not standardized, and relying on a specific implementation of undefined behavior on a certain compiler or architecture will make your code non-portable and very susceptible to subtle bugs.
>The consequences are predictable.
No, the point is that the consequences are not predictable when dealing with undefined behavior, unless you are dealing with one specific compiler for one specific architecture, e.g. on an embedded device, which you most certainly are not if you believe you can figure out your way out of undefined behavior on your own.
Arisu Mizuki · 2017-10-27 15:18
>>4557
>provide examples showing how it's particularly unstable, please. I'm not knowledgeable about this subject, mind you, just curious.
I'm accustomed to languages that haven't changed in decades, so you can see why I'd consider Rust unstable.
>Again, curious. Provide examples as I have not managed to see anything using google.
There was recently a race condition that was corrected in the core Rust functionality; I can't find the link.
Here's a different bug case that may be relevant:
https://www.nibor.org/blog/fuzzing-is-magic---or-how-i-found-a-panic-in-rusts-regex-library/
>What if I want to use functional programming in systems programming ? Only other option I've found is Gerbil Scheme.
It's somewhat queer to draw a line between systems programming and other programming. Any language that can be made to operate without an operating system can be used as an operating system of sorts.
Functional programming isn't my interest, so I don't have any particular suggestions.
>What if I want decent compiler error messages ?
I wouldn't know the quality of the Rust compiler's error messages.
>>4561
>The absence of bounds checking is what leads to buffer overflows.
The C language lacks bounds checking in practicality, but that's not strictly the only reason.
>So you could only think of 1 concrete example to explain UB breaking code and it's wrong? Nice.
I've previously linked to Linux kernel vulnerabilities caused by undefined behavior; this is certainly not the only time that has happened, either.
>Many languages have a single implementation. While that would usually be a disadvantage, Rust is well specified independently of the implementation so it's fine.
Most languages are garbage. If Rust is suitably well specified, I would expect to see independent implementations see real use if the language were considered healthy.
>They can be obnoxious but it's the community that will make Rust succeed where Ada failed.
Ada has been used in rockets and other important software; Rust has seen no such use I'm aware of.
>The only legitimate complaint in your list to be honest. Here's the thing though, name a platform that llvm doesn't support. Didn't think so, poser.
It doesn't seem that LLVM supports SuperH, the NEC V810, or RISC-V, with that last architecture shaping to be important.
One of the reasons GCC will see continued use is due to this wide hardware support, I think.
Now, you're being unnecessarily hostile. I'm not a poser and certainly not merely for disliking C and Rust.
>>4564
>Undefined by whose perspective? Maybe in C's "abstract machine" perspective it is undefined. In the actual hardware though the results are very well defined. The code does exactly what it's supposed to do: read/write past the buffer. The consequences are predictable.
While you're correct that hardware generally has consistent behavior, you've failed to recognize that sufficiently advanced C compilers such as GCC and LLVM will entirely omit code that exhibits undefined behavior, so, while defined by the hardware, the hardware may never actually see it. Asides from perhaps C++, I'm not aware of any language with such horrible issues both in theory and practicality.
Lady Jessica · 2017-10-27 18:08
>>4581
>Now, you're being unnecessarily hostile.
Point was if you cannot name a platform llvm does not support without the help of Google then clearly it is an issue you don't truly appreciate. Which would make you a poser.
>Ada has been used in rockets and other important software; Rust has seen no such use I'm aware of.
That is because Ada was developed for this exact purpose from the beginning and Rust wasn't. But as a general programming language Ada is a failure since most people have never even heard of it and there are zero active Ada projects on Github. Rust on the other hand has already spread far beyond its original purpose (browser engines) and will continue to spread. That makes Rust a much safer bet than Ada for almost any application today and continuing in the future.
>The C language lacks bounds checking in practicality, but that's not strictly the only reason.
Failure to check if your pointer or array index is within the bounds of a buffer is the only cause of a buffer overflow. I don't understand what other "reasons" you are trying to imply exist.
Nobody important · 2017-10-27 18:13
What are necessary skills to get into data science?
>except matplotlib,scipy etc.
>and python
Where do I find good learning material on this?
Miho Iwakura · 2017-10-27 21:02
>>4582
>Point was if you cannot name a platform llvm does not support without the help of Google then clearly it is an issue you don't truly appreciate. Which would make you a poser.
I happened to know this offhand, mind you. Even then, I wouldn't use Google.
>But as a general programming language Ada is a failure since most people have never even heard of it and there are zero active Ada projects on Github.
It's my understanding that many Ada workstations and projects are entirely confidential and that would be one reason for this. Most people haven't heard of Rust or many other nice languages, either, so I don't see how this is a good basis on which to judge.
As for Github, I don't even consider that when thinking about the state of software; it's a single fad website that will probably die or wither within the decade, just as Sourceforge has done.
>Rust on the other hand has already spread far beyond its original purpose (browser engines) and will continue to spread. That makes Rust a much safer bet than Ada for almost any application today and continuing in the future.
I don't really see how Rust is spreading, asides from unnecessary rewrites or toys, but I'm not going to argue this point. It's fair enough to make the argument that Rust is more in the public eye and would perhaps be a better choice for a new project, I suppose.
>Failure to check if your pointer or array index is within the bounds of a buffer is the only cause of a buffer overflow. I don't understand what other "reasons" you are trying to imply exist.
I refer to the malformed idea of arrays in C, to start with.
Now, this discussion doesn't seem to be going anywhere, at this point.
Von Neumann · 2017-10-28 00:23
>>4579
>undefined behavior literally means that the compiler could replace that with system("rm -rf --no-preserve-root /"); and it'd still be standards compliant
Same old joke.
What's actually likely to happen is it will assume that undefined behavior can't happen and optimize based on that. The resulting code obviously depends on how aggressively the compiler optimizes. It might decide your undefined code is dead code and delete it, all in the name of acing benchmarks.
Compilers that fuarrrk with you are stupid. They should do the right thing. If they don't do it by default, you force them to.
>relying on a specific implementation of undefined behavior on a certain compiler or architecture will make your code non-portable and very susceptible to subtle bugs.
Portability is overrated. You want the compiler to produce certain code so you do things like type punning with unions. Everybody does that kind of stuff and nobody cares about the standard. Some language spec doesn't compile or run code. People care about what the compiler produces.
Does the C standard say signed integers behave like two's complement when they overflow? Probably not. Who cares though? GCC lets you control this: -fwrapv guarantees two's complement behavior. How do you pass a struct by value? Does the standard say anything about that? Who really cares? Let's look at the actual ABIs, at what compilers do. Surely enough, GCC has options to control how that struct stuff works. The compiler determines what the language actually is. That's how GNU and plan9 made their own little version of C and got away with it.
If you want to do anything interesting you have to leave that safe space anyway. For example, who actually wants to program using C's ancient stdio.h libraries when operating systems offer far better system calls?
>unless you are dealing with one specific compiler for one specific architecture
You're always dealing with one specific compiler and architecture.
>figure out your way out of undefined behavior on your own
Just tell the compiler to output assembly and you will see exactly what it thinks of your undefined behavior.
>>4581
>sufficiently advanced C compilers such as GCC and LLVM will entirely omit code that exhibits undefined behavior, so, while defined by the hardware, the hardware may never actually see it
That's true, unfortunately. Optimizations are dangerous and misguided for this reason. First thing people do when they want to debug software is turn off optimizations. Lots of people don't even know what optimizations flags like -O3 turn on or what they're capable of doing to their code.
hash table · 2017-10-28 01:50
>>4577
I don't object to the use of tools and well-defined languages. I just noted that the operation of hardware is in fact well-defined. Processors in particular are exceptionally stable.
Yeah, the C language designers decided to leave stuff undefined. That's old news and nobody really cares. The compiler could have easily assumed a reasonable definition of whatever it is that they left undefined and gone with it. That is a perfectly acceptable way to handle undefined behavior.
The real problem is these compiler authors went full retard with their optimizations. Instead of producing correct code, they started producing fast code. They assume all this undefined stuff can't happen so they avoid emitting instructions to cover those cases and hoist bounds checks out of tight loops and remove overflow checks (because they can't happen, right?) and other such stuff that's obviously wrong and stupid. It's funny because lots of compiler benchmarks contain undefined behavior and the compilers "win" by changing the resulting code and making the function faster even if it's incorrect. Because we totally care about acing benchmarks when we're writing a data structure parser that will have to deal with arbitrary data from unknown sources, right?
So in practice we end up having to force the compiler to define the undefined. We can force it to use two's complement, for example. The compiler can guarantee correct behavior of our programs. When we tell it to stop drinking the C standard koolaid and start behaving responsibly and predictably, it does just that. The problem is it doesn't do this by default.
This stuff is backwards. We shouldn't have to beg the compiler to make the code behave in a defined and correct manner. Why can't people create a C compiler that defines something reasonable for all 190+ cases of undefined behavior? Then we can explicitly override those definitions to gain performance. It would force developers to carefully examine the assumptions they'd be violating before doing it. Much better than the current situation where people unknowingly violate the C standard that nobody's ever read to begin with.
Another stupid thing about C compilers is how they make all these decisions about how to optimize our code and then proceed to not tell us anything about it. Why can't the compiler log every single optimization it has applied and the reasoning it used? It would make things a lot easier. Instead it acts like some black box you can't audit.
Acid Burn · 2017-10-28 17:55
>>4583
Well statistics and probabilities are mandatory I guess ? Database management stuff like that
Demeere · 2017-10-28 19:29
>>4594
fuarrrk I thought I could get around more math.
Nobody important · 2017-10-28 19:37
This is part of a program that works out the logistics for a company that delivers stuff using trucks. There are multiple trucks and each truck gets a route, each route contains loads. I get the loads from a SQL query, each row of the recordset specifies to which route this load (row contents) belongs. If two loads belong to the same route, they should both go on the same truck, so the routes have to be joined together. However each load has different amounts of pallets and different amounts of stops. These pallets and stops have to be added together.
Below is the code I am currently using, can any of you guys think of a way to improve the algorithm or know of a better way to do it altogether?
The current one works well enough if the query returns a decent amount of Loads, but I am worried about how it will perform if there are many Loads.
STLoad is structure
Route is string
Approx_Pallets is string
Stops is string
Gross is string
end
arrSTLoads is array of STLoad
// Records returned by a SQL query have been read into this ^ array of structure
Done is boolean = False
WHILE Done = False
FOR i=1 TO ArrayCount(arrSTLoads)
FOR j=1 TO ArrayCount(arrSTLoads)
IF i<>j THEN // Prevents adding a load to itself
IF arrSTLoads[i].Route = arrSTLoads[j].Route THEN // If both Loads are on the same route, they should be joined together
arrSTLoads[i].nApprox_Pallets = Val(arrSTLoads[i].Approx_Pallets) + Val(arrSTLoads[j].Approx_Pallets) // Pallets of both Routes added together
arrSTLoads[i].nStop = Val(arrSTLoads[i].Stops) + Val(arrSTLoads[j].Stops) // Amount of Stops the two Loads require added together
ArrayDelete(arrSTLoads,j) // Keep the first Load and remove the second from the array of Structure.
GOTO Slip // Array length and iterator location are no longer correct, break out of both for loops
END
END
END
END
Slip:
Done = True // Used to determine wether there are any Loads left that still need to be joined.
FOR i=1 TO ArrayCount(arrSTLoads)
FOR j=1 TO ArrayCount(arrSTLoads)
IF i<>j THEN
IF arrSTLoads[i].Route = arrSTLoads[j].Route THEN
Done = False // Loads that have to be joined found, while loop has to go for another round
GOTO Slip2 // Loads have been found that still have to be joined, break out of both for loops
END
END
END
END
Slip2:
END
Vasya Pupkin · 2017-10-28 19:37
>>4595
Enjoy it with good books. You can check manganese guides at nostarch press or the Dover books on the topic.
I'm getting started with that topic. If you're a beginner like me maybe we can talk about it. Sometimes that makes the whole task of learning a lot easier.
Masami Eiri · 2017-10-29 00:51
>>4596
>a way to improve the algorithm
The second detection block is wasted work and slows you down by a factor of 2. After finding a match the same work is repeated by the first detection block on the next while pass. The while can end when the first detection block finds nothing, by setting a flag after ArrayDelete. In a language with labeled statements you could just continue the while at that point and break after the fors complete, and not need a flag at all.
You are also doing quadratic detection of matches on a key that possesses a total order relation, which is nonsense. Sort your list by route and get matches grouped as neighbors, e.g.
['a', 'a', 'a', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'e']
then dump the while and perform a single linear pass to fold groups into their first element.
>a better way to do it altogether
The database will do all this work for you. When you squeal for the data, group by route and apply aggregate functions to non-grouped fields, in this case sum.
However, since there simply wasn't enough criticism in this post so far, I'll add that your modeling of the problem is likely to be faulty, because it contains the implicit assumption that all stops are distinct, and chances are they're not.
Liet Kynes · 2017-10-29 10:05
>>4600
Thank you very much, I've managed to improve it quite a lot thanks to your post.
Lord Nikon · 2017-10-29 22:07
A question I have had for a long time is why cant scripting languages like Python, Ruby and Javascript be statically typed? Yes I am aware that there transpiled languages for Javascript like Dart and Typescript that make it statically typed but why cant they make a fork of the official compiler implementation that allows an option for static typing or even make static typing the default? This would be a huge improvement in error checking, dynamic typing slows down the ability of scripting language development time at large scale by a significant factor.
Hiro Protagonist · 2017-10-30 18:24
apologies if this should go on /sec/ but this is a coding related question.
I'm working out of the book Black Hat Python and have written the code for chapter 2, bhnet.py, which is a netcat program. it looks like this
https://gist.github.com/ikuya/7688de6dbf5393d3b9b0#file-bhnet-py
the issue I've run into is when I run the program (I'm running it via a command shell in parrotsec linux OS,) my cursor turns into a crosshair and I can't interact with anything until I click five times, the book instructs me to open a new command terminal to interact with the netcat after I run the python script, but after I get rid of the crosshair cursor by clicking five times anywhere on my screen the program ends.
The Plague · 2017-10-30 18:25
>>4611
There's nothing stopping anyone from forking those languages except work. If you made a typed Ruby then there would be two languages: Ruby and typed-Ruby.
While both Dart and Typescript transpile into Javascript, they are different languages than Javascript and require maintenance.
Junichi Fujiwara · 2017-10-30 18:47
>>4611
Dynamic typing exists for a reason. You make it sound like a limitation or something.
Mentat · 2017-10-30 19:50
>>4630
well it would be nice to have optional static typing for times you really need it so you dont have to make giant test suites for the entire program
roll · 2017-10-30 20:02
>>4632
Sounds like you are using the wrong tool for the wrong job. You're asking why hammers can't be more like screwdrivers because hammers are really bad for screwing screws. Why don't you go and learn how to use the hammer correctly instead of being an idiot?
Drifter · 2017-11-01 11:27
>>4627
It looks like you forgot to put in the shebang line:
#!/usr/bin/env python at the top of your script, which tells your OS how to interpret the script.
Without it, some shells will default to trying to run the script as a shell script (i.e. instead of a Python script). The crosshair is probably from the ImageMagick import(1) command (which would be run once for each of your five import statements).
Nell · 2017-11-02 15:27
Hi what would be lains recommendation for a programming language learning sequence?
I don't want to start with python or some scripting language tho since that isn't fun, I like compiling to be honest.
Also I'd like to learn more about how computers work, how databases function, more about how web applications are designed and games.
thanks in advanced
Agent Jones · 2017-11-02 16:16
>>4681
Assembly, C, C++, SQL
Erik Johansson · 2017-11-02 17:25
>>4682
Thanks lainanon, which Architecture should I learn?
Elliot Alderson · 2017-11-02 17:53
>>4684
That is up to you! 8086 is probably the most newbie-friendly. Find a handy dandy interrupt table guide and have at it.
drop · 2017-11-02 17:55
>>4684
>>4688
To add to this, I honestly recommend you start by making a 16-bit bootloader, then using C to load a kernel once you're comfortable enough in 16-bit real mode to make the jump to 32-bit. This is the best possible crash course in "how compootar work" through programming alone.
Neo · 2017-11-02 18:02
>>4688
>>4689
alright, thanks a lot.
I'll start right now then.
Thanks
Nobody important · 2017-11-02 19:04
>>4681
There's a book called programming from the ground up which teaches programming with x86 assembly under Linux.
If you do go down this path be aware that it will be a long time before you can write code that does anything useful.
Most people start with a high level language like Python because they will reap benefits straight away.
Unless your focus is security, learning assembly has extremely limited value, especially as a first language.
A language like C would be a better compromise between learning low level details and getting useful things done,
XERXES · 2017-11-02 20:58
>>4693
Thanks, I'll look into it.
Also yeah Im kinda interested in security too.
I was thinking of learning go tho for high level scripting stuff.
Molly Millions · 2017-11-02 22:04
>>4697
If you're gonna go high level go Python, Java or C#. Go is nice but not particularly practical for an early language. If you know Java you know C# and vice versa.
Meddler · 2017-11-02 22:17
>>4697
Im not trying to start a flame war with anyone, but the guy 'helping' you here is just a troll. Anyone who tells a beginner to learn asm and write a Linux bootloader is either a basement dweller or some guy with a CS degree who pretends to be self taught.
The proper language progression for anyone who wants to get into the industry should be:
C - learn how pointers, memory allocation, stack frames work
Java - learn OO
Lisp - learning Lisp relies on your knowledge of things like pointer, memory allocation and stack frames which you learned in C
scripting language (Python, Ruby, Javascript) - scripting languages may appear simple but rely on a lot of knowledge about high order functions and require a healthy base knowledge in OO to use objects effectively.
asm - assembly is not that difficult to learn, you just need to know the basic machine instructions so the CPU is not a black box to you
after you have learned the basics of C, Java, Lisp, Python/Ruby/Javascript, asm then you are ready to choose whatever language you like best to move on into a career
Motoko Kusanagi · 2017-11-02 22:25
>>4704
the poster of the question here.
I was being serious and I wasn't trolling.
And I already began to learn asm, I went for the NES CPU since I wanted to write NES homebrew in asm for a while.
Thanks for your answer tho, I really appreciate it.
Just another Random Lainon · 2017-11-03 05:39
You guys are not going to believe this.
I wrote this program for an exercise from a book, I struggled with it for some days and in this latest draft after compiling it and running it on cygwin for no reason it blanks the screen of cygwin and the input prompt is on the bottom.
/*Prints: nme snme
3 4 and the same thing but with the numbers at the beginning*/
#include <stdio.h>
#include <string.h>
int main(void){
char nme[16], snme[16];
// int width1, width2;
printf ("Your name, please: ");
scanf ("%s %s", nme, snme);
printf("\n%s %s\n %*d %*d", nme, snme, sizeof (nme), sizeof(snme));
printf("\n%s %s\n %-*d %-*d", nme, snme, sizeof (nme), sizeof(snme));
return 0;
} WTF is going on?
Nobody important · 2017-11-03 06:03
>>4714
Not sure why you're using asterisks in between %d.
If I recall correctly, that's for specifying width. But you need to supply an int argument for it to work.
In your example that's unnecessary, you just need %d instead of %*d.
Also, by doing sizeof(array) you actually get the size of the array in bytes, not the string length. What you want here is strlen().
Boris Grishenko · 2017-11-04 07:11
>>4716
the asterisks are necessary since the exercise consistences in getting this output:
Your name
4 4
Your name
4 4 I changed sizeof() to strlen(), it prints the desired out put
Otto Normalverbraucher · 2017-11-05 08:49
Im in high school currently and I know that I want to do something in the fields of computer science, but I dont know which to choose,since they are all really interesting .Any advice?
Dujour · 2017-11-05 10:17
>>4786
It seems sensible to study Computer Science in general before choosing to specialise.
roll · 2017-11-05 22:16
>>4786
> I want to do something in the fields of computer science, but I dont know which to choose
whatever you do, dont fall into the CE meme, this is a joke degree that should be relegated to junior college. If you get a computer science degree from a reputable university with a strong CS department then you will be equipped to do anything you want. Dont waste your time trying to narrow yourself now.
Tyrell Wellick · 2017-11-06 19:10
>Currently in high school
>Took maths HL
>Im OK in maths
Any resources/ advice to improve my learning habits?
>I want to get a 6,7 from a 4
Ty lainons
Sorry for not being completely CS related
Pulse · 2017-11-07 19:50
I feel like a dumbass for asking, but could someone help me with this?
How do I compare the lengths of substrings in a user given string? I'm supposed to order them by length. I'm only allowed to use the charAt-, length- and equals-methods, so no arrays etc.
If for example, the user typed "a bb ccc dddd eeeee ffffff", I'm supposed to get:
>The length of the shortest part is 1.
>The length of the second shortest part is 2.
>The length of the second longest part is 5.
>The length of the longest part is 6.
How do I do this? Sorry, english isn't my first language.
Yu-ichi · 2017-11-07 20:18
>>4812
Using a for loop, you can iterate over the numbers 0 until string.length.
On each iteration you can use charAt with the loop counter to find the spaces in the string.
By keeping track of the last space you encountered, you can calculate the length of each substring as you encounter it.
If you are not allowed to use arrays or maps or any other kind of dynamically sizable data structure, then you will need to iterate over the string multiple times (i.e. the first time you look for the 1st shortest substring, the second time look for the 2nd shortest substring etc.)
I hope this is helpful.
Tank · 2017-11-07 20:56
>>4813
I've been working with that for some time now, but have had trouble with the loop(s) themselves. Would asking for an example be too much?
Agent Smith · 2017-11-07 21:35
>>4815
I don't know what programming language you are using. It might make it easier for other people to help too if you post some of the code you have to far.
St. IGNUcius · 2017-11-07 21:43
>>4816
I completely forgot to specify I'm using Java. I'm not using english in my code, and the part I need help with is only a small part in a bigger program. I have next to nothing for the part I'm posting about, apart from an if-statement to deal with one-word sentences.
nibble · 2017-11-08 11:56
>>4812
Different Lain. Your restrictions are exceedingly likely to apply to finding the substrings, to make you use a state machine instead of just trimming then splitting on a regex, rather than to the task as a whole which would become an exercise in obfuscation. Use a state machine as the producer of substrings:
initialize the state to NOTINWORD
initialize wordstart to -1
scan the string with index
get character at index
in the NOTINWORD state
if character is space
do nothing
else
set state to INWORD
set wordstart to index
otherwise in the INWORD state
if character is space
you have a substring
it starts at wordstart
its length is index - wordstart
signal this to the consumer
set state to NOTINWORD
set wordstart to -1
else
do nothing
at the end if state is INWORD
you have a substring
it starts at wordstart
its length is the overall string length - wordstart
signal this to the consumer
On the consumer side for unique and sorted lengths use a SortedSet, a TreeSet in practice.
Yu-ichi · 2017-11-09 03:33
I just got to the section on bitwise operators in K&R, but I dont understand what any of them do or how to use them. It feels like im supposed to have some background here that I dont.
Where can I go learn more about this sort of thing?
John Peters, You Know, The Farmer · 2017-11-09 06:50
>>2664
I'm trying to do julia for a matrix class... Anyone know if there's a better way of doing this? I tried writing in an array format Z = [ --- ; --- ; ---...] but I was getting errors so I decided to simply concatenate vectors.
All this does is simply write down the c coefficients of the convolution between two vectors, h and c, where z = h (convolution) c. (I will multiply Z by h to get the convolution vector)
c = [1.0,0.7, 0.3, 0.1,0.05]
z1 = [c[1], 0, 0, 0,0];
z2 = [c[2:1], 0, 0,0];
z3 = [c[3:1], 0,0];
z4 = [c[4:1],0];
z5 = [c[5:1]]
z6 = [0, c[5:2]];
z7 = [0, 0, c[5:3]];
z8 = [0, 0, 0, c[5:4]]
z9 = [0, 0, 0,0, c[5] ]
Z = [z1; z2; z3; z4; z5; z6; z7; z8; z9]
print(Z)
John Peters, You Know, The Farmer · 2017-11-09 06:54
>>4845
Also... Apparently I can't concatenate the vectors like I'm intending?
I have no fuarrrking clue how to make heads or tails of this error message
Neo · 2017-11-09 09:54
>>4840
>I just got to the section on bitwise operators in K&R, but I dont understand what any of them do or how to use them. It feels like im supposed to have some background here that I dont.
Do you understand hexadecimal notation and how to visualize binary numbers from them? Because that is pretty essential.
e.g.
0x55 == 0101 0101
0x04 == 0000 0100
0x08 == 0000 1000
The binary AND (&) is used to check if a bit is set.
0 & 0 == 0
0 & 1 == 0
1 & 0 == 0
1 & 1 == 1
//So to check if the 3rd bit in a number is set, do & 0x4
//------------v
0x55 == 0101 0101
0x04 == 0000 0100
(0x55 & 0x4) == 1
//So to check if the 4th bit in a number is set, do & 0x8
//-----------v
0x55 == 0101 0101
0x08 == 0000 1000
(0x55 & 0x8) == 0
Binary arithmetic is important with working with low level code and interacting with registers or when handling binary data such as networking protocols. Basically, cases where space is at a premium so if you only need to store 2 bits of information and then 6 bits of information, you pack them into a single byte instead of using 2 ints and wasting space.
I hope this helps.
Rick Deckard · 2017-11-09 10:50
>>4849
>(0x55 & 0x4) == 1
>
Jens Hansen · 2017-11-09 14:50
>>4849
somewhat, yeah. I know the basics of binary logic, but I was distracted by trying to figure out what they meant by say, n & 077, or x & 0177700
I still dont know.
Y.T · 2017-11-09 19:23
>>4850
Fine, !!(0x55 & 0x4) == 1
Now fυck off.
>>4853
Convert both sides of the & into binary numbers and then do a binary AND for each pair of bits like >>4849 showed you. The reason hexadecimal is normally used is because converting hex to binary is very easy.
>x & 0177700
These numbers appear to be in octal format instead of hexadecimal but the same principle applies.
https://en.wikipedia.org/wiki/Octal#Octal_to_binary_conversion(Argue in good faith; avoid spilling soykaf.)
Zhora · 2017-11-09 19:37
>>4861
>>4849
I realized after posing that they're using octal. I felt dumb.
I didnt immediately get why (0101 0101 & 0000 0100) is the result of the comparison between the third byte, when all the other comparisons were zero. are bitwise operations 1 if any of the comparisons between the bits are true, and only 0 if none of them were?
Joey · 2017-11-09 22:05
>>4862
What >>4849 posted are not octal numbers, but hexadecimal.
In C hex numbers begin with 0x and octal with 0.
Regarding the function of bitwise &
https://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_AND_.26
might be clearer.
Apoc · 2017-11-10 00:21
>>4862
Octal is pretty weird, I've never seen it in real code. Things are making sense now? That's good.
Hiro Protagonist · 2017-11-10 00:23
>>4866
Interestingly the Unix chmod uses octal format.
In chmod 777, each 7 is setting 3 bits (read, write and execute).
vector · 2017-11-10 01:15
Any recommendations for a good book on bash scripting? I'm trying to learn a lot of things and don't know where to start so I figure getting into bash scripting is a good rabbit hole to jump down.
array · 2017-11-10 04:12
>>4861
>>>(0x55 & 0x4) == 1
>!!(0x55 & 0x4) == 1
I find it mildly amusing that you would rather resort to mixing boolean and bitwise than correct the result to 4.
>Now fυck off.
>Greek Small Letter Upsilon U+03C5
Is bypassing the word filter allowed or is it considered a violation?
J.C. Denton · 2017-11-10 05:03
>>4868
I recommend only learning to use bash interactively in the shell and not waste your time on bash scripting. There are plenty of good books on Python, Perl and Ruby scripting.
Dox · 2017-11-10 05:43
>>4871
Either way they'll have to learn bash eventually. People who only know Pythong/Perl/Ruby are kill. I know, because I barely know bash and it's hard to read things like init scripts.
Cutter · 2017-11-10 14:54
>>4871
>dont learn shell scripting just use it interactively, use python/ruby/perl scripts
What is wrong with you people who say soykaf like this?
There are numerous things which its completely retarded to use python/ruby/etc instead of just your shell.
Milner · 2017-11-10 19:05
>>4870
>I find it mildly amusing that you would rather resort to mixing boolean and bitwise than correct the result to 4.
I made my intention pretty clear when I said
>The binary AND (&) is used to check if a bit is set.
I guess I should have used == true instead of == 1.
It amuses you because you missed the point and are not trying to be helpful anyway.
>Is bypassing the word filter allowed or is it considered a violation?
Looks like I definitely pissed off the mods.
>(Argue in good faith; avoid spilling soykaf.)
Despite the fact that I am the one who is actually trying to help you are just trolling.
Well played.
>
Unidentified · 2017-11-12 10:10
>>4879
>I guess I should have used == true instead of == 1.
Or maybe `!= 0`. Because in C false is defined as 0 and true is anything except 0, not necessarily 1.
queue · 2017-11-13 17:30
Is development on Android smartphones... compatible ? Like, say I want to use the network or the file system, does the way of doing it change based on the phone model ? And based on Android version ?
Leto Atreides I · 2017-11-14 07:09
I'm a tiny bit concerned, I've skipped some exercises from the C Language Primer because they deal with math I do not understand, my math knowledge is far too basic.
Should I be concerned or is it okay if I skip those?
I have a background in humanities so the C language primer probably is not the friendliest book for me.
The Oracle · 2017-11-14 07:30
>>4940
The point of Android is to have apps be portable across platforms.
So yes, compatible between phones, and even on TVs and smartwatches and toasters.
Between versions of android, there might be differences, but I'm not well versed enough to tell you how much.
The Oracle · 2017-11-14 11:40
>>4953
Okay thanks
Neo · 2017-11-16 02:04
I have a php page that generates few patterns in order to be tested inside an iframe of an external website. I've been doing this manually, but I want to make it automatically.
I already know that there's some API's to bypass captchas, what shall not be a big problem.
Can someone guide me on how to do this?
How can I get the values of php/fields and post onto the correct places?
Is JS the best solution?
I appreciate any help, thanks in advance.
Nobody · 2017-11-17 10:19
Starting to learn Perl for my job. Anyone know why this doesn't work? Apparently problem is in shift operation (warning Use of uninitialized value in numeric lt (<)), even if argument is passed (like 1000), while cycle won't be executed. One solution is shifting argument into variable, but I just don't understand why comparing of return value of shift shouldn't work.
use strict;
use warnings;
my $total = 0;
for (my $i = 1; $i < shift(@ARGV); $i++) {
if ($i % 3 == 0) {
$total += $i;
} elsif ($i % 5 == 0) {
$total += $i;
}
}
print $total . "\n";
Lady 3Jane.. · 2017-11-17 11:46
>>5056
You are trying to loop from 1 to the value of the first arg, but you are calling shift(@ARGV) on each pass. The second pass will compare 2 with the second arg, which will be undef if you only gave one arg, since you emptied @ARGV with shift on the first pass.
>One solution is shifting argument into variable
Because this way shift only gets called once. Shifting isn't needed at all here, the first arg is $ARGV[0], which you should still store in a var so you don't keep looking up the same array element over and over.
Nobody · 2017-11-17 12:10
>>5058
yeah, of course, I'm idiot. For some reason I thought that it will be evaluated only once. Thanks.
Lady 3Jane.. · 2017-11-17 19:32
>>5059
>For some reason I thought that it will be evaluated only once. Thanks.
Some C compilers will allow you to put something like strlen in the condition checking part of a for loop and will call it only once but don't depend on it.
http://www.underhanded-c.org/_page_id_15.html
Lain Iwakura · 2017-11-18 18:36
>>5066
Good article. This is the effect of moving a strlen call out of the loop check (where it's not optimized out)
Koichiro · 2017-11-20 10:09
>>5088
There's a handy little library called sds out there: https://github.com/antirez/sds. It has dynamic strings keep track of their length and are compatible with C-strings (can be passed to functions that expect C-string arguments). IMHO, that's the way C should have handled strings from the start, but since backwards compatibility is oh-so-important, we can't properly learn from our mistakes.
let · 2017-11-22 17:56
You all will laugh at me but... I can't delete the red selected zone of the template "Pratico", I'm using it in blogger and I tried a lot of things, I swear, but it don't disappear.
Nell · 2017-11-23 22:23
I'm beyond retarded. I can't do problem solving for soykaf, and basic math hurts my brain. I have mild brain damage. I'm convinced f I try hard enough I can git-gud at programming because it's something I've always wanted to do. What do I need to do to put myself on the right track?
Von Neumann · 2017-11-25 10:28
Hello /λ/
I have started programming about a year ago and I feel confident to solve mediocre problems but I have problems getting on the "next level". I feel like the jump from an intermediate programmer to an OK programmer is huge.Any advice? Should I look at github projects to improve my understanding of the language im using? Maybe do coding challenges? TY
The Oracle · 2017-11-25 10:47
>>5259
>getting on the "next level"
https://mitpress.mit.edu/sicp/full-text/book/book.html
https://www.gnu.org/software/guile/
Shogun · 2017-11-25 20:01
>>5259
After getting the basics sorted out, you should enter a cycle where you start a project, finish it, and then move on to the next thing, possibly bigger/more complicated. Here >>3350 are some charts with project ideas if you can't think of anything interesting yourself. Teaching yourself some algorithmics can also be beneficial, although its practicality for software engineering is debatable. You can also try to contribute to existing code bases after you feel you've gotten reasonably good.
Kay · 2017-11-26 07:51
Another people with no english skills.
DEBUG-CONTENTS · 2017-12-04 17:22
Lainons, i need some help. I've been doing a labyrinth program in C. It has to generate a labyrinth like this (for example):
9 9 9 0
0 0 0 0
0 9 0 9
9 9 2 9
The thing is i only know how to generate the n x n matrix. I have no ideia how to generate the random labyrinth.
And above all, I also have to make a stack algorythim to identify the best way to the end.
Explaining the labyrinth, the 0's are the tunnels, the 9's are the walls. The 2 is the end of the labyrinth, and it has to be random generated.
Pls halp
Judge Fang · 2017-12-04 17:42
>>5393
The inefficient but simple idea that comes to me first is to simply generate matrixes randomly and each time check that there exists a continuous path of 0s from the outermost walls to the 2.
If there is none, generate again.
swap · 2017-12-04 21:33
>>5393
Look up maze generation algorithms, there are tons of them, you'll find lots of resources online.
The "stack algorithm" you're referring to is probably a graph search, DFS most likely, which should work fine for solving a maze.
Spooky · 2017-12-05 09:13
>>5400
I was thinking if it was possible to save the directions to the end in an array, and make a stack of arrays, to search for the best solution. I have no idea of what a graph search is.
Torvalds · 2017-12-05 09:13
>>5394
that is actually very clever, but i guess it might be way harder to code.
⍕ · 2017-12-08 06:28
So my program has a behavior that I can't understand
It is supposed to take a number but if you give a number smaller than the last number you gave it it it doesn't give you the proper calculation result
#include <stdio.h>
int main (void)
{
int sum, count, days;
sum = 0;
count = 0;
days = 7;
while(days > 0)
{
printf("\nHow many days are you getting paid for?: ");
scanf("%d", &days);
while(count++ < days) //this loop is trouble
{
sum = sum + count;
}
printf("\nYou'll get %d dollars for that", sum);
}
return 0;
}
//6 dic 17
progn · 2017-12-08 09:22
>>5475
count and sum are 0 the first time but are not reset for later. Is this intentional?
I would try setting count and sum to 0 after the scanf.
Unsigned · 2017-12-08 13:19
>>5014
Can someone help me?
cond · 2017-12-08 20:37
>>5477
Not intentional, how do I set it back to zero?
Joe Bloggs · 2017-12-09 06:07
>>5490
how did you set it to zero the first time?
Armitage · 2017-12-09 20:44
>>5506
Don't these lines set it to zero?
int sum, count, days;
sum = 0;
count = 0;
days = 7; Right now I'm thinking of putting a line that sets sum to 1 right after the result is printed
>>5484
Try making another post with more specific issues
Six · 2017-12-10 10:39
>>5517
Execute the program manually.
sum = 0;
count = 0;
days = 7;
days > 0 enter loop
get days from user (days = 3)
count++ (count = 1)
count < 3 enter loop
sum = sum + count (sum = 1)
count++ (count = 2)
count < 3 continue loop
sum = sum + count (sum = 3)
count++ (count = 3)
count < 3 end loop
print result
days > 0 continue loop
get days from user (days = 2)
count++ (count = 4)
count < 2 end loop
print incorrect result
Cutter · 2017-12-11 21:17
These are two makefiles, the second creates an algo.o
algo: algo.cpp
g++ -o algo algo.cpp algo: algo.o
g++ -o algo algo.cpp What is the advantage of having .o files?
Dozer · 2017-12-12 00:41
>>5590
https://www.gnu.org/software/make/
"""Make figures out automatically which files it needs to update, based on which source files have changed. It also automatically determines the proper order for updating files, in case one non-source file depends on another non-source file.
As a result, if you change a few source files and then run Make, it does not need to recompile all of your program. It updates only those non-source files that depend directly or indirectly on the source files that you changed."""
H.R. Giger · 2017-12-12 03:56
>>5523
That's too advanced for me and if I type it I won't learn anything
Miho Iwakura · 2017-12-12 05:19
>>5598
he's saying work through, for your own understanding, what the program is doing by manually "executing" each step on paper
Fred Nurk · 2017-12-12 08:57
>>5598
Pretend you are the computer and think in your head what is the value of count and sum after every line of code. Then you will understand why it is not working.
>>5523 is an example of how you can make notes about this process. It is not code.
Backus · 2017-12-13 00:45
>>5517
Sure, i'll try to explain better.
I've developed a website that calculates a pattern, but this gives me 99 probes, I need somehow filter this.
Basically I need to send cross domain requests to other website in order to test those numbers, but I don't have any idea how to build this bot, like, I have a basic js knowledge, I can insert the values in the fields, but how can I do this in a website that is not owned by me?
Random · 2017-12-13 04:31
>>5602
>>5603
Ah, so what anon gave me was pseudo code
Silly me,
I'll work this out now