nezachem 616 Practically a Posting Shark

This is no GoExpert, yet we do "have a clue".
So, what is your question?

nezachem 616 Practically a Posting Shark

I've added the 'ofstream output' to the Print_Detail prototype. The error is that the call Print_Detail doesn't take 5 arguments.

input(lettercode, GPA); line 83 getting the error

No. The error is that input is not a function of 2 arguments. In fact, it is not a function at all. According to the Sum_GPA signature, it is a reference to ifstream . If you want to read something from it, you need to call its methods, e.g.

input >> lettercode;
    input >> GPA;

Before you do that, however, be advised, that the OpenFiles function is meaningless as written. The input and output mentioned there have nothing in common with other variables of the same name.

nezachem 616 Practically a Posting Shark

There's an example at the top of paragraph 20.11 (ftplib) of python documentation. See how a callback is passed to retrbinary. You need a similar setup for your ftp.dir() - or better ftp.retrlines('LIST', callback).

nezachem 616 Practically a Posting Shark

This is a documented behaviour. FTP.dir() returns None. However, it calls a callback function for each line of the transfer. The default callback prints lines to stdout. You need to provide your own callback.

nezachem 616 Practically a Posting Shark

How do you build your project?

nezachem 616 Practically a Posting Shark

Your code is notified (that is, OnReceive gets called) when it is safe to read. Then, Receive returning 0 means that the peer closed the connection.
It may or may not indicate that the download completed. To make such conclusion you must look for the particular headers, primarily Content-Length, Connection, Transfer-Encoding, inspect them, and decide accordingly.

nezachem 616 Practically a Posting Shark

However, when i call insert_equivalent in my testing code i get an error saying that it is an undefined reference to it, I don't understand what that means and how to fix it.

This means that you didn't set up your project correctly.

PS: using namespace is a very bad practice. Get used to explicit namespace resolution.

nezachem 616 Practically a Posting Shark

stack and queue are also not defined in the scope

They should be std::stack and std::queue.

q and s are not defined in the scope

Since stack and queue are not defined, the compiler cannot define s and q as well. The namespace resolution (above) should take care about it.

nezachem 616 Practically a Posting Shark

That was it. Good luck. Don't forget to mark the thread solved.

nezachem 616 Practically a Posting Shark

If i'm not mistaken, each child, once completed the transfer closes the file at line 63 and closes connfd at line 64...

... and then exits the if clause, and continues the loop from the beginning. Since it already closed the sockfd, accept() returns immediately with an error, and the loop repeats, eating up all the available processor time.

You are missing a vital call in the child code. It is not related to the networking, but to the process life cycle. Try to figure it out yourself.

nezachem 616 Practically a Posting Shark

Thanks for posting the code. Yet again, as soon as I was able to compile it, run it, and generally play with it, the problem became obvious.

