D33wakar 36 Posting Whiz in Training

Similar to echoserver, but this one handles multiple clients by forking the process.

D33wakar 36 Posting Whiz in Training

This is a simple echo server that I've written while learning sockets programming.
Compile the server and run it. You can connect to it using telnet like this:

telnet localhost 1337

Disconnect the client by typing "/quit" without quotes.

You are doing strange chain of action from init return through each methods return, which is very bizare for me. why not just do the sequence of calls in main program?

This is the same program without the class.

#!/usr/bin/env python

import random 
import cPickle

#path of the dump file
filepath = '/home/deewakar/python/hangman/wordsdict.pkl'

#inset some random hints for the player
def insert_hints(length, keylist, secret_word):
    randint = random.randint
    #if the word contains 7 or more letters, you'll get 3 hints
    if length >= 7: hints = 3
    else: hints = 1
    for x in xrange(hints):
        a = randint(1, length - 1)
        keylist[a-1] = secret_word[a-1]

    return hints, keylist

def test_input(guess, secret_word, keylist, mistakes, used_keys ):
    #if the guessed letter matches
    if guess in secret_word:
        indexes = [i for i, item in enumerate(secret_word) if item == guess]
        for index in indexes:
            keylist[index] = guess

    #if the guessed letter didn't match
        mistakes += 1
    print "used letters ",set(used_keys),'\n'

    return keylist, mistakes

#load the pickled word dictionary
def load_dict():
    try :
        dumpfile = open(filepath, "r")
    except IOError:
        print "Couldn't open the dictionary file 'wordsdict.pkl'"

    dictionary = cPickle.load(dumpfile)
    words = dictionary.keys()
    return dumpfile, dictionary, words

#randomly choose a word for the challenge
def prepare_word(words):
    secret_word = random.choice(words)
    #don't count trailing spaces
    length = len(secret_word.rstrip())
    keylist = ['_' for x in xrange(length)]
    hints, keylist = insert_hints(length, keylist, secret_word)
    return secret_word, keylist, hints

#display the challenge
def ask(keylist, secret_word, dictionary):
    print ' '.join(keylist), ":", dictionary[secret_word] 