My only gripe now is that for some reason, after the first client is served, the server slows down the computer a whole lot,to the point that it basically freezes it (we're talking two separate computers here).

while(1) {
      connfd=accept(sockfd,(struct sockaddr *)&cliente,&clilen);
      if((pid=fork())==0) {
         ...
      } else {
         close(connfd);
      }
  }

I removed all irrelevant parts. Now tell me, what happens to the child, once it completed the transfer?

On line 51 why are you closing the server socket ? Should that not be like the last step of the program ?

It is the child code. The child doesn't need to listen, and correctly closes its copy of the listener socket right away.

nezachem 616 Practically a Posting Shark

I was planning to write a long response. I was planning to write the same client-server pair myself (and I actually did) to prove that there's nothing wrong with the posted code, and that the problem lies somewhere outside of the fragments you presented.
But at the last moment I noticed a little problem, right there in the server fragment.

if((pid==fork())==0)

Highlighted in red.

Obviously, pid (however (un)initialized it is) does not compare equal to the value returned by fork(); the comparison is false, and both parent and child enter the if clause. That explains all the contradictions, weirdnesses, and inconsistencies in your system behaviour.

The most valuable lesson here is that an incomplete code is impossible to debug.
Even more valuable one is that meditative debugging doesn't worth a dam.

PS:

to use read instead of fgets, and that's my next step, could you please give me the syntax of the function

You already have used them to communicate through the socket. Use write(fileno(fp), buffer, aux) at client.c:12 and read(fileno(fp), archivo, 16) at server.c:13

mitrmkar commented: Nice +5
nezachem 616 Practically a Posting Shark
for(int i = 0; i < 11; i++){

Why 11?

nezachem 616 Practically a Posting Shark

Please explain lines 19 and 20.

nezachem 616 Practically a Posting Shark

Your approach indeed doesn't work for non-integer exponents. It is just not applicable.
Check out Taylor series, or some other approximation.

nezachem 616 Practically a Posting Shark

it is a char array

You must realize that until you disclosed this vital piece of information all attempts to help were shots in the dark.

Now you may try to go with a

union u {
    unsigned long SomeLongArray[2];
    char SomeCharArray[8];
};

which will force the alignment, and avoid ugly casts.

nezachem 616 Practically a Posting Shark

Clear ISIG and turn off a canonical mode:

options.c_lflag &= ~(ISIG | ICANON);

PS: and please use code tags.

nezachem 616 Practically a Posting Shark

I really don't understand how I can implement this function into cosi().

I don't think you should.
In my understanding (from the teacher's point of view), you have to prove somehow that your cosi indeed calculates cosine; in other words, that the values returned by cosi are close enough to the "golden standard" ones returned by cos from a math library.
That is, for each angle you have to calculate both cosi and cos , and feed the results to close_enough .
Yet again, it is my understanding; better check with your teacher.

jonsca commented: That was how I was interpreting it also... +4
nezachem 616 Practically a Posting Shark

I understand what you mean. That professor is known here to be pretty controversial, and i can assure you he said that about fgets. Anyways, without abandoning the fgets and fputs, my mission now is to find a stop condition to the loop in the server, and to prevent the incoming garbage to the buffer. Could this be a way to solve the latter?

while(aux!=0){
  aux=read(sockfd, buffer, 16);

I would prefer

while((aux=read(sockfd, buffer, 16)) > 0)
buffer[aux]='\0'; // In this case, buffer would be buffer[17] instead of buffer[16]

Correct.

if(aux==-1){
  printf("Error en el read");
  }
  else if(strcmp(buffer2,buffer)!=0){
	strcpy(buffer2,buffer);
	fputs(buffer,fp);
   }
    else break;
  }

This is definitely wrong. If the file has 2 identical consecutive strings, you'd terminate transfer prematurely.
You must find the root cause of your original problem. Do not mask it.

nezachem 616 Practically a Posting Shark

Trace it out.

//return T2(12) = 12*2 = 24
def dozen():
    return T2('12')

Split it up and analyze it.

I bet you didn't.
(Hint: T2('12') returns '1212'

nezachem 616 Practically a Posting Shark

I've been able to notice that

fgets(archivo,16,fp)!=NULL

was the one that was giving me the endless loop, my professor said earlier that nowadays it wasn't recommended to use that line

This is a most surprising claim. Either your professor is incompetent, or you misunderstood him. The fact that it gives you a hard time tells that the problem is somewhere else in the program.

the professor is pretty much encouraging us to use fgets, and fputs

In that case you must realize that there is a trouble waiting to happen. Keep in mind, that a read() from the socket may return less data than requested. In your case, the returned chunk may have neither '\n' nor terminating '\0', so fputs will happily send all the trailing garbage to the file.
To use fputs() you must force a '\0' at the proper place in the buffer.

nezachem 616 Practically a Posting Shark

A fairly unorthodox indeed. A standard read/store loop is

while((aux = read(sock, buf, size)) > 0)
    write(out, buf, aux);

Note additional parenthesis in the while condition. Also notice usage of aux in the write call.

Line 13 in the server loop always calculates the same value (either 16 or 4, depending on how archivo is declared), regardless of how many bytes fgets got from the file. The num never becomes 0, with all the consequences. Again, I highly recommend to use read() instead of fgets() .

nezachem 616 Practically a Posting Shark

One thing to add. A straightforward implementation of Taylor series, as in the post #3, quickly leads to numerical problems. A 32-bit integer cannot hold a factorial of numbers beyond 12, which essentially limits the series to the first six members (hence the line 54 of the original post).

A proper way to calculate series is a Horner schema, which allows for literally thousands of member, and never forces a calculation of unreasonable large numbers. Here's how it works for a cosine:

cos x = 
1 - x^2/2! + x^4/4! - x^6/6! + ... =
1 - (x^2/(1*2)) * (1 - x^2/(3*4) + x^4/(3*4*5*6) - ...) =
1 - (x^2/(1*2)) * ( 1 - x^2/(3*4) * (1 - x^2/(5*6) + ...))

etc., which leads to the code

double cos(double x, int n)
{
    int i;
    double rc = 1.0;
    double xs = x*x;

    for(i = n*2; i > 0; i -= 2)
    {
        rc = 1.0 - xs / (i * (i - 1)) * rc;
    }

    return rc;
}
jephthah commented: well, that's clever. thanks for finding that. +7
jonsca commented: Well done +4
nezachem 616 Practically a Posting Shark
while(aux=read(sockfd, buffer, 16)!=0)

is not doing what you expect it to do. Hint: it assigns aux a result of comparison.

One side point: you should not use fgets and fputs (at least not as careless as you do). read and write are better suited for the task.

Also, n server.c at line 20:

else close(sockfd);

should be

else close(connfd);
nezachem 616 Practically a Posting Shark

The code has two obvious problems. First, its time complexity is at best quadratic. Second, the randomness is not guaranteed.
Given that there are linear algorithms with a true random results (see, for example, shuffling), I don't think that this code has any value.

nezachem 616 Practically a Posting Shark

System: Vista

What I want to do is to catch the mouse release event, which I have researched for but nothing useful came up. I found out the way to catch the pressed event:
What I want to use it for is to catch the time elapsed between the 'pressed' and 'released' event.

while( TRUE ) {
	    ReadConsoleInput(hConsole,&InputRec,1,&dwRead);

            if(InputRec.EventType == MOUSE_EVENT) {
                if(InputRec.Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) {
			printf("Left Mouse - Pressed.\n");
		} else {
                        printf("Left Mouse - Released\n");
                }
            }
	}
nezachem 616 Practically a Posting Shark

You can't make the return value of that function anything other than an integer. Why? Because they are not normal functions -- it acts more like a self-contained process than another function, except that threads have access to all global data in the entire program. So when a thread returns it just goes back to the operating system much like any other program would do.

Wrong. The thread process is prototyped to return void * with a purpose. You may return anything it wants. The calling thread may collect the returned value via pthread_join() .

In the following code I am calling a function from a pthread:

pthread_create(&threads[t], NULL, dnssearch, (void *)buffer)

I need to pass the string (buffer) to a function and the have the function pass a string back. What am I doing wrong in the function:

Quite a lot. Starting from a possible buffer overflow in fscanf, and invoking undefined behaviour at line 25, to begin with. Dangerously aliasing an argument. Probably not joining the thread.
Also, it is very unclear what the function is supposed to do; its expected result and actual behaviour. Can you explain it in plain English (especially the do loop at lines 15 to 27)?

Ancient Dragon commented: Glad to know that. Not the first time I've been wrong about something :) +28
nezachem 616 Practically a Posting Shark

The return value of Parse method has nothing to do with what you return from the start_element handler. The latter, in fact, is ignored. To keep the parsed info, the handler should create an object to keep it, and store the object in the persistent collection. It is a fun project to do; helps to understand a lot of XML inner workings; however you'd end up with some incarnation of a DOM model.
If you are just interested in getting results, switch to DOM-style parser right away.

nezachem 616 Practically a Posting Shark

The heap got corrupted somewhere else.
Looks like you are using arrays. Make sure there's no overruns, or any other writes beyond the allocated memory, or double deletes, etc, etc, etc. After you find the problem, dump arrays altogether and rewrite everything with vectors.

Salem commented: Well said +20
nezachem 616 Practically a Posting Shark

If I understand your problem correctly, I'd just modify the protocol in a following way. Let the connected client, prior to anything else, wait for a "go ahead" from the server. Let the server count the accepted connections. Once the desired count is reached, let the server send that "go ahead" to all of them.

nezachem 616 Practically a Posting Shark

I would use such algorithm =>
---------------------------------------------------
index(n) = index(n-1) + K(n) ;
K(n) = K(n-1)*C;
speedUp = (x-numberAt(index(n-2))) / (x-numberAt(index(n-1)));
when speedUp < MaxSpeedUp then C = SpeedUpFactor
when speedUp = MaxSpeedUp then C = 1
when speedUp > MaxSpeedUp then C = 1/SpeedUpFactor
;
MaxSpeedUp = 2;
SpeedUpFactor = 1.5

An overkill, in my opinion.
Let me show you how I'd do it.
The first thing is to determine the maximal height H(K) (of the skyscraper), which can be resolved in K drops. To do that, we shall observe, that the first drop must be done from exactly K 'th story (is it obvious?). Then, if the marble remains intact, we are left with K-1 tries and H(K)-K stories. Applying the same logic recursively, we end up with

H(k) = K + (K-1) + ... + 1

that is

H(K) = K*(K+1)/2

Solving for K gives the starting point for an H-story building.

nezachem 616 Practically a Posting Shark

Separate reading digits and constructing a number. Something like

int get_noisy_digit()
{
    int ch1, ch2;
    while((ch1 = getchar())!= EOF) {
        if(!IS_DIGIT(ch1))
            continue;
        if((ch2 = getchar()) == ch1)
            return ch1;
        ungetc(ch2);
    }
    return EOF;
}

That said, I doubt the protocol is any good.

nezachem 616 Practically a Posting Shark

.data, .bss, etc have nothing to do with the architecture. They represent the structure of an object file. They are linked differently; they are stored differently, they are loaded differently.

nezachem 616 Practically a Posting Shark

I want to know how my local static variable is in .data segment and my global static is in .bss specifically?
One of them ends up in .data, because it is initialized. Another one ends up in .bss because it is not (or, rather, initialized by 0).

and what about that peculiar .1784 naming in that local static variable...
This is how your compiler decided to mangle its name to take it out of the global scope.

nezachem 616 Practically a Posting Shark

Hi, i'm trying to learn some assembly, ive got a assignment from school to control a lcd screen. I've got some sample code that i mostly understand but i can't figure out what the SBI command does.
Using atmega32, with avr studio 4

sbi	PortD, LCD_E

At this point PortD = 32, and LCD_E = 0 (decimal)
After the sbi line PortD = 36

I don't see how he changes from 32 to 36.

.equ	LCD_E	= 2

Do you see now?

Salem commented: Very nice - +20
nezachem 616 Practically a Posting Shark

I wasn't implying full binary search, just a partial binary search.

The problem with even a partial binary search is that if the very first comparison fails (that is, a first marble breaks at the drop from N/2), you need to test the N/2 storeys with a single marble. This gives the worst case of N/2.

PS: You had a slightly different interpretation of the problem. You allow comparison to continue after 2 failures. This is essentially a 3 marble puzzle - which is interesting by itself.
So, having just 1 marble, the problem takes O(N) drops; with 2 marbles it is O(sqrt(N)). What is the asymptotic for 3 marbles? for k marbles?

nezachem 616 Practically a Posting Shark

First of all, malloc does not take up a stack. The memory comes from the completely different area.
Second, you have to realize that in modern OSes malloc only reserves a range of virtual addresses. A successful malloc does not guarantee that there would be enough physical memory by the time this range is accessed.
Third, you really allocate a lot; if I am calculating right, it is close 6Gb. Does your system have that much?
My only recommendation is to modify your algorithm; do not assume that there's room for everything, and keep most of the data off-RAM. Maybe swap will let you do it transparently.

nezachem 616 Practically a Posting Shark

So here is the algorithm I am trying to design...i'm not sure it will make any sense.
I have a sequence of n numbers(in ascending order). I have an another number 'x'. If i have 2 chances to compare x with a number greater than it but unlimited chances to compare with numbers lesser than it. Now I have to to find out the maximum possible value in the sequence that is less than x in the most efficient way. I know this looks a little contrived but the original question is different so I am looking for the direction I would need to go.

As an example..watch this..

I have a series from 1,2,3,4...............,19, 20.

Now I have a number x = 10.5

Now I have to find the maximum possible number "M" in the series such that M < x

The easiest way would be brute forcing ur way from the lowest possible number(they are in ascending order anyway.). As soon as the "less than comparison" fails, u have the solution. The worst case would 'n' comparisons. But we have two chances where we can fail the comparison. So a slightly better algorithm would be comparing the odd indexed numbers. So in the worst case scenario we have n/2 +1 comparisons which is better than the first.

So far so good. But you still underuse the second chance. Say, you work your way up with an increment of K. The worst case will give you (N/K) + …

nezachem 616 Practically a Posting Shark

Have you tried to do anything yet, I'd like to help but I won't do you program from start to finish. It looks like it could be solved using a 0-1 knapsack with slight modification for the heights changing as you pick. If you post some code you're working/stuck on I can try to help you. If you have nothing yet look up the 0-1 knapsack on wiki and at least you can get an idea of how to solve this.

Can you please elaborate on it? I don't see how this problem can be reduced to a knapsack. An essential property of a knapsack is its limited capacity, isn't it?

nezachem 616 Practically a Posting Shark

>>*(float*) variable = 34;

It is typcasting variable into a float *, then assigning the value 34 to it.

Correction: through it.

nezachem 616 Practically a Posting Shark
find . -name 'my*'

The quotes avoid the shell expansion - without them the shell would replace my* with the list of files whose names begin with my in the current directory.

What thus the above statement mean? Isn't it doing the same thing I mean looking for file names beginning with my?

Do an exercise:

touch my0
mkdir foo
touch foo/my1
find -name 'my*'
find -name my*

and compare results.

nezachem 616 Practically a Posting Shark

just run loops to increment their counter

So far so good.

that would be compared to the integers in the file, so it would be a typical code, like this:

// NOTE: dato is a pointer to a file

  for (x=1; x<=100;x++){
         freq=0;   
           for ( i=0; !feof( dato ) ; i++ ){
				fscanf( dato, "%d", &n );
				if (x==n) freq++;	
           }
       printf ("\n number %d appears %d times", x, freq);
    }

The problem is that I the only frequency result I get is 0. I know it's set to be 0 in the loop, but the value should be printed after each integer is checked and then reset to 0 at the beginning of the next x value, or am I wrong?

One immediate problem here is that after the very first iteration you've reached end of file, and nothing could be read anymore. That said, the approach is horrible.

...
Like I've said I tried the same thing with arrays, to get the loops compare the numbers in file with the ones in one dimensional array and store their frequency in another array, but then freq value is 149086 or something like that.

Most likely you forgot to initialize them. The array is a way to go. BTW, you don't need an array with numbers and comparison loop. A single array with frequencies will do it.

nezachem 616 Practically a Posting Shark

from wikipedia:

1.

find . -name "*.foo" -print0 | xargs -0 grep bar

The above command uses GNU specific extensions to find and xargs to separate filenames using the null character;

What is the null character? What is the significance of "separate filenames using the null character;"? why should we do that? Where is the null character specified?

Null character is a byte with a numerical value of 0 (all bits cleared).

By default, find separates the found filenames with a whitespace, which creates obvious problems if filenames have an embedded whitespace. However, it is not possible to have a filename with an embedded null character in it. Using 0 as a filename separator allows xargs to parse the find output unambiguously.

2.

find . -name "*.foo" -print0 | xargs -0 -t -r vi

first what is the significance of -r. second, after quitting from vi by :q
the shell hangs. There is a blinking cursor, but no keyboard input is accepted. It happened twice.

That was a very creative abuse of vi. Do not even know how to comment.

3.

find . -name "*.foo" -print0 | xargs -0 -I xxx mv xxx /tmp/trash

The above command uses string xxx instead of {} as the argument list marker.

But when I tried this:

find . -name "*.foo" -print0 | xargs -0 -I xxx mv xxx /tmp/

it gives:

mv: preserving permissions for `/tmp/minf.foo': Operation not supported
mv: preserving permissions for `/tmp/state.foo': Operation not supported

changing the I switch to i (as …

nezachem 616 Practically a Posting Shark

I guess i was just trying to see if someone could pose a rational explanation of why I shouldnt do it with gotos, and give an elegant alternative.

That would be extremely hard. Any rationale against goto stems this way or other from the original Dijkstra article. The point of the article is very valid, yet not applicable to this case. Your approach does not violate the sequentiality of the flow, period.

jephthah commented: well-put. i can live with that :) +7
nezachem 616 Practically a Posting Shark

yeah, i try not to jump between functions, this is just to get out of any single function cleanly in the case of a hardware error.

i guess im just soliciting opinions between doing it the first way (with gotos) or the second (without). or another way i havent considered. i'd rather not use gotos because of the stigma attached to them, but i'm not seeing a cleaner way at the moment.

I don't see anything wrong with gotos here. If you are forced to not use them, then in this particular case you can split the functionality into a worker function and a setup-cleanup wrapper, something along the lines of

int MyDriver_workerFunction(int whatever, char * something)
{
   int errCode = ERROR_CLEAR;   // zero (0) is no error
      if ((errCode = subfunction(val1, val2)) < 0) 
        return errCode;
      // ...
   
      for (port = 0; port < MAX_NUM_PORTS; port++)
      {
         if ((errCode = anotherfunction(port, &status)) < 0) 
            return errCode;

         switch(whatever)
            // ...
      }
      if ((errCode = somethingElse(command, response, something)) < 0) 
         return errCode;
   //...
    return errCode;
}
 int MyDriver_driverFunction(int whatever, char * something)
{
   errCode = MyDriver_workerFunction(whatever, something);
   if (errCode < 0)
      // hardware error-specific exit routines ...
   else 
      // standard exit routines ...

   return errCode;
}
nezachem 616 Practically a Posting Shark

Both snippets suffer the same problem. They do not update the one pointer (current->next->previous and current->previous->next respectively). The first snippet gives an impression of working because of the way you traverse the list. Try to traverse it in both directions and you will see the problem.

nezachem 616 Practically a Posting Shark

The code is not portable. It is very linux-specific. It uses termios, and it assumes that stdin is selectable.
Another problem is that it doesn't test the select error code. When select returns -1, the fds is undefined, and kbhit would return garbage.
Otherwise, it is a fairly standard way to achieve the goal, although I prefer a portable setvbuf(stdin, 0, _IONBF, 0) .

nezachem 616 Practically a Posting Shark

I doubt you can significantly speed these calculations up by "normal" means. Take a look at SIMD (aka SSE) capabilities of your very good computer.

nezachem 616 Practically a Posting Shark
printf("Enter word to add: ");	
		fflush(stdin);			
		fgets(word,9,stdin);
		fflush(stdin);			
		printf("Meaning : ");
		fflush(stdin);
		fgets(word,9,stdin);	
		add(word,meaning);

what i m trying is to input is two character arrays :-
1. word
2. meaning

1. the program only inputs the meaning and not the word.

You are reading into the same array twice. See highlighted.

2. the output when we reach that code is" Enter word to add: Meaning:"
and it will only input the meaning.

You need to fflush(stdout) , not stdin .

nezachem 616 Practically a Posting Shark

Sorry for the delay in response. Here is my code.

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

void main(int argc, char *argv[]){
	char * filename = argv[1];
	char t[sizeof(filename)+2] ;
	sprintf(t, "v=%s", filename);
	printf("%s\n",t);
	system(t);
	system("echo $v");

}

So far it creates the string correctly

Careful. sizeof(filename) is 4. You are heading to a segfault.

but it does not set the variable to anything.

Of course. Two invocations of system invoke different shells. The first one sets the variable, and dies. All changes you made to the environment are gone. Try

sprintf(cmdline, "v=%s; echo $v", filename);
    system(cmdline);