#take input from the player
def input_loop(secret_word, mistakes, ...

Without the picled dictionary I can not run the program so that is how far I can comment now (zipped and attached File would help).

That was a serious mistake on my part.

D33wakar 36 Posting Whiz in Training

This is a simple hangman game that I wrote using my beginner python skills. Though this game is playable, there must be lots of things I must've been doing wrong or the methods I'm using here may be not so pythonic. So I want some suggestions on how to improve this game.
The 'wordsdict.pkl' file contains a pickled dict with words as keys and meanings as their values.

e.g. {'word': 'its meaning'}

And here's how you use strtok (you know... for future references).


int main(void){
char line[20] = "Process0 12 1"; // suppose this is the first line read by fgets
char delim=" ";
result = NULL;
if(result != NULL)
printf("process:%s\n",result);//store process in an array
result=strtok(NULL,delim);//first argument NULL except first call to strtok
printf("quanta:%s\n",result);//store quanta in another array,you can use atoi to change
//quanta to integer type

result=strtok(NULL,delim);//first argument NULL except first call to strtok
printf("priority:%s\n",result);//store priority in another array

return 0;

[QUOTE=Gribouillis;1728291]If you want to use s, write
s = [x for x in s if x!= 'r']


s = list(x for x in s if x!= 'r')
there is a small difference with s[:] because this code create a new list for the name s. With s[:] it only fills the same list object with new elements. For example try this
a = ['b','a','r','r','i','s','t','e','r']
b = a
c = a
b = [x for x in b if x != 'r']
print a
c[:] = [x for x in c if x != 'r']
print a

print id(a), id(b), id(c)
If you want to learn more about generator expressions, read about generators and the iterator protocol in the python documentation, but you can postpone this a little if you are new to python.[/QUOTE]
Thanks for the quick reply, I really appreciate it.

[QUOTE]Conclusion: don't modify the size of a list while iterating on this list, use a copy if necessary.[/QUOTE]yes using a copy solves the problem thank you but I have couple of questions about the second method.
If I understood correctly [CODE]s[:] = (x for x in s if x != 'r')[/CODE]means reconstruct the list s from the components of the list s itself (interating through them ) but skip the element 'r' right?
Also why can't we use just s instead of s[:].
[CODE]s=(x for x in s if x!= 'r')

<generator object at 0xa80ff54>

D33wakar 36 Posting Whiz in Training

If there's a list like below
and if I tried to remove every 'r' from the list like this
[CODE]>>> for x in s:
it gives the following result.
[CODE]>>> s
['b', 'a', 'i', 's', 't', 'e', 'r'][/CODE]
Why isn't the last 'r' removed from the list.

[QUOTE]The program runs and compiles. When I enter the two words, it gives me a bunch of random stuff when printing[/QUOTE]That's because scanf is not used like this
[URL="http://en.wikipedia.org/wiki/Scanf"]click here[/URL]



int main()
int count = 0;
char doc;

printf("Enter the file name: ");
scanf("%s", doc);

inp=fopen(doc, "r");

while((doc = fgetc(doc)) != EOF)
    if (doc == ' ')


printf("%s contains %d words\n",doc,count);

return 0;


So basically I'm a little bit confused. I believe the logic of my program is correct; file pointer is declared, and I do have a character to store my array, it reads the file, and counts all the words pending a space in front/between/etc. Basically the program should ask the used the used to input the name of the file they're scanning. The file opens and goes through the program and outputs a line that tells the user the # of words in the file that was inputted.

My problem has been compiling it.

I'm getting this:

wordcount.c: In function ‘main’:
wordcount.c:13:5: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:271:14: note: expected ‘const char restrict’ but argument is of type ‘char’
wordcount.c:15:5: warning: passing argument 1 of ‘fgetc’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:535:12: note: expected ‘struct FILE
’ but argument is of type ‘char’
wordcount.c:21:5: warning: passing argument 1 of ‘fclose’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:236:12: note: expected ‘struct FILE ’ but argument is of type ‘char’[/QUOTE]
The root of all problems in your program is this line[CODE] char
[B]Walt[/B] is ...

[QUOTE]anyone can tell me what this line does?[/QUOTE]clearly, it's returning the uppercase of the character given to the function.The first return statement only works if the condition cl>='a'(i.e.97 in decimal) AND cl<='z'(i.e 122 in decimal).If it does so then the second return statement is not executed, but if it does not then the second return statement is executed and returns whatever character was given to the function.So if you give any upper case characters or symbols then they will be returned unchanged.But if you give any lower case characters, let's suppose 'b'
then this line [CODE]return ('A' + c1 - 'a'); [/CODE]looks like this
[CODE]return (65+98-97);
this [URL="http://www.asciitable.com/"]ascii table[/URL] might help you further.
have a lovely day!

[QUOTE]The case choices does not run after the input of the integers 0 or 1.[/QUOTE]
You're missing '&'before 'choice' in your 'scanf' statement .
and another(important!) thing,look at this
[CODE]int number, integer,choice;
int ArrayN[20];

printf("Enter 20 Integers\n");
scanf("%d", &number);
printf("ArrayN[%d]=%d\n",i,number);//well, that's stupid!
You have to assign values to the array
[CODE]scanf("%d",&Array[i]);//like this
// ..or like this
Good Luck! with the rest of the code for searching and all that.

[QUOTE]Can you tell me why use size_t and not int for orig_len and rep_len?[/QUOTE]
Using size_t instead of just plain int or unsigned int makes your code more portable since the size of int types vary across platforms.
Also the above standard functions expect their third argument to be of size_t type.
[CODE]char stpncpy(char restrict s1, const char restrict s2, size_t n);
int strncmp(const char
s1, const char *s2, size_t n);[/CODE]

First of all, use code tags whenever you post any code.See that CODE thingy, click that and paste your well formatted code in between.

There's no use of this #include<conio.h>in your code and why this char studentanswer[30][30+1]; why not just declare it like this

char studentanswer[30][31];

Since you're opening the file 'examdat.txt' for reading, make sure that it is in the same directory as your program is or use the full path.

int status = fgetAnswers(&numberofstudent, ans, inp); You are passing arguments without assigning any values to them.

[QUOTE][CODE]fflush(stdin);[/CODE][/QUOTE]Didn't you read my previous post ? How many times do I have to tell you that you should not use fflush() with stdin.In the c standards, it is only defined to use with the output streams.
[QUOTE]I have another problem with the following program I have tried which tests if sides form a right angled triangle or not. [/QUOTE]First of all, if you have another problem and the current problem is resolved then you should mark this thread URL="http://www.daniweb.com/community-center/daniweb-community-feedback/threads/226710"]"solved"[/URL] and open another thread with the new problem.[QUOTE]First of all, is there any unnecessary repetition? [/QUOTE]Actually, that's your job to figure it out since you know your level of expertise and how compact you need your program to be.You can use functions to make it more short and compact.
[QUOTE]Is there any simple way by which I can add a reply feature to the program?
[/QUOTE]That is as simple as you can get.[CODE]if(Condition)
printf("something else");[/CODE]

[QUOTE]oh I get the point then. So, in other words it fflush can be used instead of always creating a double getchar() in the end of each prog. [/QUOTE]
No, you don't. I've already said that fflush() should not be used with input streams, it is made to use with output streams only.People usually use getchar() at the end to consume the data that might be left in the input buffer. That could be replaced with this[CODE]while (((ch = getchar()) != '\n') && (ch != EOF))//has no body ;[/CODE]But still at least a character is left in the buffer.

[QUOTE]I see where Diwakar has made several test submissions. Any new idea's you're trying, Diwakar? [/QUOTE]No, I just couldn't believe it was showing "time limit exceeded " for the code I submitted.But yes,I tweaked it a little bit,didn't help much.I replaced the multiplications with bit shifts, did a little work to reduce the redundancy during marking off composites and printed the primes at a tab distance rather than one at each line.
[CODE]void sive(int size) {
int i,j,k,l;
char sieve = calloc(size, 1);
for (i=2,k=1,l=2; i
i <= size; i=(k<<1)+1,k++,l=i<<1) {
if (!sieve[i]) {
for(j = i*i; j < size; j+=l) {sieve[j]=1; }
for (i=2,j=0; i<size; i++) {
if (!sieve[i]) { sieve[j++]=i; }

}[/CODE]But I'm not out of ideas yet.You may have seen guys mentioning Segmented sieve in the forum there.I haven't understood the concept thoroughly, though I have read about it couple of times but you know all those mathematical symbols drive me nuts.I remember someone wrote on one of the other forums that you first produce a list of primes within a small range and use those primes intelligently to produce other larger primes.Hmm, what does that mean?
And also about the Sieve of Eratosthenes, We're now using a whole integer (of the 'sieve' array) to represent a bit that marks composite, instead can we use just a single bit to represent that.
Once, I was very fascinated by the [URL="http://en.wikipedia.org/wiki/Wheel_factorization"]Wheel Factorization[/URL], later I came to know that the numbers produced by the method are ...

[QUOTE]Am i correct if I understand I/O buffer
as the temporary memory stored/inputted in the variables? [/QUOTE]
see [URL="http://en.wikipedia.org/wiki/Data_buffer"]here[/URL].[QUOTE].but what is its use here?[/QUOTE]Just to make sure that everything in the buffer is written immediately after you call printf and not after sometimes when you're taking inputs from the user. Believe me it happens(or may not,it depends on the compiler you're using or the system you're running on), usually when you're trying to take inputs and give outputs subsequently.This happens because buffers are flushed out only when they're full or a newline is encountered or fflush() is called.

[QUOTE]This is a piece of code from some book.[/QUOTE]Is that [URL="http://www.daniweb.com/software-development/c/threads/389911/1679633#post1679633"]the same book[/URL] Narue told you to burn ?
[CODE]int fun (const union employee e);
union employee
char name[15];
int age;
float salary;
};[/CODE]You should declare the union first and then the function 'fun'.
[CODE]union employee{
char name[15];
int age;
float salary;
int fun (const union employee
);//in function prototypes, you only mention the argument type[/CODE]
[CODE]void main()//so wrong[/CODE]According to the standards, main() returns an int type[CODE]int main(void)[/CODE]
[QUOTE]but this code is running on turbo C giving just a error message of const to * conversion ????? please tell me whether this code is right ??????[/QUOTE]How could that be?If the compiler issues an error message then the code should not have compiled in the first place.And yes the code is wrong!If you have used 'const' Type qualifiers then that means that you're declaring them as constants and they should not be modified during runtime.
Quote drom c-faq.com
[QUOTE]A const value is one you promise not to modify. The compiler may therefore be able to make certain optimizations, such as placing a const-qualified variable in read-only memory. However, a const-qualified variable is not a true constant; that is, it does not qualify as a constant expression which C requires in certain situations, such as array dimensions, case labels (see section 18.3.1 below), and initializers for variables with static duration (globals and static locals). [/QUOTE]
Quote from linux man page
[QUOTE]const is used to tell the compiler that the data ...

[ICODE]'fflush(stdout)'[/ICODE] forces the data (if any)in the I/O buffer to be written to the screen .Including a '\n' character(if suitable) in the [ICODE]'printf'[/ICODE] itself also does the same thing.[CODE]printf("incorrect value\n");[/CODE]Remember that [ICODE]fflush[/ICODE] is only used with output streams.Calling [ICODE]fflush[/ICODE] with [ICODE]NULL [/ICODE]argument flushes all the opened streams.

[QUOTE]Every call to printf() incurs a small expense, because printf() can decode a boatload of formats, etc.[/QUOTE]Yeah,I couldn't agree with you more.[QUOTE]Second topic:

Just an idea, completely untested.

What if we took in ALL the queries from the tester, into an array, and quickly sorted them (time: maybe 0.2-1.0 seconds). Then we start the prime finding loop, and as soon as we find one, (in Sieve loop), that matches the next request, we print it solo, just that one number and newline.***[/QUOTE]
Now we're talking! That's a brilliant idea. I wondered, why would you need the number of queries in the input at first, since you're given all the numbers for which you have to find the primes for.Now I know, you're supposed to use that in your code, it's like a hint right? [QUOTE]Maybe print out 512 numbers with each call to printf()?[/QUOTE]Hmm, interesting!
[QUOTE]@Diwakar, I inserted part of your sieve loop (the nested for loop at the bottom of it), and found I wasn't getting all the prime numbers - lots of them, but not all. You may want to check it (but it could be just the interaction between my loop logic, and yours, in the top half of the larger loop). [/QUOTE]It may be possible since i haven't tested it for all five million! But until now it has been giving correct answers.I'll check that and inform you later.
By the way, your quicksort looks fast, I'll give that a try too.

[QUOTE]I guess it just adds ret statement and pops whatever is in the eax register. [/QUOTE]Sorry, there was a typo in the above line. I mean,pops whatever is in the [B]stack to the[/B] eax register(i.e.last pushed value).

I guess it just adds[ICODE] ret[/ICODE] statement and pops whatever is in the [ICODE]eax[/ICODE] register.

[QUOTE]Then why it is not giving any warning with [CODE]gcc -o test_cal test_cal.c[/CODE][/QUOTE]Well that's not mine (or gcc's) problem, it's your job to follow good programming practices.

The answer is in your error message
[CODE]cc1: warnings being treated as errors
test_cal.c: In function ‘calsum’:
test_cal.c:20: error: control reaches end of non-void function[/CODE]Since function calsum is non-void(means returns something), so you should add a return statement.
[CODE]return d;[/CODE]

It's a very , very messy code.Here are few things that I saw, that could be potentially causing the problem.
1.You have named many things "Information".First the struct for book data[CODE]/Structure for book information /
typedef struct Information
char subject [MAXIMUM_TITLE];
char author [MAXIMUM_AUTHOR];
int edition;
int year;
float price;
} Book;[/CODE] and then this[CODE]static Book Information;[/CODE]I don't know what's that for.And finally a pointer to Book to use with malloc.[CODE]Information = (Book ) malloc(book_number sizeof(Information)); [/CODE]
2.you are allocating space dynamically for a pointer variable.[CODE]Information = (Book
) malloc(book_number sizeof(Information)); [/CODE]should be replaced with this:[CODE]Information = (Book ) malloc(book_number * sizeof(Book)); [/CODE]I guess, you have to replace all the 'Information's with 'Book's in the code that follows.
3.At least the code should be syntactically correct, then it will be easy to find the bugs that aren't caught by the compiler. for e.g. see this declaration[CODE]Book getBookInformation(int inventory);//if returns nothing, return 'void'[/CODE]But see the definition of the function 'getBookInformation', it returns nothing.
I hope above things will help you fix your code,and in addition don't ignore compiler warning messages, they could be very helpful while debugging your code.
P.S. may be compiling them as a single source at first, may be less tiresome and less time consuming and then you can distribute them in multiple files afterwards.

[QUOTE=Adak]CSE, do you submit code or is it an executable file that gets tested?[/QUOTE]No,you just have to submit your code.
I compiled and ran your both programs and it took about 16 seconds for the version with direct numbers and about 13 seconds for the version with char array( intel core 2 duo, 2.22 GHz).The chars version was not accepted by my ide, so I had to build it in the command line.
Then I submitted the program I was working on( after editing a little bit),

define SIZE 86028122

int arr[5000000]={0};

void sieve(int size) {
int i,j,k;
char sieve = calloc(size, 1);
for (i=2,k=1; i
i <= size; i=k2+1,k++) {
if (!sieve[i]) {
for(j = i
i; j < size; j=j+i) {sieve[j]=1; }
for (i=2,j=0; i<size; i++) {
if (!sieve[i]) { arr[j++]=i; }


int main(void) {


char number[15],*file=NULL;
int n,flag=0;
while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){



   return 0;

[/CODE]I submitted it because, it was taking about 4.79 seconds on my PC and only 2.26 seconds on [URL="www.ideone.com"]ideone[/URL] which the site recommends to test your code.But it shows time limit exceeded whenever I submit it to [URL="http://www.spoj.pl"]the site [/URL]itself.Frustrating, isn't it?
[QUOTE=cse.avinash]2)Take 1 as test case it will not take any input.
that's why its giving wrong answer. [/QUOTE] But I was reading the input from a file, otherwise how else would you give this kind of input:[CODE]8

[QUOTE]The code compiles[/QUOTE]That totally amazes me.[QUOTE] but when I run the program it stops responding once it enters the while loop [/QUOTE]So there's a strong possibility that the problem lies on your while loop statement.
[QUOTE][CODE] while (fgetc(inFile) != EOF) != NULL) {[/CODE][/QUOTE]'fgetc' returns EOF when read error occurs or the EOF is reached.So this is enough[CODE]while(fgetc(inFile)!=EOF)[/CODE]But wait a minute, the file pointer you declared has a name 'inputFile'.Also that you're using fgetc just to detect the EOF seems a bad idea to me.Instead just read the whole line at a time and extract the information you need one by one.

Alright guys, I registered in to that site and submitted the following code, but it didn't accept the code as a valid answer.The time taken by the code I submitted was 1.23 as shown in the site.

define SIZE 50000000

int arr[SIZE]={0};

void sieve(int size) {
int i,j,k;
char sieve = calloc(size, 1);
for (i=2,k=1; i
i <= size; i=k2+1,k++) {
if (!sieve[i]) {
for(j = i
i; j < size; j=j+i) {sieve[j]=1; }
for (i=2,j=0,k=1; i<size; i++) {

   if (!sieve[i]) { arr[j++]=i; }

int main() {


char number[15],*file;
int n,flag=0;
while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){



   return 0;

[/CODE] That means my interpretation of the challenge was wrong.But what else could it be?