diff --git a/.gitignore b/.gitignore
index eed432eb..9e37a517 100644
--- a/.gitignore
+++ b/.gitignore
@@ -400,3 +400,4 @@ Module.symvers
Mkfile.old
dkms.conf
+.idea/
diff --git a/.readthedocs.yml b/.readthedocs.yml
deleted file mode 100644
index b843136e..00000000
--- a/.readthedocs.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-# .readthedocs.yml
-# Read the Docs configuration file
-# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
-
-# Required
-version: 2
-
-# Build documentation in the docs/ directory with Sphinx
-sphinx:
- configuration: source/conf.py
-
-# Build documentation with MkDocs
-#mkdocs:
-# configuration: mkdocs.yml
-
-# Optionally build your docs in additional formats such as PDF and ePub
-formats: []
-
-# Optionally set the version of Python and requirements required to build your docs
-python:
- version: 3.7
- install:
- - requirements: source/requirements.txt
-
diff --git a/LICENSE b/LICENSE
index 39bdc1cb..471fbc92 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2016, Senthil Kumaran
+Copyright (c) 2024, Senthil Kumaran
All rights reserved.
diff --git a/Makefile b/Makefile
index 70f793fb..81a2da1c 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,4 @@
# Makefile for Sphinx documentation
-#
# You can set these variables from the command line.
SPHINXOPTS =
@@ -27,7 +26,6 @@ help:
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
- @echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
@@ -112,8 +110,3 @@ linkcheck:
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
-
-doctest:
- $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
- @echo "Testing of doctests in the sources finished, look at the " \
- "results in $(BUILDDIR)/doctest/output.txt."
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..7acf7011
--- /dev/null
+++ b/README.md
@@ -0,0 +1,24 @@
+# https://learntosolveit.com
+
+[https://learntosolveit.com](https://learntosolveit.com) is a website to learn C programming using K&R book. It uses modern tools, and is designed to be used along with the book.
+
+I recommend [https://exercism.org](https://exercism.org) as the platform to
+learn programming, including C, and practice with a community of intrinsically
+motivated developers.
+
+### References
+
+* C Programming Language by Kernighan and Ritchie.
+* https://github.com/jflaherty/ptrtut13/blob/master/md/ch1x.md
+* https://manual.cs50.io/
+
+
+[](https://app.netlify.com/sites/learntosolveit/deploys)
+[](http://www.learntosolveit.com/?badge=latest)
+
+
+## Author
+
+* Senthil Kumaran
+* Email: [senthil@uthcode.com](mailto:senthil@uthcode.com)
+* Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com)
diff --git a/README.rst b/README.rst
deleted file mode 100644
index bb0bff67..00000000
--- a/README.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-Learn To Solve It
-=================
-
-Please visit https://exercism.org to "Learn To Solve It" using your favorite programming language.
-
-.. image:: https://readthedocs.org/projects/learntosolveit/badge/?version=latest
- :target: https://www.learntosolveit.com/?badge=latest
- :alt: Documentation Status
-
-
-For the suggest-improve and better-explain C programming contents
-
-::
-
- :c-suggest-improve:`filename.c`
- :c-better-explain:`filename.rst`
-
-
-Dependencies
-------------
-
-* https://github.com/sphinx-doc/sphinx/
-
-
-Contact
--------
-
-* Senthil Kumaran
diff --git a/languages/cprogs/CMakeLists.txt b/languages/cprogs/CMakeLists.txt
deleted file mode 100644
index 4915b8ca..00000000
--- a/languages/cprogs/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-cmake_minimum_required(VERSION 3.6)
-project(learntosolveit)
-
-set(CMAKE_C_STANDARD 11)
-
-set(SOURCE_FILES Ex_1.14_Hist_Freq.c)
-add_executable(learntosolveit ${SOURCE_FILES})
\ No newline at end of file
diff --git a/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c b/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c
index 2c59024e..e06534e3 100644
--- a/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c
+++ b/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c
@@ -7,11 +7,22 @@
#include
+const char *input = "This\tis\ta\b\btest\tstring.";
+int input_index = 0;
+
+int _getchar(void) {
+ if (input[input_index] == '\0') {
+ return EOF;
+ } else {
+ return input[input_index++];
+ }
+}
+
int main(void)
{
int c;
- while((c = getchar()) != EOF)
+ while((c = _getchar()) != EOF)
{
if(c == '\t')
{
diff --git a/languages/cprogs/Ex_1.8_count_blanks_etc.c b/languages/cprogs/Ex_1.8_count_blanks_etc.c
index 5f59bd67..4ca14c52 100644
--- a/languages/cprogs/Ex_1.8_count_blanks_etc.c
+++ b/languages/cprogs/Ex_1.8_count_blanks_etc.c
@@ -6,6 +6,16 @@
#include
+const char *input = "This\tis\ta\ttest\\string\bwith\ttabs\\and\\backspaces.\n\nnewline";
+int input_index = 0;
+
+int _getchar(void) {
+ if (input[input_index] == '\0') {
+ return EOF;
+ } else {
+ return input[input_index++];
+ }
+}
int main()
{
@@ -13,7 +23,7 @@ int main()
blanks = tabs = newlines = 0;
- while ((c = getchar()) != EOF) {
+ while ((c = _getchar()) != EOF) {
if (c == ' ')
++blanks;
if (c == '\t')
diff --git a/languages/cprogs/Ex_1.9_SinBlank.c b/languages/cprogs/Ex_1.9_SinBlank.c
index 28551142..b04acd53 100644
--- a/languages/cprogs/Ex_1.9_SinBlank.c
+++ b/languages/cprogs/Ex_1.9_SinBlank.c
@@ -6,6 +6,19 @@
#include
+const char *input = "This line has many blanks to be replaced by single blank";
+int input_index = 0;
+
+int custom_getchar(void) {
+ if (input[input_index] == '\0') {
+ return EOF;
+ } else {
+ return input[input_index++];
+ }
+}
+
+
+
#define NONBLANK '-'
int main(void)
@@ -14,7 +27,7 @@ int main(void)
lastc = NONBLANK;
- while((c = getchar()) != EOF)
+ while((c = custom_getchar()) != EOF)
{
if(c == ' ')
{
diff --git a/languages/cprogs/Ex_4.3_rpn_modulus_negative.c b/languages/cprogs/Ex_4.3_rpn_modulus_negative.c
index 1858ce2a..70f97bab 100644
--- a/languages/cprogs/Ex_4.3_rpn_modulus_negative.c
+++ b/languages/cprogs/Ex_4.3_rpn_modulus_negative.c
@@ -1,142 +1,127 @@
-/* Adding the Modulus operator and provision for negative numbers
-* Program is given the input in a single and and it print the output upon
-* getting a \n character.
-* For e.g:
-*
-* 10 10 + 100 + 2 *
-* 240
-*/
+/** In the RPN calculator, add the modulus operator and provision for negative
+ * numbers.
+ * Program is given the input in a single and and it print the output upon
+ * getting a \n character.
+ *
+ * For e.g:
+ *
+ * 10 10 + 100 + 2 *
+ * 240
+ */
-#include
-#include
-#include
+#include
+#include
+#include
+#include
+
+
+#define BUFSIZE 100
#define MAXOP 100
+#define MAXVAL 100
#define NUMBER '0'
-int getop(char []);
+int getop(char[]);
void push(double);
double pop(void);
+int getch(void);
+void ungetch(int);
-/* reverse polish calculator */
-
-int main(void)
-{
- int type;
- double op2;
- char s[MAXOP];
-
- while((type = getop(s)) != EOF)
- {
- switch(type)
- {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop()+pop());
- break;
- case '*':
- push(pop()*pop());
- break;
- case '-':
- op2 = pop();
- push(pop()-op2);
- break;
- case '/':
- op2 = pop();
- if(op2 != 0.0)
- push(pop()/op2);
- else
- printf("error:zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if(op2 != 0.0)
- push(fmod(pop(),op2));
- else
- printf("erro:zero divisor\n");
- break;
- case '\n':
- printf("\t%.8g\n",pop());
- break;
- default:
- printf("error: unknown command %s\n",s);
- break;
-
- }
- }
- return 0;
-}
-
-
-#define MAXVAL 100
-
+int bufp = 0;
int sp = 0;
+char buf[BUFSIZE];
+
double val[MAXVAL];
-void push(double f)
-{
- if(sp < MAXVAL)
- val[sp++]=f;
- else
- printf("error:stack full, cant push %g\n",f);
+void push(double f) {
+ if (sp < MAXVAL)
+ val[sp++] = f;
+ else
+ printf("error:stack full, cant push %g\n", f);
}
-
-double pop(void)
-{
- if(sp>0)
- return val[--sp];
- else
- {
- printf("error: stack empty\n");
- return 0.0;
- }
+double pop(void) {
+ if (sp > 0)
+ return val[--sp];
+ else {
+ printf("error: stack empty\n");
+ return 0.0;
+ }
}
-#include
-
-int getch(void);
-void ungetch(int);
-
int getop(char s[]) {
- int i, c;
- while ((s[0] = c = getch()) == ' ' || c == '\t')
- ;
- s[1] = '\0';
- if (!isdigit(c) && c != '.' && c != '-')
- return c; // not a number
- i = 0;
- if (c == '-' || isdigit(c)) // collect integer part along with '-'
- while (isdigit(s[++i] = c = getch()))
- ;
- if (c == '.') // collect fraction part
- while (isdigit(s[++i] = c = getch()))
- ;
- s[i] = '\0';
- if (c != EOF)
- ungetch(c);
- if (strcmp(s, "-") == 0)
- return '-';
- return NUMBER;
+ int i, c;
+ while ((s[0] = c = getch()) == ' ' || c == '\t')
+ ;
+ s[1] = '\0';
+ if (!isdigit(c) && c != '.' && c != '-')
+ return c; // not a number
+ i = 0;
+ if (c == '-' || isdigit(c)) // collect integer part along with '-'
+ while (isdigit(s[++i] = c = getch()))
+ ;
+ if (c == '.') // collect fraction part
+ while (isdigit(s[++i] = c = getch()))
+ ;
+ s[i] = '\0';
+ if (c != EOF)
+ ungetch(c);
+ if (strcmp(s, "-") == 0)
+ return '-';
+ return NUMBER;
}
-#define BUFSIZE 100
-
-char buf[BUFSIZE];
-int bufp = 0;
+int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
-int getch(void)
-{
- return (bufp > 0) ? buf[--bufp] : getchar();
+void ungetch(int c) {
+ if (bufp >= BUFSIZE)
+ printf("ungetch: too many characters\n");
+ else
+ buf[bufp++] = c;
}
-void ungetch(int c)
-{
- if(bufp >= BUFSIZE)
- printf("ungetch: too many characters\n");
- else
- buf[bufp++] = c;
+/* Reverse Polish Calculator */
+int main(void) {
+ int type;
+ double op2;
+ char s[MAXOP];
+
+ while ((type = getop(s)) != EOF) {
+ switch (type) {
+ case NUMBER:
+ push(atof(s));
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ else
+ printf("error:zero divisor\n");
+ break;
+ case '%':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(fmod(pop(), op2));
+ else
+ printf("erro:zero divisor\n");
+ break;
+ case '\n':
+ printf("\t%.8g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
+ }
+ }
+ return 0;
}
-
diff --git a/languages/cprogs/Ex_5.14_sortrevnum.c b/languages/cprogs/Ex_5.14_sortrevnum.c
index fde3e4a1..897f865d 100644
--- a/languages/cprogs/Ex_5.14_sortrevnum.c
+++ b/languages/cprogs/Ex_5.14_sortrevnum.c
@@ -48,7 +48,7 @@ int main(int argc,char *argv[])
if(option & NUMERIC)
myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))numcmp);
else
- myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))numcmp);
+ myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))strcmp);
writelines(lineptr,nlines,option & DECR);
}
else
diff --git a/languages/cprogs/Ex_5.17_sortdfnr-withoption.c b/languages/cprogs/Ex_5.17_sortdfnr-withoption.c
index d4f7e269..d796e651 100644
--- a/languages/cprogs/Ex_5.17_sortdfnr-withoption.c
+++ b/languages/cprogs/Ex_5.17_sortdfnr-withoption.c
@@ -3,6 +3,7 @@
#include
#include
+#include
#define NUMERIC 1 /* numeric sort */
#define DECR 2 /* sort in decreasing order */
@@ -15,7 +16,7 @@ void error(char *);
int numcmp(char *,char *);
void readargs(int argc,char *argv[]);
int readlines(char *lineptr[],int maxlines);
-void mqsort(void *v[],int left,int right,int (*comp)(void *,void *));
+void myqsort(void *v[],int left,int right,int (*comp)(void *,void *));
void writelines(char *lineptr[],int nlines,int order);
int option = 0;
@@ -57,7 +58,6 @@ int main(int argc,char *argv[])
void readargs(int argc,char *argv[])
{
int c;
- int atoi(char *);
while(--argc > 0 && (c=(*++argv)[0])=='-' || c == '+')
{
@@ -177,7 +177,7 @@ void error(char *);
/* substr: get a substring of S and put in str */
-void substr(char *s,char *str)
+void substr(char *s,char *str, int maxstr)
{
int i,j,len;
extern int pos1,pos2;
@@ -258,7 +258,7 @@ int readlines(char *lineptr[],int maxlines)
}
/* writelines: write output lines */
-void writelines(char *lineptr[],int nlines)
+void writelines(char *lineptr[],int nlines, int order)
{
int i;
@@ -296,7 +296,7 @@ int mgetline(char s[],int lim)
{
int c,i;
- for(i=0;i
#include
#include
-enum { NAME,PARENS,BRACKETS };
-enum { NO, YES };
+#define MAXTOKEN 100
+
+enum {NAME,PARENS,BRACKETS};
+enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);
int gettoken(void);
-extern int tokentype; /* type of last token */
-extern char token[]; /* last token string */
-extern char name[]; /* identifier name */
-extern char out[];
+int tokentype; /* type of last token */
+char token[MAXTOKEN]; /* last token string */
+char name[MAXTOKEN]; /* identifier name */
+char out[1000];
+char datatype[MAXTOKEN];
extern int prevtoken;
+extern int tokentype;
+extern char token[];
+int prevtoken = NO;
-
-/* dcl: parse a declarator */
-void dcl(void)
-{
- int ns;
-
- for(ns = 0; gettoken() == '*';) /* count *'s */
- ns++;
-
- dirdcl();
-
- while(ns-- > 0)
- strcat(out,"pointer to");
-}
-
-
-/* dirdcl: parse a direct declaration */
-void dirdcl(void)
+int main(void)
{
- int type;
-
- if(tokentype == '(' )
- {
- dcl();
-
- if(tokentype != ')')
- errmsg("error: missing ) \n");
+ int i;
+
+ if(gettoken()!=EOF)
+ {
+ strcpy(datatype,token);
+ out[0]='\0';
+ dcl();
+
+ if(tokentype != '\n')
+ printf("syntax error \n");
+
+ printf(" %s %s %s \n",name,out,datatype);
+ for(i=0;i
-#include
+/* dcl: parse a declarator */
-/* enum { NAME,PARENS,BRACKETS}; */
-/* enum { NO,YES }; */
-
-extern int tokentype; /* type of last token */
-extern char token[]; /* last token string */
-int prevtoken = NO;
-
-/* gettoken : return next token */
-
-int gettoken(void)
+void dcl(void)
{
- int c,getch(void);
- void ungetch(int);
+ int ns;
- char *p = token;
-
- if(prevtoken == YES)
- {
- prevtoken = NO;
-
- return tokentype;
- }
+ for(ns=0;gettoken()=='*';) /* count *'s */
+ ns++;
- while((c=getch()) == ' ' || c == '\t')
- ;
+ dirdcl();
+ while(ns-- > 0)
+ strcat(out," pointer to");
+}
- if(c == '(')
- {
- if((c = getch()) == ')')
- {
- strcpy(token,"()");
- return tokentype = PARENS;
- }
- else
- {
- ungetch(c);
- return tokentype = '(';
- }
- }
- else if (c == '[')
- {
- for(*p++ = c; ( *p++ = getch()) != ']';)
- ;
- *p ='\0';
+/* dirdcl: parse a direct declarator */
- return tokentype = BRACKETS;
- }
- else if (isalpha(c))
- {
- for(*p++ = c; isalnum(c=getch()); )
- *p++ = c;
-
- *p = '\0';
-
- ungetch(c);
- return tokentype = NAME;
- }
- else
- return tokentype = c;
+void dirdcl(void)
+{
+ int type;
+
+ if(tokentype == '(') /* dcl */
+ {
+ dcl();
+
+ if(tokentype != ')')
+ errmsg("error: missing ) \n");
+ }
+ else if(tokentype == NAME) /* variable name */
+ strcpy(name,token);
+ else
+ errmsg("error: expected name or (dcl) \n");
+
+ while((type=gettoken()) == PARENS || type == BRACKETS )
+ if((type = PARENS))
+ strcat(out,"function returning");
+ else
+ {
+ strcat(out," arg");
+ strcat(out,token);
+ strcat(out," of");
+ }
}
-#define BUFSIZE 100
+void errmsg(char *msg)
+{
+ printf("%s", msg);
+ prevtoken = YES;
+}
+#define BUFSIZE 100
-char buf[BUFSIZE]; /* buffer for ungetch */
-int bufp = 0; /* next free position in buf */
+char buf[BUFSIZE]; /* buffer for ungetch */
+int bufp = 0; /* next free position in buf */
-int getch(void) /* get a (possibly pushed back) character */
+int getch(void) /* get a (possibly pushed back) character */
{
- return (bufp > 0) ? buf[--bufp]: getchar();
+ return (bufp > 0) ? buf[--bufp]:getchar();
}
-void ungetch(int c)
+void ungetch(int c) /* push a character back on input */
{
- if ( bufp >= BUFSIZE)
- printf("ungetch: too many characters \n");
- else
- buf[bufp++] = c;
+ if(bufp >= BUFSIZE)
+ printf("ungetch: too many characters \n");
+ else
+ buf[bufp++] = c;
}
-
diff --git a/languages/cprogs/Ex_5.1_getint.c b/languages/cprogs/Ex_5.1_getint.c
index de97f9ff..e80f1cda 100644
--- a/languages/cprogs/Ex_5.1_getint.c
+++ b/languages/cprogs/Ex_5.1_getint.c
@@ -59,11 +59,9 @@ int getint(int *pn)
int main(void)
{
- int n,s,array[SIZE],getint(int *);
+ int n,s,array[SIZE];
- for(n=0;n=0;n--)
- printf("%f",array[n]);
-
+ {
+ for(;n>=0;n--)
+ printf("%f\n",array[n]);
+ }
return 0;
}
diff --git a/languages/cprogs/Ex_5.4_strend.c b/languages/cprogs/Ex_5.4_strend.c
index c093df10..8c042840 100644
--- a/languages/cprogs/Ex_5.4_strend.c
+++ b/languages/cprogs/Ex_5.4_strend.c
@@ -1,4 +1,5 @@
#include
+
#define MAXLINE 1000
int mgetline(char s[],int max);
diff --git a/languages/cprogs/Ex_5.5_strncpy.c b/languages/cprogs/Ex_5.5_strncpy.c
index f75719f2..342f6089 100644
--- a/languages/cprogs/Ex_5.5_strncpy.c
+++ b/languages/cprogs/Ex_5.5_strncpy.c
@@ -18,7 +18,7 @@ void mystrncpy(char *, char *, int);
void mystrncat(char *, char *, char *, int);
int mystrncmp(char *, char *, int);
-int mystrlen(char *s);
+int mystrnlen(char *s);
int main(int argc, char *argv[])
{
@@ -77,7 +77,7 @@ void mystrncpy(char *dest,char *source,int n)
int extra = mystrnlen(dest) - n;
while (extra-- > 0) {
- *dest++;
+ dest++;
}
*dest = '\0';
diff --git a/languages/cprogs/Ex_5.7_readlines_using_array.c b/languages/cprogs/Ex_5.7_readlines_using_array.c
index 11417f62..eedaf555 100644
--- a/languages/cprogs/Ex_5.7_readlines_using_array.c
+++ b/languages/cprogs/Ex_5.7_readlines_using_array.c
@@ -43,9 +43,10 @@ int readlines(char *lineptr[],char *linestor,int maxlines)
char line[MAXLEN];
char *p = linestor;
char *linestop = linestor + MAXSTOR;
+ char c;
nlines=0;
-
+loop:
while((len=mgetline(line,MAXLEN)) > 0)
if(nlines >= maxlines || p+len > linestop)
return -1;
@@ -55,8 +56,14 @@ int readlines(char *lineptr[],char *linestor,int maxlines)
strcpy(p,line);
lineptr[nlines++]=p;
p+=len;
+ printf("get a newline? 0 for no, ENTER to input next line.");
+ c = getchar();
+ if(c != '0')
+ goto loop;
+ else if(c == '0')
+ return nlines;
}
- return nlines;
+ return 0;
}
/* writelines: write output lines */
@@ -128,4 +135,3 @@ int mgetline(char *s,int lim)
return s-t;
}
-
diff --git a/languages/cprogs/Ex_6.3.c b/languages/cprogs/Ex_6.3.c
index 6d648b6d..ee0dd3e1 100644
--- a/languages/cprogs/Ex_6.3.c
+++ b/languages/cprogs/Ex_6.3.c
@@ -1,316 +1,249 @@
/*
- * Write a cross-referencer that prints a list of all words in a document, and for each word, a list of the line numbers
- * on which it occurs. Remove noise words like "the" and "and" so on.
+ * Write a cross-referencer that prints a list of all words in a document,
+ * and for each word, a list of the line numbers on which it occurs.
+ * Remove noise words like "the" and "and" so on.
*
*/
-
/*
- * 1. Add all the word structures (word structure will have word and line numbers to the tree.
- * 2. A word can occur in more than one line, if the same word is found and the new line number to the line numbers.
- * 3. So line numbers should be a linked list of numbers.
- * 4. Print it.
+ * 1. Create a binary tree that will contain words and structure with lines on which words occur.
+ * 2. Check if the word is noisy with binary search.
+ * 3. Print the words and lines.
* */
+#define N_OF_NOISEWORDS 123
+
+const char *noiseWords[N_OF_NOISEWORDS]={"a", "about", "after", "all",
+"also", "an", "another", "any", "are", "as", "and", "at", "be",
+"because", "been", "before", "being", "between", "but", "both",
+"by", "came", "can", "come", "could","did", "do","each", "even",
+"for", "from", "further", "furthermore","get", "got","has", "had",
+"he", "have", "her", "here", "him", "himself", "his", "how", "hi",
+"however","i", "if", "in", "into", "is", "it", "its", "indeed","just",
+"like","made", "many", "me", "might", "more", "moreover", "most",
+"much","must", "my","never", "not", "now","of", "on", "only", "other",
+"our", "out", "or", "over","said", "same", "see", "should", "since",
+"she", "some", "still", "such","take", "than", "that", "the", "their",
+"them", "then", "there", "these", "therefore", "they", "this", "those",
+"through", "to", "too", "thus","under", "up","very","was", "way", "we",
+"well", "were", "what", "when", "where", "which", "while", "who",
+"will", "with", "would","you", "your"};
#include
-#include
#include
+#include
#include
-#include
-#define MAXWORD 1000 /* longest word that can be read by mgetword */
-#define DEFAULT_COMP_LEN 8 /* default length to compare */
+#define MAXWORD 500
-/*
- * tnode: Tree node from K&R2 page 140. Words are initially read into
- * the tree by getword.
- */
-struct tnode
-{
- char *word;
- int count;
- struct linenumber *linenumbers;
- struct tnode *left;
- struct tnode *right;
-};
-
-struct linenumber {
- int *number;
- struct linenumber *nextnumber;
-};
+ struct tnode{
+ char *word;
+ unsigned int count;
+ struct ocurLine *lineOfOccurence;
-/*
- * simroot: Part of a linked list of pointers to simword lists with
- * a common root.
- */
-struct simroot
-{
- struct simword *firstword; /* points to the list of words */
- struct simroot *nextroot; /* points to the next node in the list */
-};
+ struct tnode *left;
+ struct tnode *right;
+ };
-/*
- * simword: Part of a linked list of words with a common root. Points
- * to the word in the tnodes.
- */
-struct simword
-{
- char *word; /* points to the word in the tree */
- int count; /* copied from the tree */
- int linenumber; /* copied from the tree */
- struct simword *nextword; /* next node */
-};
-
-struct tnode *addtree(struct tnode *, char *, int);
-void treeprint(const struct tnode *);
-int mgetword(char *, int, int *);
-struct linenumber *lnumberalloc(void);
-struct linenumber *addlinenumber(struct linenumber *, int);
-
-int main(int argc, char *argv[])
-{
- struct tnode *root;
- char word[MAXWORD];
- int len;
- int lineno = 0;
-
-
- /* get all the words */
- root = NULL;
- while(mgetword(word, MAXWORD, &lineno) != 'x')
- if(isalpha(word[0]))
- root = addtree(root, word, lineno);
-
- if(argc == 1)
- len = DEFAULT_COMP_LEN;
- else if(argc == 2)
- len = atoi(argv[1]);
- else {
- printf("Incorrect number of arguments.\n");
- return 1;
- }
-
- printf("Words with line numbers\n");
- treeprint(root); /* prints all the words */
+ struct ocurLine{
+ unsigned int line;
+ struct ocurLine *next;
+ };
- return 0;
-} /* end of main() */
+int binarySearch(const char *arr[], int l, int r, char *x);
-struct tnode *talloc(void);
-char *mstrdup(char *);
+void treeprint(const struct tnode *p);
+char *mstrdup(char *s);
-/* mgetword from Ex6.1 */
+int getWord(char *word, int lim);
-#define IN 1
-#define OUT 0
+void ungetch(char c);
+int getch(void);
-int mgetword(char *word, int lim, int *lineno_addr)
-{
- int c, d, getch(void), comment, string, directive;
- void ungetch(int);
- char *w = word;
+char buf; /* buffer for getch/ungetch */
- comment = string = directive = OUT;
-
- while (isspace(c = getch())) {
- if (c == '\n') {
-
- *lineno_addr = *lineno_addr +1;
+struct tnode *talloc(void);
+struct tnode *addtree(struct tnode *p, char *w, unsigned int l);
- }
- }
+void printline(const struct ocurLine *p);
- /* Check if inside a comment */
+struct ocurLine *linealloc(void);
+struct ocurLine *addLine(struct ocurLine *p, unsigned int l);
- if (c == '/') {
- if ((d = getch()) == '*') {
- comment = IN;
- } else {
- comment = OUT;
- ungetch(d);
- }
- }
+int main()
+{
+ int l=1;
+ struct tnode *root;
+ char word[MAXWORD];
+
+ root = NULL;
+
+ while(getWord(word, MAXWORD) != EOF)
+ if (word[0] == '\n') // Adding 1 to [l] if there is new line
+ l++;
+ else if(isalpha(word[0]))
+ if (binarySearch(noiseWords, 0, N_OF_NOISEWORDS, word) == -1)
+ root = addtree(root, word, l);
+ treeprint(root);
+}
- /* Check if inside a quote */
- if ( c == '\"') {
- string = IN;
- }
+ /* Binary search for our array of noise words. */
+int binarySearch(const char *arr[], int l, int r, char *x)
+{
+ if (r >= l) {
+ int mid = l + (r - l) / 2;
+ int cmp = strcmp(arr[mid], x);
- /* Check if inside a directive */
+ if (cmp == 0)
+ return mid;
- if (c == '#') {
- directive = IN;
- }
+ if (cmp > 0)
+ return binarySearch(arr, l, mid - 1, x);
+
+ return binarySearch(arr, mid + 1, r, x);
+ }
+
+ return -1;
+}
- if ( c == '\\') {
- c = getch(); /* ignore the \\ character */
- }
- if (comment == OUT && string == OUT && directive == OUT) {
+int getWord(char *word, int lim)
+{
+ int c;
- if (c != EOF)
- *w++ = c;
+ char *w = word;
- if (!isalnum(c) && c !='_' ) {
- *w = '\0';
- return c;
- }
+ while (isspace(c = getch()) && c != '\n')
+ ;
- for ( ; --lim > 0; w++) {
- *w = getch();
- if (!isalnum(*w) && *w != '_') {
- ungetch(*w);
- break;
- }
- }
- *w = '\0';
- return word[0];
- }
- else if ( comment == IN) {
+ if (c != EOF)
*w++ = c;
- *w++ = d;
-
- while ((*w++ = c = getch())) {
- if ( c == '*' ) {
- if ( (c = getch()) == '/' ) {
- *w++ = c;
- comment = OUT;
- break;
- } else {
- ungetch(c);
- }
- }
- }
- *w = '\0';
- }
- else if ( string == IN) {
- *w++ = c;
- while ((*w++ = getch()) != '\"') {
- if ( *w == '\\') /* Take care of escaped quotes */
- *w++ = getch();
- }
- string = OUT;
- *w = '\0';
- }
- else if (directive == IN) {
- *w++ = c;
- while ((*w++ = getch()) != '\n') {
- if ( c == '\\') { /* Take care of continuation line escape */
- *w++ = getch();
- }
- }
- directive = OUT;
+ if (!isalpha(c) && c != '_' && c != '#') {
*w = '\0';
+ return c;
}
- return c;
+ for ( ; --lim > 0; w++)
+ if (!isalnum(*w = getch())){
+ ungetch(*w);
+ break;
+ }
+ *w = '\0';
+ return word[0];
}
-
-
-/***************************************************************************
- * All code below here is from K&R2. *
- ***************************************************************************/
-
-/*
- * addtree: From K&R2 page 141.
- * Adds a node containing w, at or below node p.
- */
-struct tnode *addtree(struct tnode *p, char *w, int linenumber)
+/* addtree: adds branch to a tree*/
+struct tnode *addtree(struct tnode *p, char *w, unsigned int l)
{
int cond;
if(p == NULL) { /* new word */
p = talloc();
- p->word = mstrdup(w);
+ p->word=mstrdup(w);
p->count = 1;
- p->linenumbers = NULL;
- p->linenumbers = addlinenumber(p->linenumbers, linenumber);
+ p->lineOfOccurence = NULL;
+ p->lineOfOccurence = addLine(p->lineOfOccurence, l);
p->left = p->right = NULL;
}
- else if((cond = strcmp(w, p->word)) == 0) {
- p->count++;
- p->linenumbers = addlinenumber(p->linenumbers, linenumber);
+ else if((cond = strcmp(w, p->word)) == 0){
+ p->count++;
+ p->lineOfOccurence = addLine(p->lineOfOccurence, l);
}
else if(cond < 0)
- p->left = addtree(p->left, w, linenumber);
+ p->left = addtree(p->left, w, l);
else
- p->right = addtree(p->right, w, linenumber);
+ p->right = addtree(p->right, w, l);
return p;
}
-struct linenumber *addlinenumber(struct linenumber *p, int linenumber) {
- if (p == NULL) {
- p = lnumberalloc();
- p->number = linenumber;
- p->nextnumber = NULL;
- } else {
- p->nextnumber = addlinenumber(p->nextnumber, linenumber);
- }
+/* treeprint: prints all the branches of the tree with words.*/
+void treeprint(const struct tnode *p)
+{
- return p;
+ if(p != NULL) {
+ treeprint(p->left);
+
+ printf("%s: [", p->word);
+
+ printline(p->lineOfOccurence);
+
+ printf("]\n");
+
+ treeprint(p->right);
+ }
}
-struct linenumber *lnumberalloc(void)
+/* talloc: From K&R2 page 142. Makes a tnode. */
+struct tnode *talloc(void)
{
- return (struct linenumber *) malloc(sizeof(struct linenumber));
+ return (struct tnode *) malloc(sizeof(struct tnode));
}
-/* treeprint: From K&R2 page 142. Prints tree p in-order. */
-void treeprint(const struct tnode *p)
+
+/* printline: Prints all lines.*/
+void printline(const struct ocurLine *p)
{
- if(p != NULL) {
- treeprint(p->left);
- printf("\n%s :", p->word);
- printnumbers(p->linenumbers);
- treeprint(p->right);
+ if (p->next == NULL)
+ printf("%i", p->line);
+ else{
+ printf("%i, ", p->line);
+ printline(p->next);
}
}
-void printnumbers(const struct linenumber *p) {
- if (p != NULL) {
- printf("%d,", p->number);
- printnumbers(p->nextnumber);
+/* addLine: adds a line to word. */
+struct ocurLine *addLine(struct ocurLine *p, unsigned int l)
+{
+ if (p == NULL){
+ p = linealloc();
+ p->line = l;
+ p->next = NULL;
}
+ else
+ p->next = addLine(p->next, l);
+ return p;
}
-/* talloc: From K&R2 page 142. Makes a tnode. */
-struct tnode *talloc(void)
+/* linealloc: Makes ocurLine*/
+struct ocurLine *linealloc(void)
{
- return (struct tnode *) malloc(sizeof(struct tnode));
+ return (struct ocurLine *) malloc(sizeof(struct ocurLine));
}
/* strdup: From K&R2 page 143. Makes a duplicate of s. */
char *mstrdup(char *s)
{
char *p;
+
p = (char *) malloc(strlen(s) + 1);
+
if(p != NULL)
strcpy(p, s);
return p;
}
-/*
- * getch and ungetch are from K&R2, page 79
- */
-#define BUFSIZE 100
-
-char buf[BUFSIZE]; /* buffer for ungetch() */
-int bufp = 0; /* next free position in buf */
+/*************************************************************
+ * Getch/Ungetch functions from previous exercises *
+ *************************************************************/
-int getch(void) { /* get a (possibly pushed back) character */
- return (bufp > 0) ? buf[--bufp] : getchar();
+/* getch: gets a (possibly pushed-back) character */
+int getch(void)
+{
+ if (buf > 0){
+ int copy=buf;
+ buf=0;
+ return copy;
+ }
+ else
+ return getchar();
}
-void ungetch(int c) { /* push character back on input */
- if(bufp >= BUFSIZE)
- printf("ungetch: too many characters\n");
- else
- buf[bufp++] = c;
- return;
-}
\ No newline at end of file
+/* ungetch: pushes character back on input */
+void ungetch(char c)
+{
+ buf = c;
+}
diff --git a/languages/cprogs/Ex_6.4.c b/languages/cprogs/Ex_6.4.c
index d7698387..2e383d11 100644
--- a/languages/cprogs/Ex_6.4.c
+++ b/languages/cprogs/Ex_6.4.c
@@ -198,7 +198,7 @@ struct bynumbernode *traverse(const struct tnode *p, struct bynumbernode *q){
return q;
}
-void main(){
+int main(){
struct tnode *root;
char word[MAXWORD];
@@ -218,7 +218,7 @@ void main(){
printf("Words by frequency:\n");
treeprint(nroot);
- return;
+ return 0;
}
diff --git a/languages/cprogs/Ex_7.1_lower-upper.c b/languages/cprogs/Ex_7.1_lower-upper.c
index 5ef30604..847780de 100644
--- a/languages/cprogs/Ex_7.1_lower-upper.c
+++ b/languages/cprogs/Ex_7.1_lower-upper.c
@@ -1,24 +1,35 @@
-/* Write a program which converts upper case to lower case or lower case to
+/* Write a program which converts upper case to lower case or lower case to
upper case depending on the name it is involved with as found in argv[0] */
-#include
-#include
-#include
+#include
+#include
+#include
/* lower: converts upper case to lower case */
/* upper: converts lower case to upper case */
-int main(int argc,char *argv[])
-{
- int c;
+const char *input = "This\tis\ta\ttest";
+int input_index = 0;
- if(strcmp(argv[0],"./lower")==0)
- while((c=getchar()) != EOF)
- putchar(tolower(c));
- else
- while((c=getchar()) != EOF)
- putchar(toupper(c));
-
- return 0;
+int _getchar(void) {
+ if (input[input_index] == '\0') {
+ return EOF;
+ } else {
+ return input[input_index++];
+ }
}
+
+
+int main(int argc, char *argv[]) {
+ int c;
+
+ if (strcmp(argv[0], "./lower") == 0)
+ while ((c = _getchar()) != EOF)
+ putchar(tolower(c));
+ else
+ while ((c = _getchar()) != EOF)
+ putchar(toupper(c));
+
+ return 0;
+}
diff --git a/languages/cprogs/Fibonacci.c b/languages/cprogs/Fibonacci.c
deleted file mode 100644
index e1ba9c67..00000000
--- a/languages/cprogs/Fibonacci.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Fibonacci Numbers Generator */
-/* Fibonacci series is formed by adding the latest two numbers to get the next one,starting from 0 and 1 */
-
-#include
-
-int main(void)
-{
- int first,second,next,limit;
- printf("How many Numbers in the Series?");
- scanf("%d",&limit);
-
- first=0;
- second=1;
-
- printf("%d,%d",first,second);
-
- while(limit > 2) /* 0 and 1 are default and counted */
- {
- next = first + second;
- printf(",%d",next);
-
- first= second;
- second = next;
-
- --limit;
- }
-return 0;
-}
-
-
diff --git a/languages/cprogs/Nofbtn.c b/languages/cprogs/Nofbtn.c
deleted file mode 100644
index 54b77e0b..00000000
--- a/languages/cprogs/Nofbtn.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Write a Program to Count Blanks, Tabs and Newlines */
-
-#include
-
-int main(void)
-{
- int nb,nt,nl,c;
-
- nb=nt=nl=0;
-
- while((c=getchar())!=EOF)
- {
- if(c==' ')
- ++nb;
- if(c=='\t')
- ++nt;
- if(c=='\n')
- ++nl;
- }
- printf("No. of Blanks is %d,No. of Tabs is %d and No. of Newlines is %d",nb,nt,nl);
-
-return 0;
-}
-
diff --git a/languages/cprogs/alloc_afree.c b/languages/cprogs/alloc_afree.c
deleted file mode 100644
index 31cf373c..00000000
--- a/languages/cprogs/alloc_afree.c
+++ /dev/null
@@ -1,38 +0,0 @@
-#define ALLOCSIZE 1000 /* size of available space */
-
-static char allocbuf[ALLOCSIZE]; /* storage for alloc */
-static char *allocp = allocbuf; /* next free position */
-
-char *alloc(int n) /* return pointer to n characters */
-{
- if( allocbuf + ALLOCSIZE - allocp >= n)
- {
- allocp += n;
- return allocp - n; /* old p */
- }
- else
- return 0;
-}
-
-
-void afree(char *p) /* free storage pointed to by p */
-{
- if(p >= allocbuf && p < allocbuf + ALLOCSIZE)
- allocp = p;
-}
-
-int main(void)
-{
- char *p;
- printf("%p\n",allocp);
-
- p=alloc(100);
- printf("%p\n",allocp);
-
- afree(p);
- printf("%p\n",allocp);
-
- return 0;
-}
-
-
diff --git a/languages/cprogs/anylonglinelen.c b/languages/cprogs/anylonglinelen.c
deleted file mode 100644
index d55e45e6..00000000
--- a/languages/cprogs/anylonglinelen.c
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Program to print the longest line.
- This program prints the length of any-length line with as much possible text it can hold */
-
-#include
-
-#define MAXLINE 1000
-
-int getline(char line[],int lim);
-void copy(char to[],char from[]);
-
-int main(void)
-{
- int len,max;
- char line[MAXLINE],maxline[MAXLINE];
-
- max = 0;
-
- while((len=getline(line,MAXLINE)) > 0)
- {
- printf("%d\t%s",len,line);
- if(len > max)
- {
- max=len;
- copy(maxline,line);
- }
- }
- printf("%s",maxline);
-
-return 0;
-}
-
-int getline(char s[],int lim)
-{
- int i,j,c;
-
- for(i=0,j=0;(c=getchar())!=EOF && c!= '\n';++i)
- if( i < lim-2 )
- {
- s[i] = c;
- ++j;
- }
- if( c == '\n')
- {
- s[i] = c;
- ++i;
- ++j;
- }
- s[j] = '\0';
-
- return i;
-}
-
-void copy(char to[],char from[])
-{
- int i;
-
- i=0;
-
- while((to[i]=from[i]) != '\0')
- ++i;
-}
-
diff --git a/languages/cprogs/atoiv2.c b/languages/cprogs/atoiv2.c
deleted file mode 100644
index 40868701..00000000
--- a/languages/cprogs/atoiv2.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Ex5.6 */
-
-#include
-#include
-
-int atoiv2(char *);
-
-int main(void) {
- char *s = "1234";
- int ret;
-
- ret = atoiv2(s);
-
- printf("%d", ret);
-
- return 0;
-}
-
-int atoiv2(char *s) {
- int n, sign;
-
- for (; isspace(*s); s++) /* skip white space */
- ;
- sign = (*s == '-') ? -1 : 1;
-
- if (*s == '+' || *s == '-')
- s++;
- for (n = 0; isdigit(*s); s++)
- n = 10 * n + *s - '0';
-
- return sign * n;
-}
-
diff --git a/languages/cprogs/binsearch.c b/languages/cprogs/binsearch.c
deleted file mode 100644
index 87beeaf6..00000000
--- a/languages/cprogs/binsearch.c
+++ /dev/null
@@ -1,36 +0,0 @@
-/* binsearch: Implementation of Binary Search,In the array v[],search for n in the binary way*/
-
-#include
-
-int binsearch(int x,int v[],int n);
-
-int main(void)
-{
- int arr[]={2,4,5,7,8,9,11,23,45,50};
- int x,n;
-
- printf("%d",binsearch(9,arr,10));
-
- return 0;
-}
-
-int binsearch(int x,int v[],int n)
-{
- int low,high,mid;
-
- low=0;
- high=n-1;
-
- while(low v[mid])
- low = mid + 1;
- else
- return mid;
- }
- return -1;
-}
diff --git a/languages/cprogs/bitcount.c b/languages/cprogs/bitcount.c
deleted file mode 100644
index fb9616ff..00000000
--- a/languages/cprogs/bitcount.c
+++ /dev/null
@@ -1,22 +0,0 @@
-/* bitcount : count 1 bits in x */
-#include
-
-int bitcount(unsigned x);
-
-int main(void)
-{
- printf("%d",bitcount((unsigned)255));
-
- return 0;
-}
-
-int bitcount(unsigned x)
-{
- int b;
-
- for(b=0; x!= 0; x >>=1)
- if( x & 01)
- b++;
- return b;
-}
-
diff --git a/languages/cprogs/counts.c b/languages/cprogs/counts.c
deleted file mode 100644
index c8005243..00000000
--- a/languages/cprogs/counts.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Program to count the digits,white spaces and others */
-
-#include
-
-int main(void)
-{
- int c,i,nwhite,nother,ndigit[10];
-
- nwhite=nother=0;
-
- for(i=0;i<10;i++)
- ndigit[i]=0;
-
- while((c=getchar())!=EOF)
- {
-
- switch(c)
- {
- case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':
- ndigit[c-'0']++;
- break;
- case ' ':
- case '\t':
- case '\n':
- nwhite++;
- break;
- default:
- nother++;
- break;
-
- }
- }
-
- printf("digits =");
- for(i=0;i<10;i++)
- printf("%d",ndigit[i]);
- printf(", white space = %d, other = %d \n",nwhite,nother);
-
- return 0;
-}
-
diff --git a/languages/cprogs/day_datev3.c b/languages/cprogs/day_datev3.c
deleted file mode 100644
index 76c07ca2..00000000
--- a/languages/cprogs/day_datev3.c
+++ /dev/null
@@ -1,55 +0,0 @@
-#include
-
-static char daytab[2][13] = {
- {0,31,28,31,30,31,30,31,31,30,31,30,31},
- {0,31,29,31,30,31,30,31,31,30,31,30,31}
-};
-
-int day_of_year(int year,int month,int day);
-void month_day(int year,int yearday,int *pmonth,int *pday);
-
-int main(void)
-{
- int day,dat,mon;
-
- day=day_of_year(1981,10,2);
- printf("%d\n",day);
-
- month_day(1981,252,&mon,&dat);
- printf("%d,%d",mon,dat);
-
- return 0;
-}
-
-/* day_of_year: set day of year from month and day */
-int day_of_year(int year,int month,int day)
-{
- int leap;
- char *p;
-
- leap = year%4 == 0 && year % 100 !=0 || year %400 == 0;
- p = daytab[leap];
-
- while(--month)
- day += *++p;
- return day;
-}
-
-/* month_day: set month, day from day of year */
-void month_day(int year,int yearday,int *pmonth,int *pday)
-{
- int leap;
- char *p;
-
- leap = year%4 == 0 && year %100 !=0 || year % 400 == 0;
-
- p = daytab[leap];
-
- while(yearday > *++p)
- yearday -= *p;
-
- *pmonth = p - *(daytab + leap);
- *pday = yearday;
-}
-
-
diff --git a/languages/cprogs/dcl.c b/languages/cprogs/dcl.c
deleted file mode 100644
index 41724bb7..00000000
--- a/languages/cprogs/dcl.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* DCL: A Recursive Descent Parser */
-
-/* dcl: parse a declarator */
-
-void dcl(void)
-{
- int ns;
-
- for(ns=0;gettoken()=='*';) /* count *'s */
- ns++;
-
- dirdcl();
- while(ns-- > 0)
- strcat(out,"pointer to");
-}
-
-/* dirdcl: parse a direct declarator */
-
-void dirdcl(void)
-{
- int type;
-
- if(tokentype == '(') /* dcl */
- {
- dcl();
-
- if(tokentype != ')')
- printf("error: missing ) \n");
- }
- else if(tokentype == NAME) /* variable name */
- strcpy(name,token);
- else
- printf("error: expected name or (dcl) \n");
-
- while((type=gettoken()) == PARENS || type == BRACKETS )
- if(type = PARENS)
- strcat(out,"function returning");
- else
- {
- strcat(out,"arg");
- strcat(out,token);
- strcat(out,"of");
- }
-}
-
-
-#include
-#include
-#include
-
-#define MAXTOKEN 100
-
-enum {NAME,PARENS,BRACKETS};
-
-void dcl(void);
-void directdcl(void);
-int gettoken(void);
-int tokentype; /* type of last token */
-char token[MAXTOKEN]; /* last token string */
-char name[MAXTOKEN]; /* identifier name */
-char datatype[MAXTOKEN]; /* data type=char, int etc */
-char out[1000]; /* output string */
-
-int main(void)
-{
- while(gettoken()!=EOF)
- {
- strcpy(datatype,token);
- out[0]='\0';
- dcl();
-
- if(tokentype != '\n')
- printf("syntax error \n");
-
- printf(" %s %s %s \n",name,out,datatype);
- }
-
-return 0;
-}
-
-int gettoken(void)
-{
- int i,getch(void);
- void ungetch(int);
- char *p = token;
-
- while((c=getch()) == ' ' || c == '\t')
- ;
-
- if( c == '(')
- {
- if((c=getch()) == ')')
- {
- strcpy(token,"()");
- return tokentype = PARENS;
- }
- else
- {
- ungetch(c);
- return tokentype = '(';
- }
- else if ( c == '[')
- {
- for(*p++ = c; (*p++ = getch()) != ']';)
- ;
- *p = '\0';
- return tokentype = BRACKETS;
- }
- else if ( isalpha(c))
- {
- for(*p++ =c; isalnum(c=getch());)
- *p++ = c;
- *p = '\0';
- ungetch(c);
- return tokentype = NAME;
- }
- else
- return tokentype =c;
-}
-
-#define BUFSIZE 100
-
-char buf[BUFSIZE]; /* buffer for ungetch */
-int bufp = 0; /* next free position in buf */
-
-int getch(void) /* get a (possibly pushed back) character */
-{
- return (bufp > 0) ? buf[--bufp]:getchar();
-}
-
-void ungetch(int c) /* push a character back on input */
-{
- if(bufp >= BUFSIZE)
- printf("ungetch: too many characters \n");
- else
- buf[bufp++] = c;
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/languages/cprogs/endian.c b/languages/cprogs/endian.c
deleted file mode 100644
index c0b7559d..00000000
--- a/languages/cprogs/endian.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include
-int main(int argc, char *argv[])
-{
- int a=0x99000011;
- unsigned char *c = (unsigned char *) (&a);
- if (*c == 0x11)
- printf("little endian\n");
- else
- printf("big endian\n");
-
-}
diff --git a/languages/cprogs/eratosthenes.c b/languages/cprogs/eratosthenes.c
deleted file mode 100644
index 5d6ade03..00000000
--- a/languages/cprogs/eratosthenes.c
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Program illustrating sieve of Eratosthenes.
- *
- **/
-
-#include
-
-#define N 100
-
-int main(int argc, char *argv[]) {
- int nums[N];
-
- for (int i = 2; i < N; ++i) {
- nums[i] = i;
- }
-
- for (int i = 2; i < N; ++i) {
- for (int j = i; j < N; ++j) {
- if (i != j && nums[j] != 0 && (nums[j] % i == 0)) {
- nums[j] = 0;
- }
- }
- }
-
- for (int k = 2; k < N; ++k) {
- if (nums[k] != 0) {
- printf("%d\n", nums[k]);
- }
- }
-
-}
diff --git a/languages/cprogs/fork1.c b/languages/cprogs/fork1.c
deleted file mode 100644
index d9dd8723..00000000
--- a/languages/cprogs/fork1.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include
-
-int main()
-{
- int pid;
- pid = fork();
- printf("%d \n",pid);
-}
diff --git a/languages/cprogs/fsize.c b/languages/cprogs/fsize.c
deleted file mode 100644
index 977b7dba..00000000
--- a/languages/cprogs/fsize.c
+++ /dev/null
@@ -1,133 +0,0 @@
-/* Print File Sizes */
-#include
-#include
-#include /* flags for read and write */
-#include /* typedefs */
-#include /* structure returned by stat */
-#include "dirent.h"
-
-void fsize(char *);
-
-/* print file sizes */
-int main(int argc,char **argv)
-{
- if(argc == 1) /* default : current directory */
- fsize(".");
- else
- while(--argc > 0)
- fsize(*++argv);
- return 0;
-}
-
-int stat(char *,struct stat *);
-void dirwalk(char *,void (*fcn)(char *));
-
-/* fsize: print size of file "name" */
-void fsize(char *name)
-{
- struct stat stbuf;
-
- if(stat(name,&stbuf) == -1)
- {
- fprintf(stderr,"fsize: Can't access %s \n",name);
- return;
- }
- if((stbuf.st_mode & S_IFMT) == S_IFDIR)
- dirwalk(name,fsize);
- printf("%8ld %s \n",stbuf.st_size,name);
-}
-
-
-#define MAX_PATH 1024
-
-/* dirwalk: apply fcn to all files in dir */
-void dirwalk(char *dir,void (*fcn)(char *))
-{
- char name[MAX_PATH];
- Dirent *dp;
- DIR *dfd;
-
- if((dfd = opendir(dir)) == NULL)
- {
- fprintf(stderr,"dirwalk: can't open %s\n",dir);
- return;
- }
-
- while((dp = readdir(dfd)) != NULL)
- {
- if(strcmp(dp->name,".") == 0 || strcmp(dp->name,"..") == 0)
- continue;
- if(strlen(dir)+strlen(dp->name)+2 > sizeof(name))
- fprintf(stderr,"dirwalk: name %s/ %s too long \n",dir,dp->name);
- else
- {
- sprintf(name,"%s/%s",dir,dp->name);
- (*fcn)(name);
- }
- }
- closeddir(dfd);
-}
-
-
-#ifndef DIRSIZ
-#define DIRSIZ 14
-#endif
-
-struct direct /* directory entry */
-{
- ino_t d_ino; /* inode number */
- char d_name[DIRSIZ]; /* long name does not have '\0' */
-};
-
-int fstat(int fd,struct stat *);
-
-/* opendir: open a directory for readdir calls */
-
-DIR *opendir(char *dirname)
-{
- int fd;
- struct stat stbuf;
- DIR *dp;
-
- if((fd = open(dirname,O_RDONLY,0)) == -1
- || fstat(fd,&stbuf) == -1
- || (stbuf.st_mode & S_IFMT) != S_IFDIR
- || (dp = (DIR *)malloc(sizeof(DIR))) == NULL)
- return NULL;
- dp->fd = fd;
- return dp;
-}
-
-/* closedir: close directory opened by opendir */
-void closedir(DIR *dp)
-{
- if(dp)
- {
- close(dp->fd);
- free(dp);
- }
-}
-
-
-#include /* local directory structure */
-/* readdir: read directory entries in sequence */
-
-Dirent *readdir(DIR *dp)
-{
- struct direct dirbuf; /* local directory structure */
- static Dirent d; /* return: portable structure */
-
- while(read(dp->fd,(char *)&dirbuf,sizeof(dirbuf)) == sizeof(dirbuf))
- {
- if(dirbuf.d_ino= 0)
- continue;
- d.ino = dirbuf.d_ino;
- strncpy(d.name,dirbuf.d_name,DIRSIZ);
- d.name[DIRSIZ] = '\0';
- return &d;
- }
-
- return NULL;
-}
-
-
diff --git a/languages/cprogs/getbits.c b/languages/cprogs/getbits.c
deleted file mode 100644
index aaa296ad..00000000
--- a/languages/cprogs/getbits.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/* getbits: get n bits from the position p */
-
-#include
-
-unsigned getbits(unsigned x,int p,int n);
-
-int main(void)
-{
- printf("%u",getbits((unsigned)8,3,1));
-}
-
-unsigned getbits(unsigned x,int p,int n)
-{
- return (x >> (p+1-n)) & ~(~0 << n);
-}
-
-
diff --git a/languages/cprogs/getline_woandr.c b/languages/cprogs/getline_woandr.c
deleted file mode 100644
index 3bd85308..00000000
--- a/languages/cprogs/getline_woandr.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Program demonstrates the former getline forloop without && and ||.
-Also demonstrates enum data type usage */
-
-#include
-#define MAXLINE 1000
-
-int getline(char line[],int maxline);
-
-int main(void)
-{
- char line[MAXLINE];
-
- getline(line,MAXLINE);
-
- printf("%s",line);
-
- return 0;
-}
-
-int getline(char s[],int lim)
-{
- int c,i;
- enum values{NO=0,YES};
- enum values proceed;
-
- proceed= YES;
-
- i =0;
-
- while(proceed == YES)
- {
- if( i > lim - 1)
- proceed = NO;
- else if((c=getchar()) == EOF)
- proceed = NO;
- else if( c == '\n')
- proceed = NO;
- else
- {
- s[i] = c;
- ++i;
- proceed = YES;
- }
- }
- if ( c == '\n')
- {
- s[i] = c;
- ++i;
- }
- s[i] = '\0';
-
- return i;
-}
-
-
-
-
-
diff --git a/languages/cprogs/getpass1.c b/languages/cprogs/getpass1.c
deleted file mode 100644
index af10935a..00000000
--- a/languages/cprogs/getpass1.c
+++ /dev/null
@@ -1,68 +0,0 @@
-#include
-#include
-#include
-#include
-#include
-
-static int gp_save_term(int fd, struct termios *tios)
-{
- return tcgetattr(fd, tios);
-}
-
-static int gp_load_term(int fd, struct termios *tios)
-{
- return tcsetattr(fd, TCSAFLUSH, tios);
-}
-
-static void gp_set_password_flags(struct termios *tios)
-{
- tios->c_lflag &= ~ECHO; /* disable echo */
- tios->c_lflag &= ~ISIG; /* ignore signals */
-}
-
-/* Get a password of max len-1 chars and store it in dest.
- * The string is anyway nul terminated, the echo disabled. */
-int palla_getpass(char *dest, size_t len)
-{
- unsigned int i; /* character index inside pass */
- int ttyfd = fileno(stdin);
- struct termios orig, new;
-
- /* sanity check */
- if (!len || !dest)
- return -1;
-
- /* Save the old status */
- if (gp_save_term(ttyfd, &orig) == -1)
- return -1;
- new = orig; /* copy it in the new */
- gp_set_password_flags(&new); /* set the right flags */
- if (gp_load_term(ttyfd, &new) == -1) /* load the new term config */
- return -1;
-
- /* Now we are in "password mode", get the input */
- i = 0;
- while(i < (len-1)) {
- char c;
- if (read(ttyfd, &c, 1) <= 0)
- break;
- if (c == '\n')
- break;
- dest[i] = c;
- i++;
- }
- dest[i] = '\0'; /* add the nul term */
- if (gp_load_term(ttyfd, &orig) == -1) /* restore the old term */
- return -1; /* sorry, the term is left unsane */
- return i;
-}
-
-int main(void)
-{
- char dest[10];
- printf("password: ");
- fflush(stdout);
- palla_getpass(dest, 10);
- printf("'%s'\n", dest);
- return 0;
-}
diff --git a/languages/cprogs/glat17.c b/languages/cprogs/glat17.c
deleted file mode 100644
index de5f0cfc..00000000
--- a/languages/cprogs/glat17.c
+++ /dev/null
@@ -1,40 +0,0 @@
-#include
-#include
-unsigned long long int countones(unsigned long long int);
-int main(void)
-{
- unsigned long long int i,cn;
-
- for(i = 1; i<=(ULLONG_MAX - 1); ++i)
- {
- cn = countones(i);
- if( i == cn)
- {
- printf("%d \n",i);
- fflush(stdout);
- }
- }
-
- return 0;
-}
-
-unsigned long long int countones(unsigned long long int i)
-{
- static unsigned long long int count = 0;
- int digit;
-
- while((i/10) >= 1)
- {
- digit = i % 10;
-
- if(digit == 1)
- count++;
- i /= 10;
- }
- if( i == 1)
- count++;
-
- return count;
-}
-
-
diff --git a/languages/cprogs/htoi.c b/languages/cprogs/htoi.c
deleted file mode 100644
index 4af636a3..00000000
--- a/languages/cprogs/htoi.c
+++ /dev/null
@@ -1,70 +0,0 @@
-#include
-#define MAXLINE 100
-
-#define YES 1
-#define NO 0
-
-int getline(char line[],int maxline);
-int htoi(char s[]);
-
-int main(void)
-{
- char line[MAXLINE];
- int value;
-
- getline(line,MAXLINE);
- value=htoi(line);
-
- printf("The value of %s is %d",line,value);
-
- return 0;
-}
-
-int getline(char s[],int lim)
-{
- int c,i;
-
- for(i=0;i='0' && s[i] <='9')
- hexdigit= s[i] - '0';
- else if(s[i] >='a' && s[i] <='f')
- hexdigit= s[i] -'a' + 10;
- else if(s[i] >='A' && s[i] <='F')
- hexdigit= s[i] -'A' + 10;
- else
- inhex = NO;
-
- if(inhex == YES)
- n = 16 * n + hexdigit;
- }
- return n;
-}
-
-
diff --git a/languages/cprogs/leap.c b/languages/cprogs/leap.c
deleted file mode 100644
index b1526433..00000000
--- a/languages/cprogs/leap.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Program for the logic of leap year */
-
-#include
-#define YEAR 3000
-
-int main(void)
-{
- if( ((YEAR % 4 == 0) && (YEAR % 100 != 0)) || (YEAR % 400 == 0) )
- printf("The Year is a Leap Year");
- else
- printf("The Year is Not a Leap Year");
-
- return 0;
-}
-
diff --git a/languages/cprogs/likefind.c b/languages/cprogs/likefind.c
deleted file mode 100644
index a03fb451..00000000
--- a/languages/cprogs/likefind.c
+++ /dev/null
@@ -1,66 +0,0 @@
-#include
-#include
-#define MAXLINE 1000
-
-int getline(char *line,int max);
-
-/* find: print lines that match pattern from the 1st arg
- ----------------------------
- find -nx pattern
- ----------------------------
-*/
-
-int main(int argc,char *argv[])
-{
- char line[MAXLINE];
- long lineno = 0;
- int c,except =0,number =0,found =0;
-
- while(--argc > 0 && (*++argv)[0] == '-')
- while(c = *++argv[0])
- switch(c)
- {
- case 'x':
- except =1;
- break;
- case 'n':
- number =1;
- break;
- default:
- printf("find: illegal option %c\n",c);
- argc =0;
- found = -1;
- break;
- }
- if(argc != 1)
- printf("Usage: find -x -n pattern \n");
- else
- while(getline(line,MAXLINE) >0)
- {
- lineno++;
- if((strstr(line,*argv)!=NULL) != except)
- {
- if(number)
- printf("%ld:",lineno);
- printf("%s",line);
- found++;
- }
- }
- return found;
-}
-
-int getline(char *s,int lim)
-{
- int c;
- char *t=s;
-
- while(--lim > 0 && (c=getchar())!=EOF && c!='\n')
- *s++ =c;
-
- if(c=='\n')
- *s++=c;
- *s ='\0';
-
- return s -t;
-}
-
diff --git a/languages/cprogs/likegrep.c b/languages/cprogs/likegrep.c
deleted file mode 100644
index 3aae9099..00000000
--- a/languages/cprogs/likegrep.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Ex5.6 */
-
-#include
-#include
-#define MAXLINE 1000
-
-int getline(char *line,int max);
-
-/* find: prints lines that match the pattern from the 1st argument */
-
-int main(int argc,char *argv[])
-{
- char line[MAXLINE];
- int found = 0;
-
- if(argc!=2)
- printf("Usage:find pattern\n");
- else
- while(getline(line,MAXLINE)>0)
- if(strstr(line,argv[1]) != NULL)
- {
- printf("%s",line);
- found++;
- }
- return found;
-}
-
-int getline(char *s,int lim)
-{
- int c;
- char *t=s;
-
- while(--lim > 0 && (c=getchar())!=EOF && c!='\n')
- *s++=c;
-
- if(c=='\n')
- *s++=c;
- *s='\0';
-
- return s-t;
-}
-
diff --git a/languages/cprogs/long_extnal.c b/languages/cprogs/long_extnal.c
deleted file mode 100644
index 419e1fee..00000000
--- a/languages/cprogs/long_extnal.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Longest Line Program using External Variables*/
-
-#include
-#define MAXLEN 1000
-
-char line[MAXLEN],longest[MAXLEN];
-
-int getline(void);
-void copy(void);
-
-int main(void)
-{
- int len,max;
- max = 0;
- while((len=getline())>0)
- {
- if( len > max)
- {
- max = len;
- copy();
- }
- }
- if( max > 0)
- printf("%s",longest);
-
- return 0;
-}
-int getline()
-{
- int c,i;
-
- for(i=0;i
-#include
-
-int main(int argc, char *argv[])
-{
- mkdir("foobar",'644');
-}
diff --git a/languages/cprogs/mygetchar.c b/languages/cprogs/mygetchar.c
deleted file mode 100644
index 48ccdcde..00000000
--- a/languages/cprogs/mygetchar.c
+++ /dev/null
@@ -1,20 +0,0 @@
-#include
-
-int mygetchar(void);
-
-int main(void)
-{
- int c;
- c = mygetchar();
-
- printf("%c",c);
-
- return 0;
-}
-
-int mygetchar(void)
-{
- char c;
- return (read(0,&c,1)==1)?(unsigned char)c:EOF;
-}
-
diff --git a/languages/cprogs/numlinesort.c b/languages/cprogs/numlinesort.c
deleted file mode 100644
index fd732641..00000000
--- a/languages/cprogs/numlinesort.c
+++ /dev/null
@@ -1,166 +0,0 @@
-/* Sorting program, with a provision of sorting lines numerically as well */
-#include
-#include
-#define MAXLINES 5000 /* maximum number of lines to be sorted */
-char *lineptr[MAXLINES]; /* pointers to text lines */
-
-int readlines(char *lineptr[],int nlines);
-void writelines(char *lineptr[],int nlines);
-
-void myqsort(void *lineptr[],int left,int right,int (*comp)(void *,void *));
-
-int numcmp(char *,char *);
-
-/* sort input lines */
-
-int main(int argc,char *argv[])
-{
- int nlines; /* number of input lines read */
- int numeric = 0; /* if numeric sort */
-
- if( argc > 1 && strcmp(argv[1],"-n") == 0)
- numeric = 1;
- if( (nlines = readlines(lineptr,MAXLINES)) >= 0)
- {
- myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))(numeric ? numcmp:strcmp));
- writelines(lineptr,nlines);
- return 0;
- }
- else
- {
- printf("input too big to sort \n");
- return 1;
- }
-}
-
-/* myqsort: sort v[left] .. v[right] into increasing order */
-
-void myqsort(void *v[],int left,int right,int (*comp)(void *,void *))
-{
- int i,last;
- void swap(void *v[],int,int);
- if(left >= right) /* do nothing if array contains fewer than two elements */
- return;
-
- swap(v,left,(left+right)/2);
- last = left;
-
- for(i = left + 1; i <= right; i++)
- if((*comp)(v[i],v[left])<0)
- swap(v,++last,i);
-
- swap(v,left,last);
- myqsort(v,left,last-1,comp);
- myqsort(v,last+1,right,comp);
-}
-
-#include
-
-/* numcmp: compare s1 and s2 numerically */
-
-int numcmp(char *s1,char *s2)
-{
- double v1,v2;
- v1 = atof(s1);
- v2 = atof(s2);
-
- if( v1 < v2 )
- return -1;
- else if ( v1 > v2)
- return 1;
- else
- return 0;
-}
-
-void swap(void *v[],int i,int j)
-{
- void *temp;
- temp = v[i];
- v[i] = v[j];
- v[j] = temp;
-}
-
-/* for realines and writelines */
-
-#define MAXLEN 1000
-
-int getline(char *,int);
-char *alloc(int);
-
-/* readlines: read input line */
-
-int readlines(char *lineptr[],int maxlines)
-{
- int len,nlines;
- char *p,line[MAXLEN];
-
- nlines = 0;
-
- while((len=getline(line,MAXLEN)) > 0)
- if(nlines >= maxlines || (p=alloc(len)) == NULL)
- return -1;
- else
- {
- line[len-1] = '\0'; /* delete newline */
- strcpy(p,line);
- lineptr[nlines++] = p;
- }
- return nlines;
-}
-
-/* writelines: write output line */
-
-void writelines(char *lineptr[],int nlines)
-{
- int i;
- for(i =0;i < nlines;i++)
- printf("%s\n",lineptr[i]);
-}
-
-
-/* for *alloc(int) */
-
-#define ALLOCSIZE 10000
-
-static char allocbuf[ALLOCSIZE];
-static char *allocp = allocbuf;
-
-char *alloc(int n)
-{
- if(allocbuf + ALLOCSIZE - allocp >= n)
- {
- allocp += n;
- return allocp -n;
- }
- else
- return 0;
-}
-
-void afree(char *p)
-{
- if(p >= allocbuf && p < allocbuf + ALLOCSIZE)
- allocp = p;
-}
-
-
-
-/* getline: read a line into s and return its length */
-
-int getline(char s[],int lim)
-{
- int c,i;
-
- for(i=0;i
-/* echo: command line arguments; 1st version */
-
-int main(int argc,char *argv[])
-{
- int i;
-
- for( i = 1 ; i < argc ;i++ )
- printf("%s %s",argv[i],(i < argc -1)? " ": "");
- printf("\n");
- return 0;
-}
-
-
diff --git a/languages/cprogs/pgechov2.c b/languages/cprogs/pgechov2.c
deleted file mode 100644
index 0c7be6ca..00000000
--- a/languages/cprogs/pgechov2.c
+++ /dev/null
@@ -1,10 +0,0 @@
-#include
-/* echo command-line arguments: 2nd version */
-int main(int argc,char *argv[])
-{
- while(--argc > 0)
- printf("%s %s",*++argv,(argc > 1)? " ": "");
- printf("\n");
- return 0;
-}
-
diff --git a/languages/cprogs/pgechov3.c b/languages/cprogs/pgechov3.c
deleted file mode 100644
index bb1c53d2..00000000
--- a/languages/cprogs/pgechov3.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include
-/*echo command - line arguments: 3rd version */
-int main(int argc,char *argv[])
-{
- while( --argc >0)
- printf((argc > 1)?"%s ":"%s",*++argv);
- printf("\n");
-}
-
diff --git a/languages/cprogs/prepro1.c b/languages/cprogs/prepro1.c
deleted file mode 100644
index d944f2be..00000000
--- a/languages/cprogs/prepro1.c
+++ /dev/null
@@ -1,14 +0,0 @@
-/* # operator in preprocessor */
-#include
-
-#define dprint(expr) printf(#expr " = %d \n",expr);
-
-int main(void)
-{
- int x=10,y=5;
-
- dprint(x/y);
-
- return 0;
-}
-
diff --git a/languages/cprogs/prepro2.c b/languages/cprogs/prepro2.c
deleted file mode 100644
index 79ddd243..00000000
--- a/languages/cprogs/prepro2.c
+++ /dev/null
@@ -1,14 +0,0 @@
-/* ## preprocessor operator */
-
-#include
-
-#define paste(front,back) front ## back
-
-int main(void)
-{
- int i=paste(10,50);
- printf("%d",i);
-
- return 0;
-}
-
diff --git a/languages/cprogs/printd.c b/languages/cprogs/printd.c
deleted file mode 100644
index ae71b154..00000000
--- a/languages/cprogs/printd.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Recursion example; consider printing a number as a character string */
-
-#include
-
-void printd(int n);
-
-int main(void)
-{
- int n;
- n = 15000;
-
- printd(n);
-
- return 0;
-}
-
-void printd(int n)
-{
- if(n < 0)
- {
- putchar('-');
- n = -n;
- }
- if(n / 10)
- printd(n/10);
-
- putchar(n%10+'0');
-}
-
-
diff --git a/languages/cprogs/quicksort.c b/languages/cprogs/quicksort.c
deleted file mode 100644
index a71a482f..00000000
--- a/languages/cprogs/quicksort.c
+++ /dev/null
@@ -1,64 +0,0 @@
-/* quicksort: example of recursive sorting
- Developed by C.A.R. Hoare in 1962. Given an array,one element is chosen and the others are
- partitioned into two subsets - those less than the partition element and those greater than or
- equal to it. The same process is then applied recursively to the two subsets. When a subset has fewer than two elements, it does not need any sorting; this stops the recursion */
-
-#include
-
-void qsort(int v[],int left,int right);
-void swap(int v[],int i,int j);
-
-int main(void)
-{
- int i,left,right,v[10]={43,53,12,64,15,67,87,10,6,90};
- left=0;
- right=9;
-
- printf("Unsorted Array\n");
- for(i=0;i<=9;++i)
- printf(" %d",v[i]);
- qsort(v,left,right);
-
- printf("\nSorted Array\n");
- for(i=0;i<=9;++i)
- printf(" %d",v[i]);
-
- return 0;
-}
-
-void qsort(int v[],int left,int right)
-{
- int i,last;
-
- if(left>=right)
- return;
-
- swap(v,left,(left+right)/2);
-
- last=left;
-
- for(i=left+1;i<=right;i++)
- if(v[i] < v[left])
- swap(v,++last,i);
- swap(v,left,last);
-
- qsort(v,left,last-1);
-
- qsort(v,last+1,right);
-}
-
-/* swap: interchange v[i] and v[j] */
-
-void swap(int v[],int i,int j)
-{
- int temp;
-
- temp = v[i];
-
- v[i] = v[j];
-
- v[j] = temp;
-}
-
-
-
diff --git a/languages/cprogs/rot13.c b/languages/cprogs/rot13.c
deleted file mode 100644
index e80a5615..00000000
--- a/languages/cprogs/rot13.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* rot13 algorithm. Very Simple and Interesting */
-
-#include
-#define ROT 13
-
-int main(void)
-{
- int c,e;
-
- while((c=getchar())!=EOF)
- {
- if(c >='A' && c <='Z')
- {
- if((e = c + ROT) <= 'Z')
- putchar(e);
- else
- {
- e = c - ROT;
- putchar(e);
- }
- }
- else if(c >='a' && c <='z')
- {
- if((e= c + ROT) <= 'z')
- putchar(e);
- else
- {
- e = c - ROT;
- putchar(e);
- }
- }
- else
- putchar(c);
- }
-
-return 0;
-}
-
diff --git a/languages/cprogs/sample_template.c b/languages/cprogs/sample_template.c
deleted file mode 100644
index 89dda472..00000000
--- a/languages/cprogs/sample_template.c
+++ /dev/null
@@ -1,5 +0,0 @@
-#include
-
-int main(int argc, char *argv[]) {
- printf("This program needs to be replaced.");
-}
\ No newline at end of file
diff --git a/languages/cprogs/sec_8.3_open_creat.c b/languages/cprogs/sec_8.3_open_creat.c
index 759ce34c..96f684ae 100644
--- a/languages/cprogs/sec_8.3_open_creat.c
+++ b/languages/cprogs/sec_8.3_open_creat.c
@@ -2,7 +2,7 @@
#include
#include
#include
-#include
+#include
#define PERMS 0666 /* RW for owner, group and others */
diff --git a/languages/cprogs/sec_8_2_read_write.c b/languages/cprogs/sec_8_2_read_write.c
index 9d9e7151..42f96345 100644
--- a/languages/cprogs/sec_8_2_read_write.c
+++ b/languages/cprogs/sec_8_2_read_write.c
@@ -1,8 +1,6 @@
/*copy input to output */
#include
-#include
-
#define BUFSIZ 1024
int main() /* copy input to output */
diff --git a/languages/cprogs/shellsort.c b/languages/cprogs/shellsort.c
deleted file mode 100644
index 7356da4d..00000000
--- a/languages/cprogs/shellsort.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#include
-#include
-
-static void shell_sort(int a[], int size)
-{
- int i, j;
- int h=1;
- do {
- h = h * 3 + 1;
- }while (h <= size);
- do {
- h /= 3;
- for (i = h; i < size; i++)
- {
- int v = a[i];
- for (j = i; j >= h && a[j - h] > v; j -= h)
- a[j] = a[j -h];
- if (i != j)
- a[j] = v;
- }
- }while (h != 1);
-}
-
-int main(int argc, char *argv[])
-{
- int *a;
- int i;
-
- a = (int *)malloc((argc - 1) * sizeof(int));
- for (i = 0; i < argc - 1; i++)
- a[i] = atoi(argv[i+1]);
- shell_sort(a, argc);
-
- for (i = 0; i < argc -1; i++)
- printf("%d", a[i]);
- printf("\n");
- free(a);
- return 0;
-}
diff --git a/languages/cprogs/sizeof_various.c b/languages/cprogs/sizeof_various.c
deleted file mode 100644
index ba9dfb6b..00000000
--- a/languages/cprogs/sizeof_various.c
+++ /dev/null
@@ -1,12 +0,0 @@
-
-#include
-int main(int argc, char *argv[])
-{
- int i=10;
- char c='a';
- float j=1.0;
- printf("The size of int is %zu\n", sizeof i);
- printf("The size of char is %zu\n", sizeof c);
- printf("The size of float is %zu\n", sizeof j);
-}
-
diff --git a/languages/cprogs/sort.c b/languages/cprogs/sort.c
deleted file mode 100644
index 65d70bff..00000000
--- a/languages/cprogs/sort.c
+++ /dev/null
@@ -1,125 +0,0 @@
-#include
-#include
-
-#define MAXLINES 5000 /* max #lines to be sorted */
-
-char *lineptr[MAXLINES];
-
-int readlines(char *lineptr[],int nlines);
-void writelines(char *lineptr[],int nlines);
-
-void qsort(char *lineptr[],int left,int right);
-
-/* sort input lines */
-
-int main(void)
-{
- int nlines; /* number of input lines read */
-
- if((nlines = readlines(lineptr,MAXLINES)) >= 0)
- {
- qsort(lineptr,0,nlines-1);
- writelines(lineptr,nlines);
- return 0;
- }
- else
- {
- printf("error: input too big to sort \n");
- return 1;
- }
-}
-
-#define MAXLEN 1000 /* max length of any input line */
-int getline(char *,int);
-char *alloc(int);
-
-/* readlines: read input lines */
-int readlines(char *lineptr[],int maxlines)
-{
- int len,nlines;
- char *p,line[MAXLEN];
-
- nlines=0;
-
- while((len=getline(line,MAXLEN)) > 0)
- if(nlines >= maxlines || (p=alloc(len)) == NULL)
- return -1;
- else
- {
- line[len-1] = '\0';
- strcpy(p,line);
- lineptr[nlines++]=p;
- }
- return nlines;
-}
-
-/* writelines: write output lines */
-void writelines(char *lineptr[],int nlines)
-{
- int i;
- for(i=0;i= right)
- return;
- swap(v,left,(left+right)/2);
-
- last = left;
-
- for(i=left+1;i<=right;i++)
- if(strcmp(v[i],v[left])<0)
- swap(v,++last,i);
- swap(v,left,last);
- qsort(v,left,last-1);
- qsort(v,last+1,right);
-}
-
-/* swap: interchange v[i] and v[j] */
-
-void swap(char *v[],int i,int j)
-{
- char *temp;
-
- temp=v[i];
- v[i]=v[j];
- v[j]=temp;
-}
-
-#define ALLOCSIZE 10000 /* size of available space */
-
-static char allocbuf[ALLOCSIZE]; /* storage for alloc */
-static char *allocp = allocbuf; /* next free position */
-
-char *alloc(int n) /* return pointer to n characters */
-{
- if(allocbuf + ALLOCSIZE - allocp >= n)
- {
- allocp += n;
- return allocp -n;
- }
- else
- return 0;
-}
-
-int getline(char *s,int lim)
-{
- int c;
- char *t=s;
-
- while(--lim >0 && (c=getchar())!=EOF && c!='\n')
- *s++ = c;
- if( c == '\n')
- *s++ = c;
-
- *s= '\0';
-
- return s-t;
-}
-
diff --git a/languages/cprogs/sortv2.c b/languages/cprogs/sortv2.c
deleted file mode 100644
index 11e10323..00000000
--- a/languages/cprogs/sortv2.c
+++ /dev/null
@@ -1,131 +0,0 @@
-#include
-#include
-
-#define MAXLINES 5000 /* max #lines to be sorted */
-
-char *lineptr[MAXLINES];
-char linestor[MAXLINES];
-
-int readlines(char *lineptr[],char *linestor,int nlines);
-void writelines(char *lineptr[],int nlines);
-
-void qsort(char *lineptr[],int left,int right);
-
-/* sort input lines */
-
-int main(void)
-{
- int nlines; /* number of input lines read */
-
- if((nlines = readlines(lineptr,linestor,MAXLINES)) >= 0)
- {
- qsort(lineptr,0,nlines-1);
- writelines(lineptr,nlines);
- return 0;
- }
- else
- {
- printf("error: input too big to sort \n");
- return 1;
- }
-}
-
-#define MAXLEN 1000 /* max length of any input line */
-#define MAXSTOR 5000
-
-int getline(char *,int);
-char *alloc(int);
-
-/* readlines: read input lines */
-int readlines(char *lineptr[],char *linestor,int maxlines)
-{
- int len,nlines;
- char line[MAXLEN];
- char *p = linestor;
- char *linestop = linestor + MAXSTOR;
-
- nlines=0;
-
- while((len=getline(line,MAXLEN)) > 0)
- if(nlines >= maxlines || p+len > linestop)
- return -1;
- else
- {
- line[len-1] = '\0';
- strcpy(p,line);
- lineptr[nlines++]=p;
- p+=len;
- }
- return nlines;
-}
-
-/* writelines: write output lines */
-void writelines(char *lineptr[],int nlines)
-{
- int i;
- for(i=0;i= right)
- return;
- swap(v,left,(left+right)/2);
-
- last = left;
-
- for(i=left+1;i<=right;i++)
- if(strcmp(v[i],v[left])<0)
- swap(v,++last,i);
- swap(v,left,last);
- qsort(v,left,last-1);
- qsort(v,last+1,right);
-}
-
-/* swap: interchange v[i] and v[j] */
-
-void swap(char *v[],int i,int j)
-{
- char *temp;
-
- temp=v[i];
- v[i]=v[j];
- v[j]=temp;
-}
-
-#define ALLOCSIZE 10000 /* size of available space */
-
-static char allocbuf[ALLOCSIZE]; /* storage for alloc */
-static char *allocp = allocbuf; /* next free position */
-
-char *alloc(int n) /* return pointer to n characters */
-{
- if(allocbuf + ALLOCSIZE - allocp >= n)
- {
- allocp += n;
- return allocp -n;
- }
- else
- return 0;
-}
-
-int getline(char *s,int lim)
-{
- int c;
- char *t=s;
-
- while(--lim >0 && (c=getchar())!=EOF && c!='\n')
- *s++ = c;
- if( c == '\n')
- *s++ = c;
-
- *s= '\0';
-
- return s-t;
-}
-
diff --git a/languages/cprogs/squeezesc.c b/languages/cprogs/squeezesc.c
deleted file mode 100644
index 2bb67e0b..00000000
--- a/languages/cprogs/squeezesc.c
+++ /dev/null
@@ -1,48 +0,0 @@
-/* function squeeze: deletes all the c from s */
-
-#include
-#define MAXLINE 1000
-
-void squeeze(char s[],int c);
-int mgetline(char line[],int maxline);
-
-int main(void)
-{
- char line[MAXLINE];
- int c;
-
- mgetline(line,MAXLINE);
-
- putchar('#');
- c=getchar();
-
- squeeze(line,c);
-
- printf("%s",line);
-
- return 0;
-}
-
-int mgetline(char s[],int lim)
-{
- int i,c;
-
- for(i=0;i
-int strindex(char *s,char *t);
-
-int main(void)
-{
- char *s="This is a line";
- char *t="is";
- int ret;
-
- ret=strindex(s,t);
- printf("%d",ret);
-
- return 0;
-}
-
-int strindex(char *s,char *t)
-{
- char *b=s;
- char *p,*r;
-
- for(;*s!='\0';s++)
- {
- for(p=s,r=t;*r!='\0' && *p==*r;p++,r++)
- ;
-
- if(r>t && *r == '\0')
- return s-b;
- }
- return -1;
-}
diff --git a/languages/cprogs/system-programming/prog1.c b/languages/cprogs/system-programming/prog1.c
deleted file mode 100644
index 773a9599..00000000
--- a/languages/cprogs/system-programming/prog1.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- *
- * Program Description: System Programming Demonstration.
- *
- * Activity 0: http://cs-education.github.io/sys/#/chapter/0/section/0/activity/0
- *
- *
- * Date: 6/24/18
- **/
-
-int write(int, char *, int);
-
-int main(int argc, char *argv[]) {
- write(1, "Hello\n", 6);
-}
diff --git a/languages/cprogs/system-programming/prog2.c b/languages/cprogs/system-programming/prog2.c
deleted file mode 100644
index 97106557..00000000
--- a/languages/cprogs/system-programming/prog2.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- *
- * Program Description: write system call
- *
- * Date: 6/24/18
- **/
-
-#include
-
-int main(int argc, char *argv[]) {
- write(1, "Hello\n", 6);
- write(1, "World\n", 6);
-}
diff --git a/languages/cprogs/system-programming/system-programming-exercises.rst b/languages/cprogs/system-programming/system-programming-exercises.rst
deleted file mode 100644
index 864d42a6..00000000
--- a/languages/cprogs/system-programming/system-programming-exercises.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Programs
-========
-
-* * http://cs-education.github.io/sys/#/chapter/0/section/0/activity/0
diff --git a/languages/cprogs/test_post.py b/languages/cprogs/test_post.py
deleted file mode 100644
index d410442a..00000000
--- a/languages/cprogs/test_post.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import urllib
-import urllib2
-url = 'http://codepad.org'
-
-#with open('helloworld.c') as fd:
-# code = fd.read()
-
-code = "print"
-
-values = {'lang' : 'Python',
- 'code' : code,
- 'submit':'Submit'}
-data = urllib.urlencode(values)
-
-print data
-
-#response = urllib2.urlopen(url, data)
-#the_page = response.geturl()
-#print the_page + '/fork'
-"""
-for href in the_page.split(""):
- if "Link:" in href:
- ind=href.index('Link:')
- found = href[ind+5:]
- for i in found.split('">'):
- if '
-#define MAXLINE 1000
-
-void unescape(char s[],char t[]);
-int getline(char line[],int maxlimit);
-
-int main(void)
-{
- char s[MAXLINE],t[MAXLINE];
-
- getline(t,MAXLINE);
-
- unescape(s,t);
-
- printf("%s",s);
-
- return 0;
-}
-
-void unescape(char s[],char t[])
-{
- int i,j;
-
- for(i=j=0;t[i]!='\0';++i)
- switch(t[i])
- {
- case '\\':
- switch(t[++i])
- {
- case 'n':
- s[j++]='\n';
- break;
- case 't':
- s[j++]='\t';
- break;
- default:
- s[j++]='\\';
- s[j++]=t[i];
- break;
- }
- break;
- default:
- s[j++]=t[i];
- break;
- }
- s[j]='\0';
-}
-
-int getline(char s[],int lim)
-{
- int i,c;
-
- for(i=0;i
-
-std=c99 for long long int types.
-
-Program written under
-Hardware Name: i686
-Processor: i686
-Hardware Platform:i386
-*/
-
-#include
-#include
-
-int main(void)
-{
- printf("Minimum value - Singed Char : %d\n",SCHAR_MIN);
- printf("Maximum value - Signed Char : %d\n",SCHAR_MAX);
- printf("Maximum value - Unsigned Char : %d\n",UCHAR_MAX);
-
- printf("Minimum value - Signed Short Int : %d\n",SHRT_MIN);
- printf("Maximum value - Signed Short Int : %d\n",SHRT_MAX);
- printf("Maximum value - Unsigned Short Int : %d\n",USHRT_MAX);
-
- printf("Minimum value - Signed Int : %d\n",INT_MIN);
- printf("Maximum value - Signed Int : %d\n",INT_MAX);
- printf("Maximum value - Unsigned Int : %u\n",UINT_MAX);
-
- printf("Minimum value - Signed long int : %ld\n",LONG_MIN);
- printf("Maximum value - Signed long int : %ld\n",LONG_MAX);
- printf("Maximum value - Unsigned long int : %lu\n",ULONG_MAX);
-
- printf("Minimum value - Signed long long int: %lld\n",LLONG_MIN);
- printf("Maximum value - Signed long long int: %lld\n",LLONG_MAX);
- printf("Maximum value - Unsigned long long int : %llu\n",ULLONG_MAX);
-
- return 0;
-}
diff --git a/languages/cprogs/wumpus.c b/languages/cprogs/wumpus.c
deleted file mode 100644
index d247286b..00000000
--- a/languages/cprogs/wumpus.c
+++ /dev/null
@@ -1,315 +0,0 @@
-
-/* Hunt the Wumpus Game */
-#include
-#include
-
-/* Program Constants Defined here */
-#define MAPWIDTH 7
-#define MAPHEIGHT 7
-#define NUM_PITS 4
-
-/* Function Prototypes Defined here */
-
-void initMap(char [MAPWIDTH][MAPHEIGHT]);
-void printMap(char [MAPWIDTH][MAPHEIGHT]);
-int move(int,int,int,int,char [MAPWIDTH][MAPHEIGHT]);
-void smell(int,int,char [MAPWIDTH][MAPHEIGHT]);
-int shoot(int,int,int,int,int,char [MAPWIDTH][MAPHEIGHT]);
-
-int main(void)
-{
- int num_arrows = 3; /* Total Number of Arrows */
- char map[MAPWIDTH][MAPHEIGHT]; /* Map of Territory */
- int choice; /* Users Input Command */
- int x,y; /* Current Position of Player */
- int dx,dy; /* Change in Direction */
- int flag; /* Generic Error Flag */
- int action; /* Action 1: -> Move */
- /* Action 2: -> Shoot */
-
- int debug = 1;
-
- /* Intialize Map */
-
- srand(time(NULL));
- initMap(map);
-
- /* Place Player at Random Location */
- /* Make sure you dont place a Player on Wumpus or a in a Pit! */
-
- flag = 1;
- while(flag == 1)
- {
- x = (rand() % 5) + 1;
- y = (rand() % 5) + 1;
-
- if(map[x][y] == '.')
- {
- map[x][y] = '@';
- flag = 0;
- }
- }
-
- printf("Welcome to 'Hunt the Wumpus' \n");
-
- if(debug)
- printMap(map);
-
- smell(x,y,map);
-
- /* Keep prompting for user input */
- do
- {
- printf("Enter a Command: ");
- fflush(stdout);
- choice = getc(stdin);
- printf("\n");
-
- /* Clearing stdin manually */
- if(choice != '\n')
- while(getchar() != '\n')
- ; /* empty statement */
-
- switch(choice)
- {
- /* Movement options */
- case 'n':
- dx = 0;
- dy = -1;
- action = 1;
- break;
- case 's':
- dx = 0;
- dy = +1;
- action =1;
- break;
- case 'e':
- dx = +1;
- dy = 0;
- action =1;
- break;
- case 'w':
- dx = -1;
- dy = 0;
- action =1;
- break;
-
- /* Shoot Options */
-
- case 'N':
- dx = 0;
- dy = -1;
- action = 2;
- break;
- case 'S':
- dx = 0;
- dy = +1;
- action = 2;
- break;
- case 'E':
- dx = +1;
- dy = 0;
- action = 2;
- break;
- case 'W':
- dx = -1;
- dy = 0;
- action = 2;
- break;
-
- default:
- printf("You cannot do that!\n");
- action = 0;
- break;
-
- }
-
- /* Move Player */
-
- if(action == 1)
- {
- flag = move(x,y,dx,dy,map);
- if(flag == 1)
- {
- map[x][y] ='.';
- x = x + dx;
- y = y + dy;
- map[x][y]='@';
-
- }
- else if(flag == -1)
- break;
- }
-
- /* Shoot */
- else if(action == 2)
- {
- flag = shoot(num_arrows--,x,y,dx,dy,map);
- if(flag == -1)
- break;
- }
-
- if(debug)
- printMap(map);
- smell(x,y,map);
-}while(choice != 'Q' || choice !='q');
-
-printf("Press any key to exit..");
-getchar();
-
-return 0;
-}
-
-/* Intialize Map with randomly placed Pits and Randomly placed Wumpus */
-
-void initMap(char map[MAPWIDTH][MAPHEIGHT])
-{
- int i,j;
- int x,y;
-
- /* First create a Clean Slate */
-
- for(j=0;j 0)
- {
- printf("You shoot your arrow into the dark...\n");
-
- if(map[x][y] == 'W')
- {
- printf("\a You have slain a Wumpus!\n");
- return -1;
- }
- else
- {
- printf("And, you can hear it fall to the ground in the next room \n");
- return 0;
- }
- }
- else
- {
- printf("You dont have any more arrows!\n");
- return 0;
- }
-}
diff --git a/languages/letusc/.devcontainer.json b/languages/letusc/.devcontainer.json
deleted file mode 100644
index 370528ce..00000000
--- a/languages/letusc/.devcontainer.json
+++ /dev/null
@@ -1,125 +0,0 @@
-{
- "extensions": [
- "/opt/cs50/extensions/cs50-0.0.1.vsix",
- "/opt/cs50/extensions/phpliteadmin-0.0.1.vsix",
- "/opt/cs50/extensions/workspace-layout-0.0.7.vsix",
- "cs50.ddb50",
- "cs50.extension-uninstaller",
- "ms-python.python",
- "ms-vscode.cpptools",
- "ms-vscode.hexeditor",
- "ms-vsliveshare.vsliveshare-pack",
- "tomoki1207.pdf",
- "vsls-contrib.gitdoc"
- ],
- "image": "ghcr.io/cs50/codespace",
- "postCreateCommand": "/opt/cs50/bin/postCreateCommand",
- "settings": {
- "breadcrumbs.enabled": false,
- "C_Cpp.autocomplete": "Disabled",
- "C_Cpp.codeFolding": "Disabled",
- "C_Cpp.dimInactiveRegions": false,
- "C_Cpp.enhancedColorization": "Enabled",
- "C_Cpp.errorSquiggles": "Disabled",
- "editor.autoClosingQuotes": "never",
- "editor.colorDecorators": false,
- "editor.emptySelectionClipboard": false,
- "editor.folding": false,
- "editor.foldingHighlight": false,
- "editor.hover.enabled": false,
- "editor.lightbulb.enabled": false,
- "editor.matchBrackets": "near",
- "editor.minimap.enabled": false,
- "editor.occurrencesHighlight": false,
- "editor.parameterHints.enabled": false,
- "editor.quickSuggestions": false,
- "editor.renderIndentGuides": false,
- "editor.renderWhitespace": "selection",
- "editor.selectionHighlight": false,
- "editor.semanticTokenColorCustomizations": {
- "[Default Dark+]": {
- "enabled": true,
- "rules": {
- "type": "#569CD6"
- }
- },
- "[Default Light+]": {
- "enabled": true,
- "rules": {
- "type": "#0000FF"
- }
- }
- },
- "editor.suggestOnTriggerCharacters": false,
- "extensions.ignoreRecommendations": true,
- "extension-uninstaller.uninstall": [
- "github.copilot",
- "github.copilot-nightly",
- "tabnine.tabnine-vscode"
- ],
- "files.autoSave": "afterDelay",
- "files.exclude": {
- "**/.*": true
- },
- "files.trimTrailingWhitespace": true,
- "files.watcherExclude": {
- "**/.git/objects/**": true,
- "**/.git/subtree-cache/**": true,
- "**/node_modules/*/**": true
- },
- "git.autofetch": true, /* Disable "Would you like Code to periodically run 'git fetch'?" toast */
- "git.decorations.enabled": false,
- "gitdoc.autoPull": "off",
- "gitdoc.enabled": true,
- "gitdoc.commitMessageFormat": "ddd, MMM D, YYYY, h:mm A Z",
- "gitdoc.commitValidationLevel": "none",
- "gitdoc.pullOnOpen": false,
- "html.suggest.html5": false,
- "javascript.suggest.enabled": false,
- "javascript.validate.enable": false, /* Disable red squiggles */
- "problems.decorations.enabled": false,
- "remote.otherPortsAttributes": {
- "onAutoForward": "silent"
- },
- "scm.countBadge": "off",
- "terminal.integrated.commandsToSkipShell": [
- "workbench.action.toggleSidebarVisibility"
- ],
- "terminal.integrated.defaultProfile.linux": "bash",
- "terminal.integrated.profiles.linux": {
- "bash": {
- "args": [
- "-l"
- ],
- "path": "bash"
- },
- "JavaScript Debug Terminal": null
- },
- "terminal.integrated.persistentSessionReviveProcess": "never",
- "terminal.integrated.sendKeybindingsToShell": true,
- "terminal.integrated.tabs.description": "${task}${separator}${local}", /* Remove cwdFolder from description */
- "terminal.integrated.tabs.showActiveTerminal": "never",
- "window.autoDetectColorScheme": true,
- "workbench.colorCustomizations": {
- "editor.lineHighlightBorder": "#0000", /* Disable gray border-{bottom,top} on active line */
- "editorError.foreground": "#0000", /* Disable red squiggles */
- "editorWarning.foreground": "#0000", /* Disable yellow squiggles */
- "editorGutter.addedBackground": "#0000",
- "editorGutter.deletedBackground": "#0000",
- "editorGutter.modifiedBackground": "#0000", /* Disable yellow bars to left of lines modified since last commit */
- "[GitHub Light Default]": {
- "terminal.foreground": "#000000" /* Change terminal font color to #000 for GitHub Light Default theme */
- }
- },
- "workbench.editor.closeOnFileDelete": true,
- "workbench.editor.untitled.hint": "hidden",
- "workbench.enableExperiments": false,
- "workbench.iconTheme": "vs-minimal", /* Simplify icons */
- "workbench.preferredDarkColorTheme": "Default Dark+",
- "workbench.preferredLightColorTheme": "Default Light+",
- "workbench.startupEditor": "none",
- "workbench.statusBar.visible": false,
- "workbench.tips.enabled": false,
- "workbench.welcomePage.walkthroughs.openOnInstall": false
- }
-}
diff --git a/languages/python/8queens.py b/languages/python/8queens.py
deleted file mode 100644
index e27ee489..00000000
--- a/languages/python/8queens.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from itertools import permutations
-
-# What's the difference between permutations and combinations.
-# permutations is about arrangements.
-# combinations is about choosing.
-
-
-def eight_queens():
- queens = list(range(8))
- for pos in permutations(queens):
- # how many times is the if statement below evaluated?
- # How does subtracting and addition the position work?
- if (8 == len(set(pos[i] + i for i in queens))
- == len(set(pos[i] - i for i in queens))):
- print(pos)
-
-
-if __name__ == '__main__':
- eight_queens()
diff --git a/languages/python/Queue.py b/languages/python/Queue.py
deleted file mode 100644
index 93a62931..00000000
--- a/languages/python/Queue.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""
-Simple implementation of a Queue datastructure in Python.
-"""
-class Queue:
- def __init__(self, items = None):
- if items is None:
- items = []
- self.__queue = items
-
- def __repr__(self):
- return str(self.__queue)
-
- def isempty(self):
- return len(self.__queue) == 0
-
- def enqueue(self, item):
- self.__queue.append(item)
-
- def dequeue(self):
- return self.__queue.pop(0)
-
- def peek(self):
- return self.__queue[0]
-
-if __name__ == '__main__':
- q = Queue()
- q.enqueue(10)
- q.enqueue(20)
- q.enqueue(30)
- q.enqueue(40)
- print(q)
- print(q.peek())
- q.dequeue()
- print(q)
diff --git a/languages/python/README b/languages/python/README
deleted file mode 100644
index d74d6425..00000000
--- a/languages/python/README
+++ /dev/null
@@ -1,29 +0,0 @@
-Categories of Python Programs
------------------------------
-
-Try to classify each of the program into any of these categories.
-And rename the python program as category_name_program_name_#number.py
-
-* text_manipulation
- - This category demonstrates text manipulation. It reads input and applies
- simple text manipulation and provides the output. Many programs fall into this category.
-* networking
- - This program demonstrates networking and socket calls. Anything to do with servers and clients.
-* web
- - These deal with websites, webapplications and work on top of networking layer.
-* design
- - These programs demonstrate software design ascepts. These can be pretty
- deep as, "why" it is done so is not obvious, but the program usually
- demonstrates how it is done.
-* algorithm
- - This is an implementation of a well known CS algorithm.
-* software_engineering
- - This is how software is built in real world. If your software needs to
- make money, you will need to take care of these aspects.
-
-
-For e.g, I renamed these programs:
-
- renamed: context_1.py -> design_context_manager_1.py
- renamed: client.py -> networking_socket_client.py
-
diff --git a/languages/python/algorithm_binary_representation.py b/languages/python/algorithm_binary_representation.py
deleted file mode 100644
index c50153bd..00000000
--- a/languages/python/algorithm_binary_representation.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""
-Program to do binary representation of various interesting ints.
-"""
-
-
-def convert_to_binary(n):
- binary = []
- while n:
- binary.append(str(n % 2))
- n /= 2
- binary.reverse()
- return "".join(binary)
-
-
-for i in range(20, 30):
- print((i, convert_to_binary(i)))
-
-hexa_values = ['0', '1', 'A', 'FF', 'DEADBEEF', 'CAFEBABE']
-
-for each in hexa_values:
- dec = int(each, 16)
- print((each, convert_to_binary(dec)))
-
-"""
-Find out if the machine is storing it in the one's complement or two's
-complement.
-1 is stored as 0000 0001
--1 in 1's complement is 1111 1110
--1 in 2's complement is 1111 1111
-"""
-
-import struct
-
-if ord(struct.pack('b', -1)[0]) == 255:
- print('twos complement')
-else:
- print('ones complement')
-
-for i in range(200, 255):
- print((hex(i)))
-
-for i in range(0, 256):
- print((chr(i), i, hex(i)))
-
-"""
-Binary Addition and Subtraction
-"""
-a = 20
-b = 10
-
-a_bin = convert_to_binary(a)
-b_bin = convert_to_binary(b)
-
-if len(a_bin) > len(b_bin):
- b_bin = b_bin.rjust(len(a_bin), '0')
-elif len(a_bin) < len(b_bin):
- a_bin = a_bin.rjust(len(b_bin), '0')
-
-
-def sum_bin(a, b):
- rules = {('0', '0'): (0, 0),
- ('0', '1'): (1, 0),
- ('1', '0'): (1, 0),
- ('1', '1'): (0, 1)
- }
- carry = 0
- sum = 0
- result = ""
- for x, y in zip(reversed(a), reversed(b)):
- sum = rules[(x, y)][0]
- if carry:
- sum = rules[(str(sum), str(carry))][0]
- result += str(sum)
- carry = rules[(x, y)][1]
-
- if carry:
- result += str(1)
-
- return result[::-1]
-
-
-def sub_bin(a, b):
- ones_complement = ""
- for c in b:
- if c == '0':
- ones_complement += '1'
- elif c == '1':
- ones_complement += '0'
-
- b = ones_complement
- b = sum_bin(b, '1'.rjust(len(b), '0'))
-
- rules = {('0', '0'): (0, 0),
- ('0', '1'): (1, 0),
- ('1', '0'): (1, 0),
- ('1', '1'): (0, 1)
- }
-
- carry = 0
- sum = 0
- result = ""
- for x, y in zip(reversed(a), reversed(b)):
- sum = rules[(x, y)][0]
- if carry:
- sum = rules[(str(sum), str(carry))][0]
- result += str(sum)
- carry = rules[(x, y)][1]
- # unlike addition carry should be discarded.
-
- return result[::-1]
-
-
-print(('a', a, a_bin))
-print(('b', b, b_bin))
-
-print(('a+b ', sum_bin(a_bin, b_bin)))
-print(('a-b ', sub_bin(a_bin, b_bin)))
diff --git a/languages/python/algorithm_binary_search.py b/languages/python/algorithm_binary_search.py
deleted file mode 100644
index 34bb4f40..00000000
--- a/languages/python/algorithm_binary_search.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import random
-
-def find_in_sorted(arr, x):
- def binsearch(start, end):
- if start == end:
- return -1
- mid = start + (end - start) // 2
- if x < arr[mid]:
- return binsearch(start, mid)
- elif x > arr[mid]:
- return binsearch(mid+1, end)
- else:
- return mid
- return binsearch(0, len(arr))
-
-
-ar = sorted(random.sample(list(range(10)),9))
-r = random.randint(0,10)
-print((find_in_sorted(ar,r)))
diff --git a/languages/python/algorithm_cellauto.py b/languages/python/algorithm_cellauto.py
deleted file mode 100644
index 85c76685..00000000
--- a/languages/python/algorithm_cellauto.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-"""
- CellularAutomata.py: Wolfram-style cellular automata in Python
-
- Options:
- -h # Use a screen of height # for the simulation
- -w # Use a screen of width # for the simulation
- -r Use a random initial row (rather than the standard single 1 in the middle)
- -R # Use rule # for the simulation
-
-Requires python-image (PIL package) installed.
-Fills up an initial cell and runs a particular rule of Cellular Automata.
-
-.. image:: https://lh4.googleusercontent.com/_ny1HYbb2lDw/Tazon5TsgXI/AAAAAAAAKgU/ud6v_XhcHB0/s288/bs.png
-
-*I can't remember the source, if you claim/know, please inform.*
-
-"""
-
-import getopt,sys
-from random import randint
-
-
-def ca_data(height,width,dorandom,rulenum):
- # Create the first row, either randomly, or with a single 1
- if dorandom:
- first_row = [randint(0,1) for i in range(width)]
- else:
- first_row = [0]*width
- first_row[width/2] = 1
- results = [first_row]
-
- # Convert the rule number to a list of outcomes.
- rule = [(rulenum/pow(2,i)) % 2 for i in range(8)]
-
- for i in range(height-1):
- data = results[-1]
- # Determine the new row based on the old data. We first make an
- # integer out of the value of the old row and its two neighbors
- # and then use that value to get the outcome from the table we
- # computed earlier
- new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]]
- for j in range(width)]
- results.append(new)
- return results
-
-def pil_render(data,height,width,fname="bs.png"):
- import Image, ImageDraw
- img = Image.new("RGB",(width,height),(255,255,255))
- draw = ImageDraw.Draw(img)
-
- for y in range(height):
- for x in range(width):
- if data[y][x]: draw.point((x,y),(0,0,0))
- img.save(fname,"PNG")
- return
-
-def main():
- opts,args = getopt.getopt(sys.argv[1:],'h:w:rR:')
- height = 500
- width = 500
- dorandom = 0
- rule = 22
- for key,val in opts:
- if key == '-h': height = int(val)
- if key == '-w': width = int(val)
- if key == '-r': dorandom = 1
- if key == '-R': rule = int(val)
- data = ca_data(height,width,dorandom,rule)
- pil_render(data,height,width)
- return
-
-if __name__ == '__main__': main()
diff --git a/languages/python/algorithm_checking_string_text_or_binary.py b/languages/python/algorithm_checking_string_text_or_binary.py
deleted file mode 100644
index fa6b4ef3..00000000
--- a/languages/python/algorithm_checking_string_text_or_binary.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""
-This program checks if a string is a text or binary.
-This snippet is from Python Cookbook.
-"""
- # ensure / does not truncate
-import string
-text_characters = "".join(map(chr, list(range(32, 127)))) + "\n\r\t\b"
-_null_trans = string.maketrans("","")
-
-def istext(s, text_characters=text_characters, threshold=0.30):
- # if s contains any null, then it is not text:
- if '\0' in s:
- return False
- # An empty string is still a text
- if not s:
- return True
- # Get the substring of s made of non-text characters
- t = s.translate(_null_trans, text_characters)
- # s is 'text' if less than 30% of its characters are non-text ones:
- return len(t)/len(s) <=threshold
-
-print("Hello, World ", istext("Hello, World"))
-print("\xc3\xa4", istext("\xc3\xa4"))
diff --git a/languages/python/algorithm_eratosthenes.py b/languages/python/algorithm_eratosthenes.py
deleted file mode 100644
index 14d0493a..00000000
--- a/languages/python/algorithm_eratosthenes.py
+++ /dev/null
@@ -1,15 +0,0 @@
-def eratosthenes():
- D = {}
- q = 2
- while True:
- p = D.pop(q, None)
- if p:
- x = p + q
- while x in D:
- x += p
- D[x] = p
- else:
- D[q*q] = q
- yield q
- q += 1
-
diff --git a/languages/python/algorithm_fact2.py b/languages/python/algorithm_fact2.py
deleted file mode 100644
index 8e385ba4..00000000
--- a/languages/python/algorithm_fact2.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import operator
-from functools import reduce
-print(reduce(operator.mul, range(1,10)))
diff --git a/languages/python/algorithm_fibo.py b/languages/python/algorithm_fibo.py
deleted file mode 100644
index ab10593c..00000000
--- a/languages/python/algorithm_fibo.py
+++ /dev/null
@@ -1,14 +0,0 @@
-def fibo(n):
- if n == 0:
- return 0
- if n == 1:
- return 1
- return (fibo(n-2) + fibo(n-1))
-
-print(fibo(0))
-print(fibo(1))
-print(fibo(2))
-print(fibo(3))
-print(fibo(4))
-print(fibo(5))
-print(fibo(6))
diff --git a/languages/python/algorithm_graph.py b/languages/python/algorithm_graph.py
deleted file mode 100644
index 50648007..00000000
--- a/languages/python/algorithm_graph.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""
-Simplest possible graph representation.abs
-
-In theory, Graph is represented with vertices "V" and edges "E". We use the same notation here.
-
-Expected Output
----------------
-
-['a', 'c', 'b']
-True
-True
-"""
-
-class Graph:
- def __init__(self , g):
- self.g = g
-
- def V(self):
- return list(self.g.keys())
-
- def E(self, node1, node2):
- return node2 in self.g[node1]
-
-if __name__ == '__main__':
- gobject = Graph({"a":["b","c"],"b":["e","c"],"c":["a","b"]})
- print((gobject.V()))
- print((gobject.E("a","c")))
- print((gobject.E("b","e")))
diff --git a/languages/python/algorithm_hanoi.py b/languages/python/algorithm_hanoi.py
deleted file mode 100644
index ecf39de3..00000000
--- a/languages/python/algorithm_hanoi.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-# Towers of Hanoi program.
-
-disks = 3
-from_tower = 'A'
-to_tower = 'C'
-using_tower = 'B'
-
-def hanoi(n, from_tower, to_tower, using_tower):
- if n > 0:
- hanoi(n-1, from_tower, using_tower, to_tower)
- print('move disk from ', from_tower, ' to ', to_tower)
- hanoi(n-1, using_tower, to_tower, from_tower)
-
-hanoi(disks, from_tower, to_tower, using_tower)
diff --git a/languages/python/algorithm_insertion.py b/languages/python/algorithm_insertion.py
deleted file mode 100644
index bcef1a2d..00000000
--- a/languages/python/algorithm_insertion.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import random
-list_to_sort = random.sample(list(range(10)),8)
-
-def insertion_sort(listtosort):
- for i in range(1,len(listtosort)):
- key = listtosort[i]
- j = i - 1
- while ( j > 0) and (key < listtosort[j]):
- listtosort[j+1] = listtosort[j]
- j -= 1
- listtosort[j] = key
- return listtosort
-
-print(list_to_sort)
-print(insertion_sort(list_to_sort))
-
diff --git a/languages/python/algorithm_int_to_roman.py b/languages/python/algorithm_int_to_roman.py
deleted file mode 100644
index 6988e5f5..00000000
--- a/languages/python/algorithm_int_to_roman.py
+++ /dev/null
@@ -1,171 +0,0 @@
-# Program which converts the given input integer to roman numeral.
-# Limitation: Program converts the integer numbers uptil the value of 1000
-# (Roman Numeral: D)
-# Problem: P2.1 - Implement a translator from integers to roman numeral based
-# on the syntax directed translation scheme developed in Exercise 2.9
-# Chapter 2 - A Simple One-Pass Compiler. Compilers, Principles, Techniques
-# and Tools.
-
-
-roman_dict = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
-
-def sep_num(n):
- num = []
- if n/100:
- hundreds = (n/100) * 100
- num.append(hundreds)
- n = n%100
- tens = (n/10) * 10
- if tens:
- num.append(tens)
- ones = n%10
- if ones:
- num.append(ones)
- elif n/10:
- tens = (n/10) * 10
- num.append(tens)
- ones = n%10
- if ones:
- num.append(ones)
- else:
- ones = n
- num.append(ones)
- return num
-
-def get_roman(n):
- rnos = []
- if n in roman_dict:
- rnos.append(n)
- return rnos
- else:
- if 1 < n < 5:
- base,factor = 1,1
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base = base
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
- elif 5 < n < 10:
- base,factor = 5,1
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base_index = indices.index(base) - 1
- prev_base = indices[prev_base_index]
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
- elif 10 < n <50:
- base,factor = 10,10
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base = base
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
- elif 50 < n < 100:
- base, factor = 50,10
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base_index = indices.index(base) - 1
- prev_base = indices[prev_base_index]
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
- elif 100 < n < 500:
- base, factor = 100, 100
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base = base
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
- elif 500 < n < 1000:
- base, factor = 500, 100
- rnos.append(base)
- result = n - base
- while result > 0:
- rnos.append(factor)
- result = result - factor
- if rnos.count(factor) > 3:
- for n in rnos[:]:
- rnos.remove(n)
- indices = list(roman_dict.keys())
- indices.sort()
- prev_base_index = indices.index(base) - 1
- prev_base = indices[prev_base_index]
- base_index = indices.index(base) + 1
- base = indices[base_index]
- rnos.append(prev_base)
- rnos.append(base)
- return rnos
-
-
-def main():
- number = int(input("Enter the Integer: "))
- if number > 1000:
- print('Sorry, I know uptil 1000 only.')
- exit()
- if number in roman_dict:
- print("Roman: ",roman_dict[number])
- else:
- romans = []
- res = sep_num(number)
- for each in res:
- rvalues = get_roman(each)
- for value in rvalues:
- romans.append(roman_dict[value])
- print("Roman: ",''.join(romans))
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/algorithm_locate.py b/languages/python/algorithm_locate.py
deleted file mode 100644
index 224626d9..00000000
--- a/languages/python/algorithm_locate.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import fnmatch
-import os
-
-def locate(pattern, root=os.getcwd()):
- for path, dirs, files in os.walk(root):
- for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
- yield filename
diff --git a/languages/python/algorithm_maxsort.py b/languages/python/algorithm_maxsort.py
deleted file mode 100644
index c5088d73..00000000
--- a/languages/python/algorithm_maxsort.py
+++ /dev/null
@@ -1,12 +0,0 @@
-def maxsort(A):
- size = len(A) -1
- for i in range(0,size):
- max_index = 0
- for j in range(0, (size -i)+1):
- if A[j] > A[max_index]:
- max_index = j
- A[size-i], A[max_index] = A[max_index], A[size-i]
-
-A = [5,4,3,2,1]
-maxsort(A)
-print(A)
diff --git a/languages/python/algorithm_mergesort.py b/languages/python/algorithm_mergesort.py
deleted file mode 100644
index eec9e53b..00000000
--- a/languages/python/algorithm_mergesort.py
+++ /dev/null
@@ -1,40 +0,0 @@
-import random
-import math
-
-def merge(left,right):
- result = []
- while left and right:
- if left[0] < right[0]:
- result.append(left.pop(0))
- else:
- result.append(right.pop(0))
- if left:
- result.extend(left)
- else:
- result.extend(right)
- return result
-
-def mergesort(m):
- left = []
- right = []
- result = []
-
- if len(m) <=1:
- return m
- middle = len(m)/2
-
- left = m[:middle]
- right = m[middle:]
-
- left = mergesort(left)
- right = mergesort(right)
-
- if left[-1] > right[0]:
- result = merge(left, right)
- else:
- result = left + right
- return result
-
-p = random.sample(list(range(10)),8)
-print(p)
-print(mergesort(p))
diff --git a/languages/python/algorithm_npuzzle.py b/languages/python/algorithm_npuzzle.py
deleted file mode 100644
index b946d61c..00000000
--- a/languages/python/algorithm_npuzzle.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# vim: ts=4 sw=4 et ai ff=unix ft=python nowrap
-#
-# Program: npuzzle.py
-#
-# Description: Solves the N-Puzzle Sliding Block Problem.
-#
-# Usage: python npuzzle.py.
-#
-# License: GNU GPL Version 2.0. Please refer www.gnu.org.
-
-import random
-
-
-class State:
-
- def __init__(self, nsize):
- """Initialze the n-puzzle problem, with n-size value, tsize the total nodes and initial the goal state from n.
- """
-
- self.nsize = nsize
- self.tsize = pow(self.nsize, 2)
- self.goal = list(range(1, self.tsize))
- self.goal.append(0)
-
- def printst(self, st):
- """Print the list in a Matrix Format."""
-
- for (index, value) in enumerate(st):
- print(' %s ' % value, end=' ')
- if index in [x for x in range(self.nsize - 1, self.tsize,
- self.nsize)]:
- print()
- print()
-
- def getvalues(self, key):
- """Utility function to gather the Free Motions at various key positions in the Matrix."""
-
- values = [1, -1, self.nsize, -self.nsize]
- valid = []
- for x in values:
- if 0 <= key + x < self.tsize:
- if x == 1 and key in range(self.nsize - 1, self.tsize,
- self.nsize):
- continue
- if x == -1 and key in range(0, self.tsize, self.nsize):
- continue
- valid.append(x)
- return valid
-
- def expand(self, st):
- """Provide the list of next possible states from current state."""
-
- pexpands = {}
- for key in range(self.tsize):
- pexpands[key] = self.getvalues(key)
- pos = st.index(0)
- moves = pexpands[pos]
- expstates = []
- for mv in moves:
- nstate = st[:]
- (nstate[pos + mv], nstate[pos]) = (nstate[pos], nstate[pos +
- mv])
- expstates.append(nstate)
- return expstates
-
- def one_of_poss(self, st):
- """Choose one of the possible states."""
-
- exp_sts = self.expand(st)
- rand_st = random.choice(exp_sts)
- return rand_st
-
- def start_state(self, seed=1000):
- """Determine the Start State of the Problem."""
-
- start_st = (self.goal)[:]
- for sts in range(seed):
- start_st = self.one_of_poss(start_st)
- return start_st
-
- def goal_reached(self, st):
- """Check if the Goal Reached or Not."""
-
- return st == self.goal
-
- def manhattan_distance(self, st):
- """Calculate the Manhattan Distances of the particular State.
- Manhattan distances are calculated as Total number of Horizontal and Vertical moves required by the values in the current state to reach their position in the Goal State.
- """
-
- mdist = 0
- for node in st:
- if node != 0:
- gdist = abs(self.goal.index(node) - st.index(node))
- (jumps, steps) = (gdist // self.nsize, gdist % self.nsize)
- mdist += jumps + steps
- return mdist
-
- def huristic_next_state(self, st):
- """This is the Huristic Function. It determines the next state to follow and uses Mahattan distances method as the huristics. This this determined way, a A* approach for path finding is used.
-If more than one path have same manhattan distance, then a random choice of one of them is analyzed and carried forward. If not best path, randomness to providethe other choice is relied upon. No Depth First search is Used."""
-
- exp_sts = self.expand(st)
- mdists = []
- for st in exp_sts:
- mdists.append(self.manhattan_distance(st))
- mdists.sort()
- short_path = mdists[0]
- if mdists.count(short_path) > 1:
- least_paths = [st for st in exp_sts if self.manhattan_distance(st) == short_path]
- return random.choice(least_paths)
- else:
- for st in exp_sts:
- if self.manhattan_distance(st) == short_path:
- return st
-
- def solve_it(self, st):
- while not self.goal_reached(st):
- st = self.huristic_next_state(st)
- self.printst(st)
-
-
-if __name__ == '__main__':
- print('N-Puzzle Solver!')
- print(10 * '-')
- state = State(3)
- print('The Starting State is:')
- start = state.start_state(5)
- state.printst(start)
- print('The Goal State should be:')
- state.printst(state.goal)
- print('Here it Goes:')
- state.printst(start)
- state.solve_it(start)
-
-
diff --git a/languages/python/algorithm_pyex2_multiprocessing.py b/languages/python/algorithm_pyex2_multiprocessing.py
deleted file mode 100644
index ceb641c5..00000000
--- a/languages/python/algorithm_pyex2_multiprocessing.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from multiprocessing import Pool
-
-def factorial(N, dictionary):
- "Compute a Factorial"
-
-p = Pool(5)
-result = p.map(factorial, list(range(1,1000,10)))
-for v in result:
- print(v)
diff --git a/languages/python/algorithm_pyex_multiprocessing.py b/languages/python/algorithm_pyex_multiprocessing.py
deleted file mode 100644
index e09f5749..00000000
--- a/languages/python/algorithm_pyex_multiprocessing.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import time
-from multiprocessing import Process, Queue
-
-def factorial(queue, N):
- "Compute a factorial."
- # If N is a multiple of 4, this function will take much longer.
- if (N % 4) == 0:
- time.sleep(0.05 * N/4)
-
- # Calculate the result
- fact = 1
- for i in range(1, N+1):
- fact = fact * i
-
- # Put the result back into the Queue
- queue.put(fact)
-
-if __name__ == '__main__':
- queue = Queue()
-
- N = 5
-
- p = Process(target=factorial, args=(queue, N))
- p.start()
- p.join()
-
- result = queue.get()
-
- print('Factorial', N, '=', result)
diff --git a/languages/python/algorithm_quicksort.py b/languages/python/algorithm_quicksort.py
deleted file mode 100644
index b354674e..00000000
--- a/languages/python/algorithm_quicksort.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# Quick sort in Python
-
-# The basic idea behind Quick Sort is to first find an element Pivot from the array
-# Based on pivot element, the array is sorted such that all the elements to the left of pivot are smaller
-# than pivot and elements to right of pivot are greater than pivot
-# The same process is repeated in the left and right sub array of the pivot.
-
-
-# function to find the partition position
-def partition(array, low, high):
-
- # choose the rightmost element as pivot
- pivot = array[high]
-
- # pointer for greater element
- i = low - 1
-
- # traverse through all elements
- # compare each element with pivot
- for j in range(low, high):
- if array[j] <= pivot:
- # if element smaller than pivot is found
- # swap it with the greater element pointed by i
- i = i + 1
-
- # swapping element at i with element at j
- (array[i], array[j]) = (array[j], array[i])
-
- # swap the pivot element with the greater element specified by i
- (array[i + 1], array[high]) = (array[high], array[i + 1])
-
- # return the position from where partition is done
- return i + 1
-
-def quickSort(array, low, high):
- if low < high:
-
- # find pivot element such that
- # element smaller than pivot are on the left
- # element greater than pivot are on the right
- pi = partition(array, low, high)
-
- # recursive call on the left of pivot
- quickSort(array, low, pi - 1)
-
- # recursive call on the right of pivot
- quickSort(array, pi + 1, high)
-
-
-data = [10, 11, 3, 5, 16, 34, 15]
-print("Unsorted Array")
-print(data)
-
-size = len(data)
-
-quickSort(data, 0, size - 1)
-
-print('Sorted Array in Ascending Order:')
-print(data)
diff --git a/languages/python/algorithm_scrmable.py b/languages/python/algorithm_scrmable.py
deleted file mode 100644
index cc3245c7..00000000
--- a/languages/python/algorithm_scrmable.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-# Cphryigot: O.R.Senthil Kumaran
-#
-# Inrpeisd from jwz scrmable: http://www.jwz.org/hacks/scrmable.pl
-#
-# Tihs pgrarom is fere sortfwae; you can rrtiestiubde it ad/onr mdfioy
-# it udenr the tmers of the GNU Graneel Pbuilc Liscene as phlibsued by
-# the Fere Sfwartoe Fanouiodtn; eeihtr vierosn 2 of the Liscene, or
-# (at your opotin) any leatr vierosn.
-#
-# Tihs pgrarom is diisertbtud in the hope taht it will be uusfel,
-# but WTHOIUT ANY WRAANRTY; whitout eevn the iipemld watrarny of
-# MNTIBRAEAHCITLY or FNTIESS FOR A PTULACRIAR PURPSOE. See the
-# GNU Graneel Pbuilc Liscene for mroe dalites.
-#
-# You suolhd have reievced a copy of the GNU Graneel Pbuilc Liscene
-# along wtih tihs pgrarom; if not, wtire to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-import random
-import sys
-
-
-def mxiup(ecah_wrod):
- if len(ecah_wrod) <= 2:
- return ecah_wrod
- else:
- nwewrod = ecah_wrod[0]
- if ecah_wrod[-1] in ['.', ',', ':', ';', '-', '?', '!']:
- inbet = ecah_wrod[1:-2]
- for each in random.sample(list(inbet), len(inbet)):
- nwewrod += each
- nwewrod += ecah_wrod[-2]
- else:
- inbet = ecah_wrod[1:-1]
- for each in random.sample(list(inbet), len(inbet)):
- nwewrod += each
- nwewrod += ecah_wrod[-1]
- return nwewrod
-
-
-def srcambel(line):
- mixedwrods = []
- wrods = line.split()
- for ecah_wrod in wrods:
- mixedwrods.append(mxiup(ecah_wrod))
- for w, m in zip(wrods, mixedwrods):
- line = line.replace(w, m)
- print(line, end='')
-
-
-def getgraparaph():
- line = sys.stdin.read()
- return line
-
-
-def mian():
- try:
- line = getgraparaph()
- srcambel(line)
- except (EOFError, KeyboardInterrupt):
- sys.exit(0)
-
-
-mian()
diff --git a/languages/python/algorithm_spelling.py b/languages/python/algorithm_spelling.py
deleted file mode 100644
index e3e0a522..00000000
--- a/languages/python/algorithm_spelling.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import re, collections
-
-def words(text): return re.findall('[a-z]+', text.lower())
-
-def train(features):
- model = collections.defaultdict(lambda: 1)
- for f in features:
- model[f] += 1
- return model
-
-NWORDS = train(words(file('big.txt').read()))
-
-alphabet = 'abcdefghijklmnopqrstuvwxyz'
-
-def edits1(word):
- splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
- deletes = [a + b[1:] for a, b in splits if b]
- transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
- replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
- inserts = [a + c + b for a, b in splits for c in alphabet]
- return set(deletes + transposes + replaces + inserts)
-
-def known_edits2(word):
- return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
-
-def known(words): return set(w for w in words if w in NWORDS)
-
-def correct(word):
- candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
- return max(candidates, key=NWORDS.get)
diff --git a/languages/python/algorithm_splitter.py b/languages/python/algorithm_splitter.py
deleted file mode 100644
index 59f3a367..00000000
--- a/languages/python/algorithm_splitter.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from string import ascii_lowercase
-from itertools import combinations
-
-HEADER = "whatever\n"
-
-def splitter(chunksize, source, outputprefix):
- input = open(source)
- counter = 0
- for suffix in (''.join(pair) for pair in combinations(ascii_lowercase, 2)):
- with open(outputprefix + suffix, 'w') as output:
- chunk = input.read(chunksize)
- if not chunk.endswith('\n'):
- lastln = chunk.rfind('\n')
- chunksize = chunksize - lastsize
- output.write(HEADER)
- output.write(chunk)
- if len(chunk) < chunksize:
- return
-
-splitter(15,'data.big','foo')
diff --git a/languages/python/algorithm_syllablecount.py b/languages/python/algorithm_syllablecount.py
deleted file mode 100644
index 8761e5b2..00000000
--- a/languages/python/algorithm_syllablecount.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# written by kennenth gonsalves
-
-import codecs
-
-def countsyll(instring):
- """This function counts the number of characters in a tamil string
- This is done by ignoring the vowel additions. If one uses the len
- function, the sample string has a length of 17 - but there are actually
- only 11 characters"""
- s = codecs.utf_8_encode(instring)
- print(s)
- x = codecs.utf_8_decode(s[0])[0]
- print(repr(x))
- syllen = 0
- vowels = ['\u0bbe','\u0bbf','\u0bc0',
- '\u0bc1','\u0bc2','\u0bc6',
- '\u0bc7','\u0bc8','\u0bca',
- '\u0bcb','\u0bcc','\u0bcd',]
- for y in x:
- if y not in vowels:
- syllen += 1
- return syllen
-
-if __name__=='__main__':
- print(countsyll('ஆண்டவரின் துணைவன்'))
diff --git a/languages/python/algorithm_toss_coins.py b/languages/python/algorithm_toss_coins.py
deleted file mode 100644
index bde42348..00000000
--- a/languages/python/algorithm_toss_coins.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# Example showing tossing of coins
-
-import random
-
-heads = tails = count = 0
-choice = ''
-
-while choice.lower() != 'q':
- count = count + 1
- choice = random.choice(["heads","tails"])
- if choice == "heads":
- heads = heads + 1
- else:
- tails = tails + 1
- print(choice)
- choice = input("Press any key to continue or q to quit")
-
-print('Total :', count)
-print('Heads :', str(heads), ' Percentage ', ((heads * 1.0)/count) * 100)
-print('Tails :', str(tails), ' Percentage ', ((tails * 1.0)/count) * 100)
diff --git a/languages/python/algorithm_traversal.py b/languages/python/algorithm_traversal.py
deleted file mode 100644
index 29508795..00000000
--- a/languages/python/algorithm_traversal.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from collections import deque
-
-
-def bfs(g, start):
- queue, enqueued = deque([(None, start)]), set([start])
- while queue:
- parent, n = queue.popleft()
- yield parent, n
- new = set(g[n]) - enqueued
- enqueued |= new
- queue.extend([(n, child) for child in new])
-
-def dfs(g, start):
- stack, enqueued = [(None, start)], set([start])
- while stack:
- parent, n = stack.pop()
- yield parent, n
- new = set(g[n]) - enqueued
- enqueued |= new
- stack.extend([(n, child) for child in new])
-
-def shortest_path(g, start, end):
- parents = {}
- for parent, child in bfs(g, start):
- parents[child] = parent
- if child == end:
- revpath = [end]
- while True:
- parent = parents[child]
- revpath.append(parent)
- if parent == start:
- break
- child = parent
- return list(reversed(revpath))
- return None # or raise appropriate exception
-
-if __name__ == '__main__':
- # a sample graph
- graph = {'A': ['B', 'C','E'],
- 'B': ['A','C', 'D'],
- 'C': ['D'],
- 'D': ['C'],
- 'E': ['F', 'D'],
- 'F': ['C']}
-
- for node in bfs(graph,'A'):
- print(node)
diff --git a/languages/python/algorithm_tree2.py b/languages/python/algorithm_tree2.py
deleted file mode 100644
index 510fb387..00000000
--- a/languages/python/algorithm_tree2.py
+++ /dev/null
@@ -1,41 +0,0 @@
-class Node:
- def __init__(self, value, left=None, right=None):
- self.value = value
- self.left = left
- self.right = right
-
-n1 = Node(1)
-n2 = Node(2)
-n3 = Node(3,n1,n2)
-n4 = Node(4)
-n5 = Node(5,n4,n3)
-
-print('Inorder')
-def inorder(n):
- if n == None:
- return
- inorder(n.left)
- print(n.value)
- inorder(n.right)
-
-inorder(n5)
-
-print('Preorder')
-def preorder(n):
- if n == None:
- return
- print(n.value)
- preorder(n.left)
- preorder(n.right)
-
-preorder(n5)
-
-print('Postorder')
-def postorder(n):
- if n == None:
- return
- postorder(n.left)
- postorder(n.right)
- print(n.value)
-
-postorder(n5)
diff --git a/languages/python/asyncio_examples/aiohttp_client.py b/languages/python/asyncio_examples/aiohttp_client.py
deleted file mode 100644
index 3d225c80..00000000
--- a/languages/python/asyncio_examples/aiohttp_client.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import asyncio
-
-from contextlib import closing
-
-import time
-
-import aiohttp
-
-
-async def fetch_page(session, host, port=8000, wait=0):
- url = '{}:{}/{}'.format(host, port, wait)
- with aiohttp.Timeout(10):
- async with session.get(url) as response:
- assert response.status == 200
- return await response.text()
-
-
-def get_multiple_pages(host, waits, port=8000, show_time=True):
- tasks = []
- pages = []
- start = time.perf_counter()
-
- with closing(asyncio.get_event_loop()) as loop:
- with aiohttp.ClientSession(loop=loop) as session:
- for wait in waits:
- tasks.append(fetch_page(session, host, port, wait))
- pages = loop.run_until_complete(asyncio.gather(*tasks))
-
- duration = time.perf_counter() - start
- sum_waits = sum(waits)
- if show_time:
- msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
- print((msg.format(duration, sum_waits)))
- return pages
-
-if __name__ == '__main__':
- def main():
- """Test it."""
- pages = get_multiple_pages(host='http://localhost',
- port='8888',
- waits=[1, 5, 3, 2])
- for page in pages:
- print(page)
- main()
diff --git a/languages/python/asyncio_examples/asyncio_twisted_similarity.py b/languages/python/asyncio_examples/asyncio_twisted_similarity.py
deleted file mode 100644
index de96bbdb..00000000
--- a/languages/python/asyncio_examples/asyncio_twisted_similarity.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""
-from twisted.internet import defer
-from twisted.internet import reactor
-
-def multiply(x):
- result = x * 2
- d = defer.Deferred()
- reactor.callLater(1.0, d.callback, result)
- return d
-
-def step1(x):
- return multiply(x)
-
-def step2(result):
- print("result: %s", result)
- reactor.stop()
-
-d = deter.Deferred()
-d.addCallback(step1)
-d.addCallback(step2)
-d.callback(5)
-
-reactor.run()
-"""
-
-import asyncio
-
-async def multiply(x):
- result = x * 2
- await asyncio.sleep(1)
- return result
-
-async def steps(x):
- result = await multiply(x)
- print(("result: %s" % result))
-
-
-loop = asyncio.get_event_loop()
-coro = steps(5)
-loop.run_until_complete(coro)
-loop.close()
diff --git a/languages/python/asyncio_examples/creating_task.py b/languages/python/asyncio_examples/creating_task.py
deleted file mode 100644
index a54ac9fc..00000000
--- a/languages/python/asyncio_examples/creating_task.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import asyncio
-
-async def say(what, when):
- await asyncio.sleep(when)
- print(what)
-
-loop = asyncio.get_event_loop()
-loop.create_task(say('first hello', 2))
-loop.create_task(say('second hello', 1))
-
-loop.run_forever()
-loop.close()
diff --git a/languages/python/asyncio_examples/env.sh b/languages/python/asyncio_examples/env.sh
deleted file mode 100644
index 2c37a102..00000000
--- a/languages/python/asyncio_examples/env.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/usr/bin/env bash
-source /Users/senthil/python3.6/py36venv/bin/activate
diff --git a/languages/python/asyncio_examples/get_onepage_async.py b/languages/python/asyncio_examples/get_onepage_async.py
deleted file mode 100644
index a3ff23e4..00000000
--- a/languages/python/asyncio_examples/get_onepage_async.py
+++ /dev/null
@@ -1,100 +0,0 @@
-"""
-Get a web page asynchronously.
-"""
-
-import asyncio
-import random
-import time
-
-from contextlib import closing
-
-ENCODING = "ISO-8859-1"
-
-
-def get_encoding(header):
- """File out encoding."""
- for line in header:
- if line.lstrip().startswith("Content-type"):
- for entry in line.split(";"):
- if entry.strip().startswith('charset'):
- return entry.split('=')[1].strip()
- return ENCODING
-
-
-async def get_page(host, port, wait=0):
- """Get a web-page asynchronously."""
- reader, writer = await asyncio.open_connection(host, port)
- writer.write(
- b'\r\n'.join([
- 'GET /{} HTTP/1.0'.format(wait).encode(ENCODING),
- b'Host: %b' % host.encode(ENCODING),
- b'Connection: close',
- b'',
- b'']))
- header = []
- msg_lines = []
- async for raw_line in reader:
- line = raw_line.decode(ENCODING).strip()
- if not line.strip():
- break
- header.append(line)
- encoding = get_encoding(header)
- async for raw_line in reader:
- line = raw_line.decode(encoding).strip()
- msg_lines.append(line)
- writer.close()
- return "\n".join(msg_lines)
-
-
-def get_multiple_pages(host, port, waits, show_time=True):
- """Get multiple pages."""
- start = time.perf_counter()
- pages = []
- with closing(asyncio.get_event_loop()) as loop:
- for wait in waits:
- pages.append(loop.run_until_complete(get_page(host, port,wait)))
- duration = time.perf_counter() - start
- sum_waits = sum(waits)
- if show_time:
- msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
- print((msg.format(duration, sum_waits)))
-
- return pages
-
-
-def get_multiple_pages2(host, port, waits, show_time=True):
- """Get multiple pages."""
- start = time.perf_counter()
- pages = []
- tasks = []
-
- with closing(asyncio.get_event_loop()) as loop:
- for wait in waits:
- tasks.append(get_page(host, port, wait))
- pages = loop.run_until_complete(asyncio.gather(*tasks))
-
- duration = time.perf_counter() - start
- sum_waits = sum(waits)
-
- if show_time:
- msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
- print((msg.format(duration, sum_waits)))
-
- return pages
-
-
-if __name__ == '__main__':
-
- def main():
- """Test it!"""
- if random.choice([True, False]):
- pages = get_multiple_pages(host='localhost', port='8888',waits=[1, 5, 3, 2])
- for page in pages:
- print(page)
- else:
- pages = get_multiple_pages2(host='localhost', port='8888',waits=[1, 5, 3, 2])
- for page in pages:
- print(page)
-
- main()
-
diff --git a/languages/python/asyncio_examples/hello_clock.py b/languages/python/asyncio_examples/hello_clock.py
deleted file mode 100644
index 30583289..00000000
--- a/languages/python/asyncio_examples/hello_clock.py
+++ /dev/null
@@ -1,26 +0,0 @@
-"""
-Hello Clock
-
-Example illustrating how to schedule two coroutines to run concurrently.
-They run for ten minutes, during which the first coroutine is scheduled to run every second, while the second is scheduled to run every minute.
-"""
-
-import asyncio
-
-async def print_every_second():
- """"Print seconds."""
- while True:
- for i in range(60):
- print((i, 's'))
- await asyncio.sleep(1)
-
-async def print_every_minute():
- """Print Every minute."""
- for i in range(1, 10):
- await asyncio.sleep(60)
- print((i, "minute"))
-
-loop = asyncio.get_event_loop()
-loop.run_until_complete(
- asyncio.gather(print_every_second(), print_every_minute()))
-loop.close()
diff --git a/languages/python/asyncio_examples/http_client.py b/languages/python/asyncio_examples/http_client.py
deleted file mode 100644
index 761e254d..00000000
--- a/languages/python/asyncio_examples/http_client.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""
-HTTP Client Example
-"""
-
-import asyncio
-import aiohttp
-
-
-async def fetch_page(session, url):
- with aiohttp.Timeout(10):
- async with session.get(url) as response:
- assert response.status == 200
- return await response.read()
-
-loop = asyncio.get_event_loop()
-
-with aiohttp.ClientSession(loop=loop) as session:
- content = loop.run_until_complete(
- fetch_page(session, "http://python.org"))
- print(content)
-
-loop.close()
diff --git a/languages/python/asyncio_examples/producer.py b/languages/python/asyncio_examples/producer.py
deleted file mode 100644
index a7729ca5..00000000
--- a/languages/python/asyncio_examples/producer.py
+++ /dev/null
@@ -1,35 +0,0 @@
-import asyncio
-import random
-
-async def produce(queue, n):
- for x in range(1, n+1):
- # produce an item
- print(('producing {}/{}'.format(x, n)))
- # simulate i/o operation using sleep
- await asyncio.sleep(random.random())
- item = str(x)
- # put the item in the queue
- await queue.put(item)
-
-
-async def consume(queue):
- while True:
- # wait for an item from the producer
- item = await queue.get()
- if item is None:
- # producer emits None to indicate that it is done
- break
-
- # process the item
-
- print(("consuming item {}...".format(item)))
- # simulate the i/o operation using sleep
- await asyncio.sleep(random.random())
-
-loop = asyncio.get_event_loop()
-queue = asyncio.Queue(loop=loop)
-producer_coro = produce(queue, 10)
-consumer_coro = consume(queue)
-
-loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
-loop.close()
diff --git a/languages/python/asyncio_examples/producer_consumer_task_done.py b/languages/python/asyncio_examples/producer_consumer_task_done.py
deleted file mode 100644
index 23f8031a..00000000
--- a/languages/python/asyncio_examples/producer_consumer_task_done.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""
-A simple producer/consumer example using Queue.task_done and Queue.join
-"""
-
-import asyncio
-import random
-
-async def produce(queue, n):
- for x in range(n):
- # produce an item
- print(('producing {}/{}'.format(x, n)))
- # simulate i/o operation using sleep
- await asyncio.sleep(random.random())
- item = str(x)
- # put the item in the queue
- await queue.put(item)
-
-
-async def consume(queue):
- while True:
- # wait for an item from the producer
- item = await queue.get()
-
- # process the item
- print(("consuming {}...".format(item)))
- # simulate i/o operation using sleep
- await asyncio.sleep(random.random())
-
- # notify the queue that the item has been processed.
- queue.task_done()
-
-async def run(n):
- queue = asyncio.Queue()
- # schedule a consumer
- consumer = asyncio.ensure_future(consume(queue))
- # run the producer and wait for completion
- await produce(queue, n)
- # wait until the consumer has processed all items
- await queue.join()
- # the consumer is still awaiting for an item, cancel it
- consumer.cancel()
-
-loop = asyncio.get_event_loop()
-loop.run_until_complete(run(10))
-loop.close()
diff --git a/languages/python/asyncio_examples/run_subprocess.py b/languages/python/asyncio_examples/run_subprocess.py
deleted file mode 100644
index f298ba6d..00000000
--- a/languages/python/asyncio_examples/run_subprocess.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import asyncio
-
-async def run_command(*args):
- # Create a subprocess
- process = await asyncio.create_subprocess_exec(
- *args,
- # stdout must be a pipe to be accessible as process.stdout
- stdout=asyncio.subprocess.PIPE)
- # Wait for the subprocess to finish
- stdout, stderr = await process.communicate()
- # return stdout
- return stdout.decode().strip()
-
-loop = asyncio.get_event_loop()
-
-# Gather uname and date commands
-
-commands = asyncio.gather(
- run_command('uname'),
- run_command('date'))
-
-# Run the commands
-
-uname, date = loop.run_until_complete(commands)
-
-# Print a report
-
-print(('uname: {}, date: {}'.format(uname, date)))
-loop.close()
diff --git a/languages/python/asyncio_examples/simple_coroutine.py b/languages/python/asyncio_examples/simple_coroutine.py
deleted file mode 100644
index 36d52cca..00000000
--- a/languages/python/asyncio_examples/simple_coroutine.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import asyncio
-
-async def say(what, when):
- await asyncio.sleep(when)
- print(what)
-
-
-loop = asyncio.get_event_loop()
-loop.run_until_complete(say("Hello, World", 2))
-loop.close()
diff --git a/languages/python/asyncio_examples/simple_server.py b/languages/python/asyncio_examples/simple_server.py
deleted file mode 100644
index e81fa2bd..00000000
--- a/languages/python/asyncio_examples/simple_server.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""
-Simple HTTP Server with GET that waits for given seconds.
-"""
-
-from http.server import BaseHTTPRequestHandler, HTTPServer
-from socketserver import ThreadingMixIn
-import time
-
-ENCODING = 'utf-8'
-
-
-class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
- """Simple multi-threaded HTTP Server."""
- pass
-
-
-class MyRequestHandler(BaseHTTPRequestHandler):
- """Very simple request handler. Only supports GET."""
-
- def do_GET(self):
- """Respond after seconds given in path.
- """
- try:
- seconds = float(self.path[1:])
- except ValueError:
- seconds = 0.0
-
- if seconds < 0:
- seconds = 0.0
-
- text = "Waited for {:4.2f} seconds.\nThat's all.\n"
- msg = text.format(seconds).encode(ENCODING)
- time.sleep(seconds)
-
- self.send_response(200)
- self.send_header("Content-type", "text/plain; charset=utf-8")
- self.send_header("Content-length", str(len(msg)))
- self.end_headers()
- self.wfile.write(msg)
-
-
-def run(server_class=ThreadingHTTPServer,
- handler_class=MyRequestHandler,
- port=8888):
- """Run the simple server on a given port."""
- server_address = ('', port)
- httpd = server_class(server_address, handler_class)
- print(("Serving from port {}...".format(port)))
- httpd.serve_forever()
-
-
-if __name__ == '__main__':
- run()
diff --git a/languages/python/asyncio_examples/stopping_loop.py b/languages/python/asyncio_examples/stopping_loop.py
deleted file mode 100644
index f2d914c1..00000000
--- a/languages/python/asyncio_examples/stopping_loop.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import asyncio
-
-async def say(what, when):
- await asyncio.sleep(when)
- print(what)
-
-async def stop_after(loop, when):
- await asyncio.sleep(when)
- loop.stop()
-
-loop = asyncio.get_event_loop()
-
-loop.create_task(say("first hello", 2))
-loop.create_task(say("second hello", 1))
-loop.create_task(say("third hello", 4))
-loop.create_task(stop_after(loop, 3))
-
-loop.run_forever()
-loop.close()
diff --git a/languages/python/asyncio_examples/subprocess_communicate.py b/languages/python/asyncio_examples/subprocess_communicate.py
deleted file mode 100644
index 4f401abf..00000000
--- a/languages/python/asyncio_examples/subprocess_communicate.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import asyncio
-
-async def echo(msg):
- # Run an echo subprocess
- process = await asyncio.create_subprocess_exec(
- 'cat',
- # stdin must a pipe to be accessible as a process.stdin
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE)
- # Write a message
-
- print(('Writing {!r}...'.format(msg)))
- process.stdin.write(msg.encode() + b'\n')
-
- # Read reply
-
- data = await process.stdout.readline()
- reply = data.decode().strip()
-
- print(("Received {!r}".format(reply)))
-
- # Stop the subprocess
-
- process.terminate()
- code = await process.wait()
-
- print(("Terminated with code {}".format(code)))
-
-
-loop = asyncio.get_event_loop()
-loop.run_until_complete(echo('hello!'))
-loop.close()
diff --git a/languages/python/asyncio_examples/sync_client.py b/languages/python/asyncio_examples/sync_client.py
deleted file mode 100644
index ea72510b..00000000
--- a/languages/python/asyncio_examples/sync_client.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""
-Synchronous client to retrieve web pages.
-"""
-
-from urllib.request import urlopen
-import time
-
-ENCODING = 'ISO-8859-1'
-
-
-def get_encoding(http_response):
- """Find out encoding."""
- content_type = http_response.getheader("Content-type")
- for entry in content_type.split(";"):
- if entry.strip().startswith('charset'):
- return entry.split('=')[1].strip()
- return ENCODING
-
-
-def get_page(host, port, wait=0):
- """Get one page suppling 'wait' time.
-
- The path will be build with 'host:port/wait'
- """
- full_url = '{}:{}/{}'.format(host, port, wait)
- with urlopen(full_url) as http_response:
- html = http_response.read().decode(get_encoding(http_response))
- return html
-
-
-def get_multiple_pages(host, port, waits, show_time=True):
- """Get multiple pages."""
-
- start = time.perf_counter()
- pages = [get_page(host, port, wait) for wait in waits]
- duration = time.perf_counter() - start
- sum_waits = sum(waits)
-
- if show_time:
- msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
- print((msg.format(duration, sum_waits)))
-
- return pages
-
-if __name__ == '__main__':
-
- def main():
- """Test it."""
- pages = get_multiple_pages(
- host='http://localhost',
- port='8888',
- waits=[1, 5, 3, 2])
- for page in pages:
- print(page)
-
- main()
-
diff --git a/languages/python/asyncio_examples/tcp_echo_client.py b/languages/python/asyncio_examples/tcp_echo_client.py
deleted file mode 100644
index c99f2ef9..00000000
--- a/languages/python/asyncio_examples/tcp_echo_client.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import asyncio
-
-async def tcp_echo_client(message, loop):
- reader, writer = await asyncio.open_connection(
- '127.0.0.1',
- 8888,
- loop=loop)
- print(("Send: %r" % message))
- writer.write(message.encode())
-
- data = await reader.read(100)
- print(("Received: %r" % data.decode()))
-
- print("Close the socket.")
- writer.close()
-
-message = "hello, world!"
-loop = asyncio.get_event_loop()
-loop.run_until_complete(tcp_echo_client(message, loop))
-loop.close()
diff --git a/languages/python/asyncio_examples/tcp_echo_server.py b/languages/python/asyncio_examples/tcp_echo_server.py
deleted file mode 100644
index e0e0f52f..00000000
--- a/languages/python/asyncio_examples/tcp_echo_server.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import asyncio
-
-async def handle_echo(reader, writer):
- data = await reader.read(100)
- message = data.decode()
- addr = writer.get_extra_info('peername')
- print(("Received %r from %r" % (message, addr)))
-
- print(("Send: %r" % message))
- writer.write(data)
- await writer.drain()
-
- print("Close the client socket")
- writer.close()
-
-loop = asyncio.get_event_loop()
-coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
-server = loop.run_until_complete(coro)
-
-# Serve requests until Control+C is pressed
-print(("Serving on {}".format(server.sockets[0].getsockname())))
-
-try:
- loop.run_forever()
-except KeyboardInterrupt:
- pass
-
-# close the server
-server.close()
-loop.run_until_complete(server.wait_closed())
-loop.close()
diff --git a/languages/python/asyncio_examples/threads_example.py b/languages/python/asyncio_examples/threads_example.py
deleted file mode 100644
index 2ee8048d..00000000
--- a/languages/python/asyncio_examples/threads_example.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import asyncio
-
-
-def compute_pi(digits):
- # implementation
- return 3.14
-
-async def main(loop):
- digits = await loop.run_in_executor(None, compute_pi, 20000)
- print(("pi: %s" % digits))
-
-loop = asyncio.get_event_loop()
-loop.run_until_complete(main(loop))
-loop.close()
diff --git a/languages/python/bs.png b/languages/python/bs.png
deleted file mode 100644
index b5645343..00000000
Binary files a/languages/python/bs.png and /dev/null differ
diff --git a/languages/python/coding_made_simple/max_rect_area.py b/languages/python/coding_made_simple/max_rect_area.py
deleted file mode 100644
index 631ab1ec..00000000
--- a/languages/python/coding_made_simple/max_rect_area.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""
-Title: Maximum Rectangular Area in Histogram
-Video link: https://youtu.be/ZmnqCZp9bBs
-
-Java code: https://github.com/mission-peace/interview/blob/master/src/com/interview/stackqueue/MaximumHistogram.java
-
-"""
-
-class MaximumHistogram:
-
- def maxHistogram(self, _input):
- stack = []
- max_area = 0
- area = 0
- i = 0
- while i < len(_input):
- if len(stack) == 0 or stack[-1] <= _input[i]:
- stack.append(i)
- i += 1
- else:
- top = stack.pop(-1)
-
- if len(stack) == 0:
- area = _input[top] * i
- else:
- area = _input[top] * (i - stack[-1] - 1)
-
- max_area = max(area, max_area)
-
- while stack:
- top = stack.pop(-1)
-
- if len(stack) == 0:
- area = _input[top] * i
- else:
- area = _input[top] * (i - stack[-1] - 1)
-
- max_area = max(area, max_area)
-
- return max_area
-
-
-if __name__ == "__main__":
- _input = [2,2,2,6,1,5,4,2,2,2,2]
- mh = MaximumHistogram()
- print((mh.maxHistogram(_input)))
- assert mh.maxHistogram(_input) == 12, "Algorithm did not specify the correct result."
-
-
-
-
-
diff --git a/languages/python/design_args_kwargs.py b/languages/python/design_args_kwargs.py
deleted file mode 100644
index 2b69697e..00000000
--- a/languages/python/design_args_kwargs.py
+++ /dev/null
@@ -1,41 +0,0 @@
-def fun1(arg):
- print(arg)
-
-def fun2(arg,arg2):
- print(arg, arg2)
-
-def fun3(arg, *arg2):
- print(arg, arg2)
-
-def fun4(*arg):
- print(arg)
-
-def fun5(**kw):
- print(kw)
-
-def fun6(*arg, **kw):
- print(arg)
-
-def fun7(a, *arg, **kw):
- print(a)
- print(arg)
- print(kw)
-
-def fun8(*arg, **kw):
- print("***args", arg)
- fun7(*arg, **kw)
-
-def fun9(a, b, *args, **kw):
- fun8(a, b, *args, **kw)
-
-fun1(10)
-fun2(10,20)
-fun3(10,20,30)
-fun3(10)
-fun4(10,20,30,40)
-fun5(a=10,b=20)
-fun6(10,20,40)
-fun7(10, 20, 30, k=40)
-fun7(10, k=10)
-fun8(10, 20, 30, k=40)
-fun9(10, 20, 30, k=40)
diff --git a/languages/python/design_ast_example1.py b/languages/python/design_ast_example1.py
deleted file mode 100644
index b6f84759..00000000
--- a/languages/python/design_ast_example1.py
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/python
-#$Id$
-
-"""
-This program is directly executing it a Abstract Syntax Tree Level.
-This is just doing xy*3.
-"""
-import ast
-
-node = ast.Expression(ast.BinOp(
- ast.Str('xy'),
- ast.Mult(),
- ast.Num(3)))
-
-fixed = ast.fix_missing_locations(node)
-
-codeobj = compile(fixed, '', 'eval')
-print(eval(codeobj))
diff --git a/languages/python/design_atexit_1.py b/languages/python/design_atexit_1.py
deleted file mode 100644
index e12807cc..00000000
--- a/languages/python/design_atexit_1.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import atexit
-
-def foo():
- print("foo")
-
-class SomeClass(object):
-
- def __init__(self):
- self.a = 10
- self.b = 20
- atexit.register(foo)
-
-obj = SomeClass()
-print(obj.a)
-print(obj.b)
diff --git a/languages/python/design_caseinsensitivedict.py b/languages/python/design_caseinsensitivedict.py
deleted file mode 100644
index f2bab0a0..00000000
--- a/languages/python/design_caseinsensitivedict.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/python
-# $Id$
-
-"""
-Case Insenstive Dictionary Lookup. Dictionary keys are case sensitive. However
-you might want some facilities to do a case-insenstive dictiionary lookup at
-times. This provides the facility for the same.
-"""
-
-class CaseInsensitiveDict(dict):
- def __init__(self, *args, **kwargs):
- self._keystore = {}
- d = dict(*args, **kwargs)
- for k in list(d.keys()):
- self._keystore[self._get_lower(k)] = k
- return super(CaseInsensitiveDict,self).__init__(*args,**kwargs)
-
- def __setitem__(self, k, v):
- self._keystore[self._get_lower(k)] = k
- return super(CaseInsensitiveDict, self).__setitem__(k, v)
-
- def __getitem__(self, k):
- return super(CaseInsensitiveDict,
- self).__getitem__(self._keystore[self._get_lower(k)])
- @staticmethod
- def _get_lower(k):
- if isinstance(k,str):
- return k.lower()
- else:
- return k
-
-def test():
- obj = CaseInsensitiveDict([('name','senthil')])
- print(obj)
- obj['Sname']='kumaran'
- obj['spam'] ='eggs'
- obj['SPAM']='ham'
- print(list(obj.items()))
- obj1 = dict(fname='FIRST')
- obj.update(obj1)
- print(obj)
- print(list(obj.keys()))
- print(list(obj.items()))
- print(obj['NAME'])
- print(obj['SNAME'])
-
-if __name__ == '__main__':
- test()
diff --git a/languages/python/design_closure1.py b/languages/python/design_closure1.py
deleted file mode 100644
index 352a8fe4..00000000
--- a/languages/python/design_closure1.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""
-A Simple Example of closure in python
-A closure is function which returns another function. For example, the
-``constant`` function here returns, ``_inner`` function. At the top level you
-passed the value and calling the inner function from within, it is not required
-to send the value.
-"""
-def constant(value):
- def sq(x):
- return x*x
-
- def _inner():
- return sq(value)
- return _inner
-
-x = constant(5)
-print((x()))
diff --git a/languages/python/design_closure_example1.py b/languages/python/design_closure_example1.py
deleted file mode 100644
index 46ea13c4..00000000
--- a/languages/python/design_closure_example1.py
+++ /dev/null
@@ -1,8 +0,0 @@
-class Constant():
- def __init__(self, value):
- self._value = value
-
- def __call__(self):
- return self._value
-y = Constant(5)
-print((y()))
diff --git a/languages/python/design_context_2.py b/languages/python/design_context_2.py
deleted file mode 100644
index e179677f..00000000
--- a/languages/python/design_context_2.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from contextlib import contextmanager
-
-@contextmanager
-def somefun():
- yield "something"
-
-with somefun() as f:
- print(f)
diff --git a/languages/python/design_contextmanager.py b/languages/python/design_contextmanager.py
deleted file mode 100644
index 2658f07a..00000000
--- a/languages/python/design_contextmanager.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""
-This is a simple example of a context manager. The context manager is
-implemented by a decorator provided by the contextlib module.
-
-You will see that tag will yield after the first print statement and as it a
-contextmanager, it is resumed after the __exit__ call, which is called by
-default when the with statement falls out of scope and in that case, the next
-print statement is called.
-
-This outputs:
-
- foo
-
-"""
-
-from contextlib import contextmanager
-
-@contextmanager
-def tag(name):
- print("<%s>" % name)
- yield
- print("%s>" % name)
-
-with tag("h1"):
- print("foo")
diff --git a/languages/python/design_contextmanager_ex.py b/languages/python/design_contextmanager_ex.py
deleted file mode 100644
index 4839ee8a..00000000
--- a/languages/python/design_contextmanager_ex.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from contextlib import contextmanager
-
-@contextmanager
-def opened(filename, mode="r"):
- f = open(filename, mode)
- try:
- yield f
- finally:
- f.close()
-
-with opened("toss_coins.py") as f:
- for line in f:
- print(line.strip())
diff --git a/languages/python/design_decorator3.py b/languages/python/design_decorator3.py
deleted file mode 100644
index 91418489..00000000
--- a/languages/python/design_decorator3.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-
-def my_decorator(fun):
- def wrapper(*args):
- print("Before Invocation")
- fun(*args)
- print("After Invocation")
- return wrapper
-
-@my_decorator
-def hello_world(x):
- print("Hello, World")
- print(x)
-
-hello_world(10)
diff --git a/languages/python/design_ex_iterable27.py b/languages/python/design_ex_iterable27.py
deleted file mode 100644
index 69784440..00000000
--- a/languages/python/design_ex_iterable27.py
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/python
-
-class IterableObject(object):
- """A Simple example of object iteration in Python."""
- def __init__(self):
- self.obj_data = []
-
- def __iter__(self):
- for data_item in self.obj_data:
- yield data_item
-
-
-class Something(IterableObject):
- def __init__(self):
- self.obj_data = ["one", "two", "three", "four", "five"]
-
-
-if __name__ == '__main__':
- something = Something()
- for i in something:
- print (i)
diff --git a/languages/python/design_func_args.py b/languages/python/design_func_args.py
deleted file mode 100644
index 8def964d..00000000
--- a/languages/python/design_func_args.py
+++ /dev/null
@@ -1,25 +0,0 @@
-def fun1(arg):
- print(arg)
-
-def fun2(arg,arg2):
- print(arg, arg2)
-
-def fun3(arg, *arg2):
- print(arg, arg2)
-
-def fun4(*arg):
- print(arg)
-
-def fun5(**kw):
- print(kw)
-
-def fun6(*arg, **kw):
- print(arg)
-
-
-fun1(10)
-fun2(10,20)
-fun3(10,20,30)
-fun4(10,20,30,40)
-fun5(a=10,b=20)
-fun6(10,20,40)
diff --git a/languages/python/design_generator.py b/languages/python/design_generator.py
deleted file mode 100644
index cbf21eb7..00000000
--- a/languages/python/design_generator.py
+++ /dev/null
@@ -1,12 +0,0 @@
-def mygen():
- """Yield 5 until something else is passed back via send()"""
- a = 5
- while True:
- f = yield(a) #yield a and possibly get f in return
- if f is not None: a = f #store the new value
-
-g = mygen()
-print(next(g))
-print(next(g))
-g.send(7)
-print(next(g))
diff --git a/languages/python/design_getattribute_example1.py b/languages/python/design_getattribute_example1.py
deleted file mode 100644
index 0af49f49..00000000
--- a/languages/python/design_getattribute_example1.py
+++ /dev/null
@@ -1,22 +0,0 @@
-
-# Override access to one variable in a class, but return all others normally
-
-class D(object):
- def __init__(self):
- self.test = 20
- self.test2 = 40
- def __getattribute__(self, name):
- if name == 'test':
- return 0
- else:
- return self.__dict__[name]
-
-# The above wont work.
-# This will give
-# RuntimeError: maximum recursion depth exceeded in cmp
-# Look at getattribute_example2.py for correct solution.
-
-obj1 = D()
-print(obj1.test)
-print(obj1.test2)
-
diff --git a/languages/python/design_getattribute_example2.py b/languages/python/design_getattribute_example2.py
deleted file mode 100644
index 08a93d0f..00000000
--- a/languages/python/design_getattribute_example2.py
+++ /dev/null
@@ -1,17 +0,0 @@
-
-# Override access to one variable in a class, but return all others normally
-# http://stackoverflow.com/a/371833/18852
-
-class D(object):
- def __init__(self):
- self.test = 20
- self.test2 = 40
- def __getattribute__(self, name):
- if name == 'test':
- return 0
- else:
- return object.__getattribute__(self, name)
-
-obj1 = D()
-print(obj1.test)
-print(obj1.test2)
diff --git a/languages/python/design_hextobin.py b/languages/python/design_hextobin.py
deleted file mode 100644
index be187ca0..00000000
--- a/languages/python/design_hextobin.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from functools import partial
-
-hexbin = partial(int, base=16)
-print((bin(hexbin("FFFF"))))
\ No newline at end of file
diff --git a/languages/python/design_inheritance.py b/languages/python/design_inheritance.py
deleted file mode 100644
index b97db7ae..00000000
--- a/languages/python/design_inheritance.py
+++ /dev/null
@@ -1,13 +0,0 @@
-class A(object):
- def __init__(self):
- print("A is called.")
-
-class B(object):
- def __init__(self):
- print("B is called.")
-
-class C(A, B):
- def __init__(self):
- super(C, self).__init__()
-
-c = C()
diff --git a/languages/python/design_iterator_ex2.py b/languages/python/design_iterator_ex2.py
deleted file mode 100644
index 85a1e188..00000000
--- a/languages/python/design_iterator_ex2.py
+++ /dev/null
@@ -1,12 +0,0 @@
-dict1 = {'a':1,'b':2,'c':3}
-
-sequence= dict1
-
-it = iter(sequence)
-while True:
- try:
- value = next(it)
- except StopIteration:
- break
- print(value)
-
diff --git a/languages/python/design_object_size.py b/languages/python/design_object_size.py
deleted file mode 100644
index 380f5a4a..00000000
--- a/languages/python/design_object_size.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import pickle
-import sys
-
-obj = list(range(10000))
-
-def GetMemoryUsage(ob):
- s = pickle.dumps(ob)
- memUsed = sys.getpymemalloced()
- ob2 = pickle.loads(s)
- return sys.getpymemalloced() - memUsed
-
-print(GetMemoryUsage(obj))
diff --git a/languages/python/design_python3_meta_ex1.py b/languages/python/design_python3_meta_ex1.py
deleted file mode 100644
index 4b247ed8..00000000
--- a/languages/python/design_python3_meta_ex1.py
+++ /dev/null
@@ -1,18 +0,0 @@
-class mymeta(type):
- def __new__(cls, name, bases, dict):
- print(("Creating name:", name))
- print(("Base Classes:", bases))
- print(("Class Body:", dict))
- # create the actual class object
- return type.__new__(cls, name, bases, dict)
-
-class Rectangle(object, metaclass=mymeta):
- def __init__(self, width, height):
- self.width = width
- self.height = height
-
- def area(self):
- return self.width * self.height
-
- def perimeter(self):
- return 2*self.width + 2* self.height
diff --git a/languages/python/design_python_objects_type.py b/languages/python/design_python_objects_type.py
deleted file mode 100644
index 54c14742..00000000
--- a/languages/python/design_python_objects_type.py
+++ /dev/null
@@ -1,38 +0,0 @@
-print('issubclass(type,object) ', issubclass(type,object))
-print('issubclass(object,type) ', issubclass(object,type))
-print('isinstance(type,object) ', isinstance(type,object))
-print('isinstance(object,type) ', isinstance(object,type))
-print('-------------------------')
-try:
- print(issubclass(True,object))
-except TypeError:
- print('issubclass(True,object) does not make sense. Object is not class.')
-try:
- print(issubclass(1,object))
-except TypeError:
- print('issubclass(1,object) does not make sense. Object is not class')
-try:
- print(issubclass('c',object))
-except TypeError:
- print("issubclass('c',object) does not make sense. Object is not class")
-print('-------------------------')
-try:
- print(issubclass(True,type))
-except TypeError:
- print('issubclass(True,type) does not make sense. type is not class.')
-try:
- print(issubclass(1,type))
-except TypeError:
- print('issubclass(1,type) does not make sense. type is not class')
-try:
- print(issubclass('c',type))
-except TypeError:
- print("issubclass('c',type) does not make sense. type is not class")
-print('-------------------------')
-print('isinstance(True,object) ', isinstance(True,object))
-print('isinstance(1,object) ', isinstance(True,object))
-print('isinstance("c",object) ', isinstance(True,object))
-print('-------------------------')
-print('isinstance(True,type) ', isinstance(True,type))
-print('isinstance(1,type) ', isinstance(True,type))
-print('isinstance("c",type) ', isinstance(True,type))
diff --git a/languages/python/design_restricter_class.py b/languages/python/design_restricter_class.py
deleted file mode 100644
index 9a228206..00000000
--- a/languages/python/design_restricter_class.py
+++ /dev/null
@@ -1,20 +0,0 @@
-class RestrictingWrapper(object):
- def __init__(self, obj, to_block):
- self._obj = obj
- self._to_block = to_block
-
- def __getattr__(self, name):
- if name in self._to_block:
- raise AttributeError(name)
- return getattr(self._obj, name)
-
-class Foo(object):
- def __init__(self, x, y, z):
- self.x, self.y, self.z = x, y, z
-
-f1 = Foo(1, 2, 3)
-print(f1.x, f1.y, f1.z)
-
-f2 = RestrictingWrapper(f1, "z")
-print(f2.x, f2.y)
-print(f2.z)
diff --git a/languages/python/design_simple_closure.py b/languages/python/design_simple_closure.py
deleted file mode 100644
index a9ab690d..00000000
--- a/languages/python/design_simple_closure.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""
-A Simple Example of closure in python
-A closure is function which returns another function. For example, the
-``constant`` function here returns, ``_inner`` function. At the top level you
-passed the value and calling the inner function from within, it is not required
-to send the value.
-"""
-def constant(value):
- def _inner():
- return value
- return _inner
-x = constant(5)
-print((x()))
diff --git a/languages/python/design_slice_ellipses.py b/languages/python/design_slice_ellipses.py
deleted file mode 100644
index b0651933..00000000
--- a/languages/python/design_slice_ellipses.py
+++ /dev/null
@@ -1,5 +0,0 @@
-class C(object):
- def __getitem__(self, item):
- return item
-
-print(C()[1:2, ..., 3])
diff --git a/languages/python/design_sorted_loop.py b/languages/python/design_sorted_loop.py
deleted file mode 100644
index 812e1e20..00000000
--- a/languages/python/design_sorted_loop.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import random
-import time
-start = time.time()
-r = random.sample(list(range(10)), 5)
-for x in range(1000):
- for i in sorted(r):
- pass
-print(time.time() - start)
diff --git a/languages/python/design_stackinspection.py b/languages/python/design_stackinspection.py
deleted file mode 100644
index b2587083..00000000
--- a/languages/python/design_stackinspection.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import sys
-def foo():
- """blah"""
- print(sys._getframe().f_back.f_locals[sys._getframe().f_code.co_name].__doc__)
-
-foo()
diff --git a/languages/python/design_struct_example.py b/languages/python/design_struct_example.py
deleted file mode 100644
index 0b4ba565..00000000
--- a/languages/python/design_struct_example.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/python
-"""
-$Id$
-
-Purpose:
- Demonstrate the way the struct module works.
-
-Description:
- One can access substrings of a string in a arbitrary manner while using the
- struct module. This is mostly useful when dealing with byte level
- programming required in embedded systems or while using sockets.
-
-Source:
- Python cookbook perhaps.
-"""
-import struct
-theline = "The quick brown fox jumped over the lazy dog."
-# Get a 5-byte string, skip 3, get two 8-byte string, then all the rest:
-baseformat = '5s 3x 8s 8s'
-# by how many bytes does theline exceed the length implied by this
-# base-format ( 24 bytes in this, but struct.calcsize is general)
-numremain = len(theline) - struct.calcsize(baseformat)
-# complete the format with the appropriate 's' field, then unpack
-format = '%s %ds' % (baseformat, numremain)
-l, s1, s2, t = struct.unpack(format, theline)
-print(l)
-print(s1)
-print(s2)
-print(t)
diff --git a/languages/python/design_total_ordering.py b/languages/python/design_total_ordering.py
deleted file mode 100644
index 8d7489e3..00000000
--- a/languages/python/design_total_ordering.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from functools import total_ordering
-
-"""
-
-http://en.wikipedia.org/wiki/Total_order
-
-For pair of items from a set, (that's the total)
-if a <= b and b <= c then a <= c (part of the order)
-if a <= b and b <= a then a compares the same as b, a == b, (the
-other part of the order)
-
-"""
-
-@total_ordering
-class Student:
- def __init__(self, lastname, firstname):
- self.firstname = firstname
- self.lastname = lastname
- def __eq__(self, other):
- return ((self.lastname.lower(), self.firstname.lower()) ==
- (other.lastname.lower(), other.firstname.lower()))
- def __lt__(self, other):
- return ((self.lastname.lower(), self.firstname.lower()) <
- (other.lastname.lower(), other.firstname.lower()))
-
-
-student1 = Student("Bond","James")
-student2 = Student("Haddock","Captain")
-
-# Where are these coming from?
-print((student2 > student1)) # True
-print((student2 >= student2)) # True
-print((student2 != student1)) # True
diff --git a/languages/python/design_traceit.py b/languages/python/design_traceit.py
deleted file mode 100644
index 0de7e26f..00000000
--- a/languages/python/design_traceit.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import sys
-import linecache
-import random
-
-def traceit(frame, event, arg):
- if event == "line":
- lineno = frame.f_lineno
- filename = frame.f_globals["__file__"]
- if (filename.endswith(".pyc") or
- filename.endswith(".pyo")):
- filename = filename[:-1]
- name = frame.f_globals["__name__"]
- line = linecache.getline(filename, lineno)
- print("%s:%s: %s" % (name, lineno, line.rstrip()))
- return traceit
diff --git a/languages/python/fbcup1.py b/languages/python/fbcup1.py
deleted file mode 100644
index 9fbc417a..00000000
--- a/languages/python/fbcup1.py
+++ /dev/null
@@ -1,34 +0,0 @@
-import string
-from collections import Counter
-from collections import defaultdict
-
-words = set(string.ascii_uppercase)
-vowels = set(['A','E','I','O','U'])
-consonants = words - vowels
-
-
-T = int(input())
-for tc in range(T):
- reverse_dict = defaultdict(list)
- num_vowels = 0
- num_consonants = 0
- tcn = tc + 1
- word = input()
- chars = set(word)
- if len(chars) == 1:
- print(f"Case #{tcn}:", 0)
- continue
- for c in chars:
- if c in vowels:
- num_vowels += 1
- else:
- num_consonants += 1
- print(f"consonants: {num_consonants}, vowels: {num_vowels}")
- word_counter = Counter(word)
- for w, c in word_counter.items():
- reverse_dict[c].append(w)
- sorted_keys = sorted(reverse_dict.keys(), reverse=True)
- # pick the one that you are not changing.
- print(reverse_dict)
- print(sorted_keys)
-
diff --git a/languages/python/files_count_lines_large_file.py b/languages/python/files_count_lines_large_file.py
deleted file mode 100644
index acb44336..00000000
--- a/languages/python/files_count_lines_large_file.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# files_count_lines_large_file.py - 30-08-2015 08:13
-
-CHUNK_SIZE = 8192 * 1024
-
-def count_lines(file_path):
- count = 0
- with open(file_path, 'rb') as fh:
- while True:
- buffer = fh.read(CHUNK_SIZE)
- if not buffer:
- break
- count += buffer.count('\n')
- return count
-
-def main():
- print((count_lines('./files_count_lines_large_file.py')))
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/files_processing_every_word.py b/languages/python/files_processing_every_word.py
deleted file mode 100644
index 335bad9e..00000000
--- a/languages/python/files_processing_every_word.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import re
-
-WORD_REGEX = re.compile(r"[\w'-]+")
-
-def do_something_with_word(word):
- print(word)
-
-def words_in_file(file_name):
- with open(file_name) as fh:
- for line in fh:
- for word in WORD_REGEX.finditer(line):
- do_something_with_word(word.group(0))
-
-def main():
- words_in_file('./files_processing_every_word.py')
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
diff --git a/languages/python/files_random_access_input_output.py b/languages/python/files_random_access_input_output.py
deleted file mode 100644
index 240d65ce..00000000
--- a/languages/python/files_random_access_input_output.py
+++ /dev/null
@@ -1,16 +0,0 @@
-def seek_and_read(file_name, buf_size, byte_number):
- with open(file_name) as f:
- f.seek(byte_number)
- buf = f.read(buf_size)
- return buf
-
-def main():
- buf_size = 48
- byte_number = 6
- print(seek_and_read(
- './files_random_access_input_output.py',
- buf_size,
- byte_number))
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/files_read_specific_line.py b/languages/python/files_read_specific_line.py
deleted file mode 100644
index 978a5004..00000000
--- a/languages/python/files_read_specific_line.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import linecache
-
-
-def get_line_from_a_file(file_path, line_number):
- return linecache.getline(file_path, line_number)
-
-
-def main():
- file_path = './files_read_specific_line.py'
- desired_line_number = 10
- print(get_line_from_a_file(file_path, desired_line_number))
-
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/files_reading_zipfile.py b/languages/python/files_reading_zipfile.py
deleted file mode 100644
index 0dc68c70..00000000
--- a/languages/python/files_reading_zipfile.py
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-import zipfile
-
-def read_zip(filename):
- with zipfile.ZipFile(filename, 'r') as z:
- for zip_filename in z.namelist():
- print("File: {0}".format(zip_filename))
- _bytes = z.read(zip_filename)
- print("has {0} bytes".format(len(_bytes)))
-
-def main():
- filename = 'sample.zip'
- read_zip(filename)
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/font.ttf b/languages/python/font.ttf
deleted file mode 100644
index 9c691234..00000000
Binary files a/languages/python/font.ttf and /dev/null differ
diff --git a/languages/python/index.txt b/languages/python/index.txt
deleted file mode 100644
index 786b684f..00000000
--- a/languages/python/index.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-restindex
- crumb: python-programs
- format: rest
- encoding: utf-8
- output-encoding: None
-/restindex
-
-Python programs
----------------
diff --git a/languages/python/input.txt b/languages/python/input.txt
deleted file mode 100644
index 8298ec00..00000000
--- a/languages/python/input.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-In a language familiar to you, if you keep the first and the last character of
-each word in the sentence, your can easily read the sentence.
-
-This is one of my earliest program that seems to have survived and still gives joy!
diff --git a/languages/python/input.txt~ b/languages/python/input.txt~
deleted file mode 100644
index 470a874b..00000000
--- a/languages/python/input.txt~
+++ /dev/null
@@ -1 +0,0 @@
-This is one of my earliest program that seems to have survived and still gives joy!
diff --git a/languages/python/min_cost_path.py b/languages/python/min_cost_path.py
deleted file mode 100644
index 6bdd4a2a..00000000
--- a/languages/python/min_cost_path.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# min_cost_path.py - 26-04-2020 09:11
-
-from typing import List
-
-# Video: https://www.youtube.com/watch?v=lBRtnuxg-gU
-
-
-class Solution:
-
- def minPathSum(self, grid: List[List[int]]) -> int:
- m = len(grid)
- n = len(grid[0])
- T = [[0] * n for _ in range(m)]
- # First left top corner cost is same.
- T[0][0] = grid[0][0]
-
- # First row in T
- for first_row_idx in range(1, n):
- T[0][first_row_idx] = T[0][first_row_idx-1] + grid[0][first_row_idx]
-
- # First col in T
- for first_col_idx in range(1, m):
- T[first_col_idx][0] = T[first_col_idx-1][0] + grid[first_col_idx][0]
-
- # Fill in the rest of the 2D matrix for T.
- for i in range(1, m):
- for j in range(1, n):
- T[i][j] = grid[i][j] + min(T[i-1][j], # top
- T[i][j-1]) # left
-
- # value to reach the right most end
- return T[-1][-1]
-
-
-if __name__ == '__main__':
- s = Solution()
- mat = [
- [1, 3, 1],
- [1, 5, 1],
- [4, 2, 1]
- ]
- print((s.minPathSum(mat)))
diff --git a/languages/python/networking_allifaces.py b/languages/python/networking_allifaces.py
deleted file mode 100644
index f05bfb7d..00000000
--- a/languages/python/networking_allifaces.py
+++ /dev/null
@@ -1,45 +0,0 @@
-#:w/usr/bin/python
-# $Id$
-"""
-List Network Interfaces
-
-**Purpose**: This program provides list of network interfaces available on
-your machine.
-
-**Description**: man netdevice provides the following information about
-SIOCGIFCONF which is used to retrieve the interfaces information.
-
-SIOCGIFCONF
-
-Return a list of interface (transport layer) addresses. This currently means
-only addresses of the AF_INET (IPv4) family for compatibility. The user passes
-a ifconf structure as argument to the ioctl. It contains a pointer to an array
-of ifreq structures in ifc_req and its length in bytes in ifc_len. The kernel
-fills the ifreqs with all current L3 interface addresses that are running:
-ifr_name contains the interface name (eth0:1 etc.), ifr_addr the address. The
-kernel returns with the actual length in ifc_len. If ifc_len is equal to the
-original length the buffer probably has overflowed and you should retry with a
-bigger buffer to get all addresses. When no error occurs the ioctl returns 0;
-otherwise -1. Overflow is not an error.
-
-"""
-
-import socket
-import fcntl
-import struct
-import array
-
-def all_interfaces():
- max_possible = 128 # arbitrary. raise if needed.
- bytes = max_possible * 32
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- names = array.array('B', '\0' * bytes)
- outbytes = struct.unpack('iL', fcntl.ioctl(
- s.fileno(),
- 0x8912, # SIOCGIFCONF
- struct.pack('iL', bytes, names.buffer_info()[0])
- ))[0]
- namestr = names.tostring()
- return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
-
-print(all_interfaces())
diff --git a/languages/python/networking_allipaddress.py b/languages/python/networking_allipaddress.py
deleted file mode 100644
index 32726d66..00000000
--- a/languages/python/networking_allipaddress.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python
-# $Id$
-
-"""
-**Purpose**: The program gets all the ipaddress assigned to all the interfaces
-in your machine.
-
-**Description**: Get all the interfaces using SIOCGIFCONF ioctl call and then
-use SIOCGIFADDR to get its address.
-
-man networking says that SIOCGIFADDR Get interface address for
-protocol family.
-
-"""
-
-import socket
-import fcntl
-import struct
-import array
-
-def all_interfaces():
- max_possible = 128 # arbitrary. raise if needed.
- bytes = max_possible * 32
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- names = array.array('B', '\0' * bytes)
- outbytes = struct.unpack('iL', fcntl.ioctl(
- s.fileno(),
- 0x8912, # SIOCGIFCONF
- struct.pack('iL', bytes, names.buffer_info()[0])
- ))[0]
- namestr = names.tostring()
- return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
-
-def get_ip_address(ifname):
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- return socket.inet_ntoa(fcntl.ioctl(
- s.fileno(),
- 0x8915, # SIOCGIFADDR
- struct.pack('256s', ifname[:15])
- )[20:24])
-
-for each in all_interfaces():
- if each:
- print(get_ip_address(each))
diff --git a/languages/python/networking_bug_gethostbyname.py b/languages/python/networking_bug_gethostbyname.py
deleted file mode 100644
index 736b708b..00000000
--- a/languages/python/networking_bug_gethostbyname.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/python
-#$Id$
-"""
-Generate a random domain name and see if it actually exists by doing a
-gethostbyname call.
-"""
-
-from socket import *
-import sys
-
-def test(name):
- print("enter test, gethostbyname(%r)" % name)
- print("You can press CTRL-C")
- try:
- try:
- gethostbyname(name)
- except:
- print("inner try")
- E = sys.exc_info()[0]
- print(type(E), repr(E), E is KeyboardInterrupt)
- raise
- except:
- print("outer try")
- E = sys.exc_info()[0]
- print(type(E), repr(E), E is KeyboardInterrupt)
- print("exit test")
-
-import random
-letters = list("typingsomeuselessword")
-random.shuffle(letters)
-name = ".".join(letters[:5]) + ".com"
-test(name)
diff --git a/languages/python/networking_email1.py b/languages/python/networking_email1.py
deleted file mode 100755
index 4a261b28..00000000
--- a/languages/python/networking_email1.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Import smtplib for the actual sending function
-import smtplib
-
-# Import the email modules we'll need
-from email.mime.text import MIMEText
-
-# Open a plain text file for reading. For this example, assume that
-# the text file contains only ASCII characters.
-fp = open('content.txt', 'rb')
-# Create a text/plain message
-msg = MIMEText(fp.read())
-fp.close()
-
-me = 'orsenthil@gmail.com'
-you = 'senthil@uthcode.com'
-msg['Subject'] = 'Hello'
-msg['From'] = me
-msg['To'] = you
-
-# Send the message via our own SMTP server, but don't include the
-# envelope header.
-s = smtplib.SMTP('smtp.gmail.com')
-s.sendmail(me, [you], msg.as_string())
-s.quit()
diff --git a/languages/python/networking_email2.py b/languages/python/networking_email2.py
deleted file mode 100644
index a0fd8d4c..00000000
--- a/languages/python/networking_email2.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import smtplib
-import getpass
-
-fromaddr = 'orsenthil@gmail.com'
-toaddrs = 'senthil@uthcode.com'
-msg = 'There was a terrible error that occured and I wanted you to know!'
-
-# Credentials (if needed)
-username = 'orsenthil'
-password = getpass.getpass()
-
-# The actual mail send
-server = smtplib.SMTP('smtp.gmail.com:587')
-server.starttls()
-server.login(username,password)
-server.sendmail(fromaddr, toaddrs, msg)
-server.quit()
diff --git a/languages/python/networking_email3.py b/languages/python/networking_email3.py
deleted file mode 100644
index 67b96684..00000000
--- a/languages/python/networking_email3.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import smtplib
-
-from email.MIMEMultipart import MIMEMultipart
-from email.MIMEBase import MIMEBase
-from email.MIMEText import MIMEText
-from email import Encoders
-import os
-
-me = 'Name '
-
-username = ''
-password = 'password'
-textfile = 'message.txt'
-attachment = 'picture.png'
-
-
-def send_email(name, to_email):
- you = to_email
- msg = MIMEMultipart()
-
- msg['From'] = me
- msg['To'] = you
- msg['Subject'] = 'Subject'
-
- fp = open(textfile, 'rb')
- contents = fp.read()
- contents = contents.format(friend=name)
- msg.attach(MIMEText(contents))
- fp.close()
-
- email_attachment = MIMEBase('application', 'octet-stream')
- email_attachment.set_payload(open(attachment, 'rb').read())
- Encoders.encode_base64(email_attachment)
- email_attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment))
-
- msg.attach(email_attachment)
-
- server = smtplib.SMTP('smtp.gmail.com:587')
- server.ehlo()
- server.starttls()
- server.ehlo()
- server.login(username, password)
- server.sendmail(me, [you], msg.as_string())
- server.close()
-
-
-if __name__ == '__main__':
- name = "recipient name"
- email = "recipient email"
- send_email(name, email)
diff --git a/languages/python/networking_email4.py b/languages/python/networking_email4.py
deleted file mode 100644
index 90a0457e..00000000
--- a/languages/python/networking_email4.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""
-Python3 script to send email via gmail.
-
-Pre-requisite: https://www.google.com/settings/security/lesssecureapps
-"""
-import os
-import smtplib
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-
-_DEFAULT_FROM_ADDRESS = ""
-_DEFAULT_FROM_PASSWORD = ""
-_DEFAULT_TO_ADDRESS = ""
-
-
-FROM_ADDRESS = os.environ.get("FROM_ADDRESS", _DEFAULT_FROM_ADDRESS)
-FROM_PASSWORD = os.environ.get("FROM_PASSWORD", _DEFAULT_FROM_PASSWORD)
-TO_ADDRESS = os.environ.get("TO_ADDRESS", _DEFAULT_TO_ADDRESS)
-MAIL_SERVER = "smtp.gmail.com"
-MAIL_PORT = 587
-
-
-def create_message(subject="", body="") -> MIMEMultipart:
- msg = MIMEMultipart()
- msg["From"] = FROM_ADDRESS
- msg["To"] = TO_ADDRESS
- msg["Subject"] = subject
- msg.attach(MIMEText(body, 'plain'))
- return msg
-
-
-def send_mail(msg: MIMEMultipart):
- server = smtplib.SMTP(MAIL_SERVER, MAIL_PORT)
- server.ehlo()
- server.starttls()
- server.login(FROM_ADDRESS, FROM_PASSWORD)
- text = msg.as_string()
- server.sendmail(FROM_ADDRESS, [TO_ADDRESS], text)
- server.quit()
-
-
-SUBJECT = "Game"
-
-MESSAGE = """
-Hello There!
-
-Let's play a game.
-
-Cheers!
-"""
-
-if __name__ == '__main__':
- subject = SUBJECT
- body = MESSAGE
- msg = create_message(subject, body)
- send_mail(msg)
diff --git a/languages/python/networking_fetchrfc.py b/languages/python/networking_fetchrfc.py
deleted file mode 100644
index 1fdd1bba..00000000
--- a/languages/python/networking_fetchrfc.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/python
-import sys
-import optparse
-import urllib.request, urllib.parse, urllib.error
-
-RFC_BASE = 'http://www.ietf.org/rfc/rfc'
-
-parser = optparse.OptionParser()
-parser.add_option('-r','--rfc',
- dest='rfc_name',
- )
-options, remainder = parser.parse_args()
-
-RFC_NAME = options.rfc_name + '.txt'
-
-RFC = RFC_BASE + RFC_NAME
-
-urllib.request.urlretrieve(RFC,filename=RFC_NAME)
-print('Here you have:', RFC_NAME)
diff --git a/languages/python/networking_socket_client.py b/languages/python/networking_socket_client.py
deleted file mode 100644
index be035c83..00000000
--- a/languages/python/networking_socket_client.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""
-This is a simple socket client. It connects to a host and port and creates a
-fileobject using makefile and prints the content of it.
-I don't remember when or why I wrote this.
-"""
-
-import socket
-import sys
-
-def main():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- host = sys.argv[1]
- port = int(sys.argv[2])
- s.connect((host, port))
- flo = s.makefile('r',0)
- for l in flo:
- print(l)
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/networking_socket_example1.py b/languages/python/networking_socket_example1.py
deleted file mode 100644
index 2f2bdcca..00000000
--- a/languages/python/networking_socket_example1.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import socket
-from urllib.parse import urlparse
-
-for url in [ 'http://www.python.org',
- 'https://www.mybank.com',
- 'ftp://prep.ai.mit.edu',
- 'gopher://gopher.micro.umn.edu',
- 'smtp://mail.example.com',
- 'imap://mail.example.com',
- 'imaps://mail.example.com',
- 'pop3://pop.example.com',
- 'pop3s://pop.example.com',
- ]:
- parsed_url = urlparse(url)
- port = socket.getservbyname(parsed_url.scheme)
- print('%6s : %s' % (parsed_url.scheme, port))
diff --git a/languages/python/networking_socket_example2.py b/languages/python/networking_socket_example2.py
deleted file mode 100644
index 0edd3029..00000000
--- a/languages/python/networking_socket_example2.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import socket
-
-def get_constants(prefix):
- """Create a dictionary mapping socket module constants to their names."""
- return dict( (getattr(socket, n), n)
- for n in dir(socket)
- if n.startswith(prefix)
- )
-
-protocols = get_constants('IPPROTO_')
-
-for name in [ 'icmp', 'udp', 'tcp' ]:
- proto_num = socket.getprotobyname(name)
- print(proto_num)
- const_name = protocols[proto_num]
- print('%4s -> %2d (socket.%-12s = %2d)' % \
- (name, proto_num, const_name, getattr(socket, const_name)))
diff --git a/languages/python/networking_socket_example3.py b/languages/python/networking_socket_example3.py
deleted file mode 100644
index ec48e08a..00000000
--- a/languages/python/networking_socket_example3.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import socket
-
-def get_constants(prefix):
- """Create a dictionary mapping socket module constants to their names."""
- return dict( (getattr(socket, n), n)
- for n in dir(socket)
- if n.startswith(prefix)
- )
-
-families = get_constants('AF_')
-print(families)
-types = get_constants('SOCK_')
-print(types)
-protocols = get_constants('IPPROTO_')
-print(protocols)
-
-for response in socket.getaddrinfo('endhiroid.blogspot.com', 'http',
- socket.AF_INET, # family
- socket.SOCK_STREAM, # socktype
- socket.IPPROTO_TCP, # protocol
- socket.AI_CANONNAME, # flags
- ):
- # Unpack the response tuple
- family, socktype, proto, canonname, sockaddr = response
-
- print('Family :', families[family])
- print('Type :', types[socktype])
- print('Protocol :', protocols[proto])
- print('Canonical name:', canonname)
- print('Socket address:', sockaddr)
- print()
diff --git a/languages/python/networking_socket_example4.py b/languages/python/networking_socket_example4.py
deleted file mode 100644
index 6d801f4b..00000000
--- a/languages/python/networking_socket_example4.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import socket
-import os
-
-parent, child = socket.socketpair()
-
-pid = os.fork()
-
-if pid:
- print('in parent, sending message')
- child.close()
- parent.sendall('ping')
- response = parent.recv(1024)
- print('response from child:', response)
- parent.close()
-
-else:
- print('in child, waiting for message')
- parent.close()
- message = child.recv(1024)
- print('message from parent:', message)
- child.sendall('pong')
- child.close()
diff --git a/languages/python/networking_twisted1.py b/languages/python/networking_twisted1.py
deleted file mode 100644
index 59f150cd..00000000
--- a/languages/python/networking_twisted1.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from twisted.internet import task
-from twisted.internet import reactor
-
-def runEverySecond():
- print("a second has passed")
-
-l = task.LoopingCall(runEverySecond)
-l.start(1.0) # call every second
-
-# l.stop() will stop the looping calls
-reactor.run()
diff --git a/languages/python/networking_twisted2.py b/languages/python/networking_twisted2.py
deleted file mode 100644
index bdb13277..00000000
--- a/languages/python/networking_twisted2.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-How is the out value passed to the function1?
-
-utils.getProcessOutput function is returning a deffered object.
-You attach a callback function to the deferred object.
-When the defered is ready with the result, the callback function is called with
-it. That is what is happening here.
-
-"""
-
-from twisted.internet import utils, reactor
-
-def function1(out):
- print(out)
- reactor.stop()
-output = utils.getProcessOutput('ls')
-output.addCallback(function1)
-reactor.run()
diff --git a/languages/python/networking_twisted3.py b/languages/python/networking_twisted3.py
deleted file mode 100644
index c9586409..00000000
--- a/languages/python/networking_twisted3.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# -*- coding: utf8 -*-
-import io as StringIO
-
-from twisted.internet import reactor
-from twisted.web.client import getPage
-from twisted.python.util import println
-from lxml import etree
-
-def parseHtml(html):
- parser = etree.HTMLParser(encoding='utf8')
- tree = etree.parse(StringIO.StringIO(html), parser)
- return tree
-
-def extractTitle(tree):
- return tree
- #titleText = unicode(tree.xpath("//title/text()")[0])
- #return titleText
-
-d = getPage('http://www.uthcode.com')
-d.addCallback(parseHtml)
-d.addCallback(extractTitle)
-d.addBoth(println)
-
-reactor.run()
diff --git a/languages/python/networking_twisted4.py b/languages/python/networking_twisted4.py
deleted file mode 100644
index ecd28813..00000000
--- a/languages/python/networking_twisted4.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import traceback
-
-def stack():
- print('The python stack:')
- traceback.print_stack()
-
-from twisted.internet import reactor
-reactor.callWhenRunning(stack)
-reactor.run()
diff --git a/languages/python/networking_twisted5.py b/languages/python/networking_twisted5.py
deleted file mode 100644
index eae51d66..00000000
--- a/languages/python/networking_twisted5.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# Example code which illustrates twisted's outline
-
-from twisted.internet.protocol import Factory, Protocol
-from twisted.internet import reactor
-
-class QOTD(Protocol):
-
- def connectionMade(self):
- self.transport.write(self.factory.quote+'\r\n')
- self.transport.loseConnection()
-
-
-class QOTDFactory(Factory):
-
- protocol = QOTD
-
- def __init__(self, quote=None):
- self.quote = quote or 'An apple a day keeps the doctor away'
-
-reactor.listenTCP(8007, QOTDFactory("configurable quote"))
-reactor.run()
diff --git a/languages/python/networking_twisted_parallel1.py b/languages/python/networking_twisted_parallel1.py
deleted file mode 100644
index 9f030474..00000000
--- a/languages/python/networking_twisted_parallel1.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from twisted.internet import defer, task
-from twisted.python import log
-from twisted.internet import reactor
-from twisted.web import client
-from twisted.internet.utils import getProcessValue
-
-def parallel(iterable, count, callable, *args, **named):
- print(args, named)
- coop = task.Cooperator()
- work = (callable(elem, *args, **named) for elem in iterable)
- return defer.DeferredList([coop.coiterate(work) for i in range(count)])
-
-def download(xxx_todo_changeme):
- (url, fileName) = xxx_todo_changeme
- return client.downloadPage(url, file(fileName, 'wb'))
-
-urls = [(url, str(n)) for (n, url) in enumerate(file('urls.txt'))]
-finished = parallel(urls, 50, download)
-finished.addErrback(log.err)
-finished.addCallback(lambda ign: reactor.stop())
-reactor.run()
diff --git a/languages/python/networking_twisted_parallel2.py b/languages/python/networking_twisted_parallel2.py
deleted file mode 100644
index 2d964ca4..00000000
--- a/languages/python/networking_twisted_parallel2.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/python2.6
-
-from twisted.internet import defer, task
-from twisted.python import log
-from twisted.internet import reactor
-from twisted.web import client
-from twisted.internet.utils import getProcessValue
-
-executable = '/home/senthil/uthcode/python/sometask'
-
-def parallel(count=None):
- coop = task.Cooperator()
- work = (getProcessValue(executable) for i in range(10))
- if count:
- return defer.DeferredList([coop.coiterate(work) for i in range(count)])
- else:
- return coop.coiterate(work)
-
-finished = parallel()
-finished.addErrback(log.err)
-finished.addCallback(lambda ign: reactor.stop())
-reactor.run()
diff --git a/languages/python/networking_udp1.py b/languages/python/networking_udp1.py
deleted file mode 100644
index de1ccb5c..00000000
--- a/languages/python/networking_udp1.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import socket
-import sys
-
-# Create a TCP/IP socket
-sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
-# Bind the socket to the port
-server_address = ('localhost', 10000)
-print('starting up on %s port %s' % server_address, file=sys.stderr)
-sock.bind(server_address)
-while True:
- print('\nwaiting to receive message', file=sys.stderr)
- data, address = sock.recvfrom(4096)
-
- print('received %s bytes from %s' % (len(data), address), file=sys.stderr)
- print(data, file=sys.stderr)
-
- if data:
- sent = sock.sendto(data, address)
- print('sent %s bytes back to %s' % (sent, address), file=sys.stderr)
diff --git a/languages/python/networking_udp2.py b/languages/python/networking_udp2.py
deleted file mode 100644
index 2ca5f5d8..00000000
--- a/languages/python/networking_udp2.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import socket
-import sys
-
-# Create a UDP socket
-sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-sock.bind(('',54557))
-
-server_address = ('localhost', 10000)
-message = 'This is the message. It will be repeated.'
-
-try:
-
- # Send data
- print('sending "%s"' % message, file=sys.stderr)
- sent = sock.sendto(message, server_address)
- print(sock.getsockname()[1])
-
- # Receive response
- print('waiting to receive', file=sys.stderr)
- data, server = sock.recvfrom(4096)
- print('received "%s"' % data, file=sys.stderr)
-
-finally:
- print('closing socket', file=sys.stderr)
- sock.close()
diff --git a/languages/python/networking_udp_time.py b/languages/python/networking_udp_time.py
deleted file mode 100644
index 2d7f2a24..00000000
--- a/languages/python/networking_udp_time.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from socket import *
-from struct import unpack
-from time import ctime, sleep
-from sys import argv
-
-argv = argv[1:]
-if len(argv) == 0:
- argv = [ 'time-nw.nist.gov' ]
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.settimeout(5.0)
-
-for server in argv:
- print(server, ":", end=' ')
- try:
- s.sendto('', 0, (server, 37))
- t = int(unpack('!L', s.recv(16)[:4])[0])
- # Convert from 1900/01/01 epoch to 1970/01/01 epoch
- t -= 2208988800
- print(ctime(t))
- except timeout:
- print("TIMEOUT")
- except:
- print("ERROR")
-
-s.close()
diff --git a/languages/python/software_engineering_copy_files_unicode.py b/languages/python/software_engineering_copy_files_unicode.py
deleted file mode 100644
index eebdf01b..00000000
--- a/languages/python/software_engineering_copy_files_unicode.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-"""
-The copyfiles function from source to destination, if the source and
-destination was unicode filenames. Remember to declaring the encoding used by
-the program if using Python2.
-"""
-
-
-import os
-import shutil
-
-def copyfiles(from_dir, to_dir):
- files_in_dir = str(from_dir)
- files_to_dir = str(to_dir)
- for root, dirs, files in files_in_dir:
- for curr_file in files:
- path_of_curr_file = os.path.join(root, curr_file)
- shutil.copy(path_of_curr_file, files_to_dir)
-
diff --git a/languages/python/software_engineering_createtempfiles.py b/languages/python/software_engineering_createtempfiles.py
deleted file mode 100755
index 0034fa1e..00000000
--- a/languages/python/software_engineering_createtempfiles.py
+++ /dev/null
@@ -1,30 +0,0 @@
-"""
-This program creates temporary files with content in them. This serves as
-useful utility if you want to fill a directory full of temporary files with
-some content. The content is Zen of Python.
-
-Capturing output with module evaluation by tempeorary redirection of stdout is
-shown here. Control the mkstemp call according to your requirements.
-
-"""
-import tempfile
-import random
-import os
-import sys
-
-num = random.randint(100,1000)
-
-fhandle = open('zen','w')
-old_stdout, sys.stdout = sys.stdout, fhandle
-import this
-sys.stdout = old_stdout
-fhandle.close()
-zen = open('zen').read()
-os.remove('zen')
-
-for i in range(num):
- fname = tempfile.mkstemp(suffix='.gz',prefix=str(i), dir=os.path.abspath('in'),
- text=True)[1]
- fhandle = open(fname, 'w')
- fhandle.write(zen)
- fhandle.close()
diff --git a/languages/python/software_engineering_datetime_counter.py b/languages/python/software_engineering_datetime_counter.py
deleted file mode 100644
index 962ff0fa..00000000
--- a/languages/python/software_engineering_datetime_counter.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import datetime
-
-def withtimestamp():
- format = "%Y-%m-%d-%H-%M-%S"
- return datetime.datetime.now().strftime(format=format)
-
-if __name__ == "__main__":
- print(withtimestamp())
-
-
diff --git a/languages/python/software_engineering_doctest_example.py b/languages/python/software_engineering_doctest_example.py
deleted file mode 100644
index d1c6da4a..00000000
--- a/languages/python/software_engineering_doctest_example.py
+++ /dev/null
@@ -1,60 +0,0 @@
-"""
-This is the "example" module.
-
-The example module supplies one function, factorial(). For example,
-
->>> factorial(5)
-120
-"""
-
-def factorial(n):
- """Return the factorial of n, an exact integer >= 0.
-
- If the result is small enough to fit it an int, return an int.
- Else return a long.
-
- >>> [factorial(n) for n in range(6)]
- [1, 1, 2, 6, 24, 120]
- >>> [factorial(long(n)) for n in range(6)]
- [1, 1, 2, 6, 24, 120]
- >>> factorial(30)
- 265252859812191058636308480000000L
- >>> factorial(30L)
- 265252859812191058636308480000000L
- >>> factorial(-1)
- Traceback (most recent call last):
- ...
- ValueError: n must be >= 0
-
- Factorials of floats are OK, but the float must be an exact integer:
- >>> factorial(30.1)
- Traceback (most recent call last):
- ...
- ValueError: n must be exact integer
- >>> factorial(30.0)
- 265252859812191058636308480000000L
-
- It must also not be ridiculously large:
- >>> factorial(1e100)
- Traceback (most recent call last):
- ...
- OverflowError: n too large
- """
-
- import math
- if not n >= 0:
- raise ValueError("n must be >= 0")
- if math.floor(n) != n:
- raise ValueError("n must be exact integer")
- if n+1 == n: # catch a value like 1e300
- raise OverflowError("n too large")
- result = 1
- factor = 2
- while factor <= n:
- result *= factor
- factor += 1
- return result
-
-if __name__ == '__main__':
- import doctest
- doctest.testmod()
diff --git a/languages/python/software_engineering_encoding_unicode_xml_html.py b/languages/python/software_engineering_encoding_unicode_xml_html.py
deleted file mode 100644
index ba61908b..00000000
--- a/languages/python/software_engineering_encoding_unicode_xml_html.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# From Python Cookbook. Recipe 1.23 - Encoding Unicode Data for XML and HTML.
-
-# Problem: Want to encode Unicode text for output in HTML, or some other XML
-# application, using a limited but popular encoding such as ASCII or latin-1
-
-def encode_for_xml(unicode_data, encoding='ascii'):
- return unicode_data.encode(encoding, 'xmlcharrefreplace')
-
-# If you prefer to use HTML's symbolic entity references instead. For this you
-# need to define and register a customized encoding error handler.
-
-import codecs
-from html.entities import codepoint2name
-
-def html_replace(exc):
- if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
- s = [ '&%s;' % codepoint2name[ord(c)] for c in
- exc.object[exc.start:exc.end]]
- return ''.join(s),exc.end
- else:
- raise TypeError("can't handle %s" % exc.__name__)
-
-codecs.register_error('html_replace',html_replace)
-
-
-def encode_for_html(unicode_data, encoding='ascii'):
- return unicode_data.encode(encoding, 'html_replace')
-
-
-if __name__ == '__main__':
- # demo
- data = '''\
-
-
- Encoding Test
-
-
- accented characters:
-
- - \xe0 (a + grave)
-
- \xe7 (c + cedilla)
-
- \xe9 (e + acute)
-
- symbols:
-
\xa3 (British pound)
- \u20ac (Euro)
- \u221e (Infinity)
-
-
-
- '''
- #print encode_for_xml(data)
- print(encode_for_html(data))
diff --git a/languages/python/software_engineering_exceptions_testing.py b/languages/python/software_engineering_exceptions_testing.py
deleted file mode 100644
index cca656a3..00000000
--- a/languages/python/software_engineering_exceptions_testing.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from urllib.error import URLError, HTTPError
-from io import StringIO
-
-print(isinstance(URLError("foo"), HTTPError))
-print(isinstance(HTTPError("foo", "bar", "baz", "zap", StringIO()), URLError))
-
-try:
- raise HTTPError("foo", "bar", "baz", "zap", StringIO())
-except URLError:
- print("caught this exception")
-else:
- print("this exception escaped.")
\ No newline at end of file
diff --git a/languages/python/software_engineering_fcntl_1.py b/languages/python/software_engineering_fcntl_1.py
deleted file mode 100644
index 3cc68c2c..00000000
--- a/languages/python/software_engineering_fcntl_1.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import fcntl
-import time, os
-
-FILE = "counter.txt"
-
-if not os.path.exists(FILE):
- # Create the counter file if it does not exist.
- file = open(FILE,'w')
- file.write('0')
- file.close()
-
-for i in range(20):
- # Increment the counter
- file = open(FILE,"r+")
- fcntl.flock(file.fileno(), fcntl.LOCK_EX)
- counter = int(file.readline()) + 1
- file.seek(0)
- file.write(str(counter))
- file.close()
- print(os.getpid(), '=>' , counter)
- time.sleep(0.1)
diff --git a/languages/python/software_engineering_fctrl2.py b/languages/python/software_engineering_fctrl2.py
deleted file mode 100644
index 535c4968..00000000
--- a/languages/python/software_engineering_fctrl2.py
+++ /dev/null
@@ -1,16 +0,0 @@
-memo = {}
-
-def fact(n):
- if n in memo:
- return memo[n]
- if n == 0:
- return 1
- else:
- ans = n * fact(n-1)
- memo[n] = ans
- return ans
-
-t = int(input())
-for i in range(t):
- n = int(input())
- print(fact(n))
diff --git a/languages/python/software_engineering_fortune_card.py b/languages/python/software_engineering_fortune_card.py
deleted file mode 100644
index f372b62a..00000000
--- a/languages/python/software_engineering_fortune_card.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import textwrap
-import subprocess
-from PIL import Image, ImageFont, ImageDraw
-import glob, os
-im = Image.new("CMYK",(800,400))
-
-p = subprocess.Popen(['fortune','-s'],
- stdout = subprocess.PIPE,
- stderr = subprocess.PIPE)
-proc_stdout, proc_stderr = p.communicate()
-text = proc_stdout
-
-chosenfont = ImageFont.truetype('font.ttf',50)
-draw = ImageDraw.Draw(im)
-x , y = 10, 10
-words_in_text = textwrap.wrap(text, 40)
-for word in words_in_text:
- draw.text((x,y), word, font=chosenfont)
-# x = x + 20
- y = y + 40
-im.save('fortune.jpg')
diff --git a/languages/python/software_engineering_htmlformatter.py b/languages/python/software_engineering_htmlformatter.py
deleted file mode 100644
index 3a7eb7f3..00000000
--- a/languages/python/software_engineering_htmlformatter.py
+++ /dev/null
@@ -1,99 +0,0 @@
-# written by Eric
-# http://studiozero.proboards.com/index.cgi?board=opensrc&action=display&thread=10666
-
-import sys
-
-if sys.version.startswith('3'):
- from html.parser import HTMLParser
-else:
- from html.parser import HTMLParser
-
-class HTMLFormatter(HTMLParser):
- """Formats HTML"""
-
- def __init__(self):
- HTMLParser.__init__(self)
- self.tabbed = 0
- self.formatted = []
-
- def append(self, data):
- self.formatted.append(str(data))
-
- def _write_tabs(self):
- self.append('\t'*self.tabbed)
-
- def _format_attrs(self, attrs):
- fattrs = ""
- for a,v in attrs:
- fattrs = fattrs + " " + a + '="' + v.replace('"', '\\"') + '"'
- return fattrs
-
- def _format_tag(self, tag, ttype='start', ats=None):
- ftag = '<'
- if ttype == 'end':
- ftag = ftag + '/'
- ftag = ftag + tag
- if ats != None and len(ats):
- ftag = ftag + self._format_attrs(ats)
- if ttype == 'self':
- ftag = ftag + ' /'
- ftag = ftag + '>'
- return ftag
-
- def handle_starttag(self, tag, attrs):
- self._write_tabs()
- self.tabbed = self.tabbed + 1
- self.append(self._format_tag(tag, ats=attrs) + '\n')
-
- def handle_endtag(self, tag):
- self.tabbed = self.tabbed - 1
- self._write_tabs()
- self.append(self._format_tag(tag, ttype='end') + '\n')
-
- def handle_startendtag(self, tag, attrs):
- self._write_tabs()
- self.append(self._format_tag(tag, ttype='self', ats=attrs) + '\n')
-
- def handle_data(self, data):
- data = data.strip()
- if(len(data)):
- self._write_tabs()
- self.append(data + '\n')
-
- def handle_charref(self, name):
- self.append(''+name+';')
-
- def handle_entityref(self, name):
- self.append('&'+name+';')
-
- def handle_comment(self, data):
- data = ''
- self._write_tabs();
- self.append(data + '\n')
-
- def handle_decl(self, decl):
- self._write_tabs()
- self.append('')
-
- def handle_pi(self, data):
- self._write_tabs()
- self.append(''+data+'>')
-
- def render(self):
- return "".join(self.formatted)
-
-if __name__ == "__main__":
- import sys
- if len(sys.argv) == 3:
- try:
- n = HTMLFormatter()
- f = open(sys.argv[1], 'r')
- n.feed(f.read())
- f.close()
- f = open(sys.argv[2], 'w')
- f.write(n.render())
- f.close()
- except IOError:
- print(("Failed opening or writing to files '{0}', '{1}'".format(sys.argv[1], sys.argv[2])))
- else:
- print("Wrong number of arguments")
diff --git a/languages/python/software_engineering_htmlwriter.py b/languages/python/software_engineering_htmlwriter.py
deleted file mode 100644
index 64d3b171..00000000
--- a/languages/python/software_engineering_htmlwriter.py
+++ /dev/null
@@ -1,97 +0,0 @@
-"""
-This program is free software; you can redistribute it and/or modify it
-under the terms of the GNU General Public License as published by the
-Free Software Foundation; either version 2 of the License, or (at your
-option) any later version. See .
-
-This program is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-for more details.
-"""
-
-class TreeNode(list):
- def __init__(self, tag, wrapper_node=None, **kwds):
- super(TreeNode, self).__init__()
- self._wrap = wrapper_node
- self._tag = tag
- self._attrs = kwds
-
- def _render_attrs(self):
- if self._attrs:
- return ' ' + ' '.join('%s="%s"' % attr for attr in self._attrs.items())
- else:
- return ''
-
- def _render(self, depth=0):
- depthStr = " " * (depth * 4)
- result = [depthStr + '<%s%s>' % (self._tag, self._render_attrs())]
- for content in self:
- try:
- content = content._render(depth=depth+1)
- except AttributeError:
- content = str(content)
- if self._wrap:
- result.append(self._wrap(content)._render(depth=depth+1))
- else:
- result.append(content)
- result.append(depthStr + '%s>' % self._tag)
- return '\n'.join(result)
-
- def __str__(self):
- return self._render()
-
-class Document(TreeNode):
- def __init__(self, title):
- super(Document, self).__init__('body')
- self._title = title
-
- def _render(self, depth=0):
- html = TreeNode('html', lang='en')
- head = TreeNode('head')
- titleNode = TreeNode('title')
- titleNode.append(self._title)
- head.append(titleNode)
- html.append(head)
- body = super(Document, self)._render(depth+1)
- html.append(body)
- return html._render(depth=depth)
-
-def _create_tag(tag, wrapper_node=None, use_list=False):
- def _tag(content=None, *args, **kwds):
- t = TreeNode(tag=tag, wrapper_node=wrapper_node, *args, **kwds)
- if content:
- if use_list:
- t.extend(content)
- else:
- t.append(content)
- return t
- return _tag
-
-Paragraph = _create_tag('p')
-Heading = _create_tag('h1')
-Subheading = _create_tag('h2')
-Row = _create_tag('tr', wrapper_node=_create_tag('td'), use_list=True)
-HeadingRow = _create_tag('tr', wrapper_node=_create_tag('th'), use_list=True)
-Table = _create_tag('table')
-
-
-
-if __name__ == '__main__':
- # A simple example that creates a basic HTML document
- # and outputs it to file.html
-
- doc = Document("Hello World")
- doc.append(Heading("This is a heading"))
- doc.append(Subheading("This is a subheading"))
- doc.append(Paragraph("This is a paragraph"))
- t = Table(cellpadding="10", border="1")
- t.append(HeadingRow(["Col1", "Col2", "Col3"]))
- t.append(Row(["Column1", "Column2", "Column3"]))
- doc.append(t)
- print(doc)
-## f=open('file.html', 'w')
-## f.write(doc)
-## f.close()
-
-
diff --git a/languages/python/software_engineering_ideone_post.py b/languages/python/software_engineering_ideone_post.py
deleted file mode 100644
index a7ae51c2..00000000
--- a/languages/python/software_engineering_ideone_post.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import os
-from ideone import Ideone
-i = Ideone(os.getenv('IDEUSER'), os.getenv('IDEPASS'))
-print(i.create_submission('print(42)', language_name='python',run=False))
diff --git a/languages/python/software_engineering_logging1.py b/languages/python/software_engineering_logging1.py
deleted file mode 100644
index 593b3fb3..00000000
--- a/languages/python/software_engineering_logging1.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import logging
-FILENAME = 'logfile.txt'
-logging.basicConfig(filename=FILENAME, level=logging.DEBUG, filemode='w')
-logging.debug("This message will go into the logfile")
diff --git a/languages/python/software_engineering_logging2.py b/languages/python/software_engineering_logging2.py
deleted file mode 100644
index c7023900..00000000
--- a/languages/python/software_engineering_logging2.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import glob
-import logging
-import logging.handlers
-
-mylogger = logging.getLogger("toolserver")
-mylogger.setLevel(logging.DEBUG)
-
-FILENAME = "log2.txt"
-
-handler = logging.handlers.RotatingFileHandler(FILENAME,
- maxBytes=20,
- backupCount=5)
-mylogger.addHandler(handler)
-
-for i in range(20):
- mylogger.debug(i)
-
-files = glob.glob("%s.*" % FILENAME)
-
-for f in files:
- print(f)
diff --git a/languages/python/software_engineering_logging3.py b/languages/python/software_engineering_logging3.py
deleted file mode 100644
index 5c93f218..00000000
--- a/languages/python/software_engineering_logging3.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import logging
-import sys
-
-LEVELS = {'debug': logging.DEBUG,
- 'info': logging.INFO,
- 'warning': logging.WARNING,
- 'error': logging.ERROR,
- 'critical': logging.CRITICAL
- }
-
-if len(sys.argv) > 1:
- log_level = sys.argv[1]
- level = LEVELS.get(log_level, logging.NOTSET)
- logging.basicConfig(level=level)
-
- logging.debug('This is a debug message')
- logging.info('This is a info message')
- logging.warning('This is a warning message.')
- logging.error('This is a error message.')
- logging.critical('This is a critical message.')
diff --git a/languages/python/software_engineering_logging4.py b/languages/python/software_engineering_logging4.py
deleted file mode 100644
index a18bdd3e..00000000
--- a/languages/python/software_engineering_logging4.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import logging
-
-logger1 = logging.getLogger('package1.module1')
-logger2 = logging.getLogger('package1.module2')
-
-logging.basicConfig(level=logging.WARNING)
-
-logger1.warning('This is a warning message')
-logger2.warning('This is a another warning message')
-
diff --git a/languages/python/software_engineering_logging5.py b/languages/python/software_engineering_logging5.py
deleted file mode 100644
index b77c2927..00000000
--- a/languages/python/software_engineering_logging5.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import logging
-
-logger = logging.getLogger("simple_example")
-logger.setLevel(logging.DEBUG)
-
-ch = logging.StreamHandler()
-ch.setLevel(logging.DEBUG)
-
-formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
-ch.setFormatter(formatter)
-
-logger.addHandler(ch)
-
-logger.debug("This is a debug message")
-logger.info("This is a info message")
-logger.warning("This is a warning message")
-logger.error("This is a error message")
-logger.critical("This is a critical message.")
diff --git a/languages/python/software_engineering_multiprocessing_1.py b/languages/python/software_engineering_multiprocessing_1.py
deleted file mode 100644
index cc8b0411..00000000
--- a/languages/python/software_engineering_multiprocessing_1.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import multiprocessing
-import subprocess
-
-def calculate(value):
- return value * 10
-
-if __name__ == '__main__':
- pool = multiprocessing.Pool(None)
- tasks = list(range(10000))
- results = []
- r = pool.map_async(calculate, tasks, callback=results.append)
- r.wait() # Wait on the results
- print(results)
diff --git a/languages/python/software_engineering_os_exec1.py b/languages/python/software_engineering_os_exec1.py
deleted file mode 100644
index f8b657e6..00000000
--- a/languages/python/software_engineering_os_exec1.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import os
-output = os.execl("/bin/date")
-print(output)
diff --git a/languages/python/software_engineering_provide_warnings.py b/languages/python/software_engineering_provide_warnings.py
deleted file mode 100644
index 83f6d792..00000000
--- a/languages/python/software_engineering_provide_warnings.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from functools import wraps
-from warnings import warn
-
-def add_warning(func, oldname):
- @wraps(func)
- def _wrapped(*args, **kwds):
- warn('Deprecated function %s being called' % oldname)
- return func(*args, **kwds)
- return _wrapped
-
-def test(a=2, b=4):
- print(a + b)
-
-old_test = add_warning(test, 'old_test')
-
-old_test(123)
diff --git a/languages/python/software_engineering_ptags.py b/languages/python/software_engineering_ptags.py
deleted file mode 100644
index ac013560..00000000
--- a/languages/python/software_engineering_ptags.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#! /usr/bin/env python
-
-# ptags
-#
-# Create a tags file for Python programs, usable with vi.
-# Tagged are:
-# - functions (even inside other defs or classes)
-# - classes
-# - filenames
-# Warns about files it cannot open.
-# No warnings about duplicate tags.
-
-import sys, re, os
-
-tags = [] # Modified global variable!
-
-def main():
- args = sys.argv[1:]
- for filename in args:
- treat_file(filename)
- if tags:
- fp = open('tags', 'w')
- tags.sort()
- for s in tags: fp.write(s)
-
-
-expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
-matcher = re.compile(expr)
-
-def treat_file(filename):
- try:
- fp = open(filename, 'r')
- except:
- sys.stderr.write('Cannot open %s\n' % filename)
- return
- base = os.path.basename(filename)
- if base[-3:] == '.py':
- base = base[:-3]
- s = base + '\t' + filename + '\t' + '1\n'
- tags.append(s)
- while 1:
- line = fp.readline()
- if not line:
- break
- m = matcher.match(line)
- if m:
- content = m.group(0)
- name = m.group(2)
- s = name + '\t' + filename + '\t/^' + content + '/\n'
- tags.append(s)
-
-if __name__ == '__main__':
- main()
diff --git a/languages/python/software_engineering_run_under_strace.py b/languages/python/software_engineering_run_under_strace.py
deleted file mode 100644
index bd2fefed..00000000
--- a/languages/python/software_engineering_run_under_strace.py
+++ /dev/null
@@ -1,2 +0,0 @@
-import subprocess
-subprocess.Popen("ls")
diff --git a/languages/python/software_engineering_runningtime.py b/languages/python/software_engineering_runningtime.py
deleted file mode 100644
index e30621d2..00000000
--- a/languages/python/software_engineering_runningtime.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""
-Book: The Essentials of Computer Architecture.
-Chapter: 4
-Problem: Write a Computer Program that measures the difference in execution
-times between the integer addition and integer division. Execute the operation
-100,000 times and compare the difference in the running time.
-"""
-import timeit
-t1 = timeit.Timer("4+2")
-m1 = (100000 * t1.timeit(100000) / 100000)
-print('Integer Addition takes: %f usecs/loop' % m1)
-t2 = timeit.Timer("4/2")
-m2 = (100000 * t2.timeit(100000) / 100000)
-print('Integer Division takes: %f usecs/loop' % m2)
-print('The difference is %s usecs' % (m2-m1))
diff --git a/languages/python/software_engineering_runningtime_intaddition.py b/languages/python/software_engineering_runningtime_intaddition.py
deleted file mode 100644
index eaeefdcb..00000000
--- a/languages/python/software_engineering_runningtime_intaddition.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""
-Book: The Essentials of Computer Architecture.
-Chapter: 4
-Problem: Write a Computer Program that measures the difference in execution
-times between the integer addition and integer division. Execute the operation
-100,000 times and compare the difference in the running time.
-
-Extend the Program to compare between 16 bit, 32 bit and 64 bit integer
-addition.
-
-Tip: Python 2.7 has bit_length() for int objects.
-
-Interesting Observation:
- For 16 bit ints, the operations take more time than 32 bit numbers.
-
-"""
-import timeit
-
-for bits in [16,32,64]:
- num1 = pow(2,bits)
-
- # Integer Addition
-
- print('Integer Addition between %d bit numbers' % (bits))
- num2 = num1 + 2
- stmt = "%d +%d" % (num2, num1)
- t = timeit.Timer(stmt)
- m = (100000 * t.timeit(100000) / 100000)
- print('%f usecs/loop' % (m))
-
- # Integer Division now.
-
- print('Integer Division between %d bit numbers' % (bits))
- num2 = 2 * num1
- stmt = "%d/%d" % (num2, num1)
- t = timeit.Timer(stmt)
- m = (100000 * t.timeit(100000) / 100000)
- print('%f usecs/loop' % (m))
diff --git a/languages/python/software_engineering_runningtime_intvsfloat.py b/languages/python/software_engineering_runningtime_intvsfloat.py
deleted file mode 100644
index 9c7631e0..00000000
--- a/languages/python/software_engineering_runningtime_intvsfloat.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""
-Book: The Essentials of Computer Architecture.
-Chapter: 4
-Problem: Write a Computer Program that measures the difference in execution
-times between the integer division and floating point division. Execute the operation
-100,000 times and compare the difference in the running time.
-
-Interesting Observation:
- * Integer Division is taking more time.
-
-"""
-
-import timeit
-num1 = pow(2,64)
-num2 = num1 * 2
-stmt = "%d/%d" % (num2,num1)
-print('Test:', stmt)
-t1 = timeit.Timer(stmt)
-m1 = (100000 * t1.timeit(100000) / 100000)
-print('Integer Division takes: %f usecs/loop' % m1)
-
-num2 = num1 * 2.0
-stmt = "%f/%f" % (num2, num1)
-print('Test:', stmt)
-t2 = timeit.Timer(stmt)
-m2 = (100000 * t2.timeit(100000) / 100000)
-print('Floating point Division takes: %f usecs/loop' % m2)
-print('The difference is %s usecs' % (m2-m1))
diff --git a/languages/python/software_engineering_simple_subprocess.py b/languages/python/software_engineering_simple_subprocess.py
deleted file mode 100644
index 0a21cab8..00000000
--- a/languages/python/software_engineering_simple_subprocess.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import subprocess
-proc = subprocess.Popen(['./simple'], stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
-out,err = proc.communicate()
-print(out)
-print(err)
diff --git a/languages/python/software_engineering_simple_threading1.py b/languages/python/software_engineering_simple_threading1.py
deleted file mode 100644
index 4f5b861d..00000000
--- a/languages/python/software_engineering_simple_threading1.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import threading
-import urllib.request, urllib.parse, urllib.error
-
-class MultiUrl(threading.Thread):
- def __init__(self, url):
- threading.Thread.__init__(self)
- self.url = url
- def run(self):
- urllib.request.urlopen(self.url).read()
-
-background = MultiUrl('http://slashdot.org')
-background.start()
-print('main continues')
-background.join()
-print('main is done.')
diff --git a/languages/python/software_engineering_sqlite3.py b/languages/python/software_engineering_sqlite3.py
deleted file mode 100755
index f14534c5..00000000
--- a/languages/python/software_engineering_sqlite3.py
+++ /dev/null
@@ -1,132 +0,0 @@
-from collections import namedtuple
-import sqlite3
-
-# make a basic Link class
-Link = namedtuple('Link', ['id', 'submitter_id', 'submitted_time', 'votes',
- 'title', 'url'])
-
-# list of Links to work with
-links = [
- Link(0, 60398, 1334014208.0, 109,
- "C overtakes Java as the No. 1 programming language in the TIOBE index.",
- "http://pixelstech.net/article/index.php?id=1333969280"),
- Link(1, 60254, 1333962645.0, 891,
- "This explains why technical books are all ridiculously thick and overpriced",
- "http://prog21.dadgum.com/65.html"),
- Link(23, 62945, 1333894106.0, 351,
- "Learn Haskell Fast and Hard",
- "http://yannesposito.com/Scratch/en/blog/Haskell-the-Hard-Way/"),
- Link(2, 6084, 1333996166.0, 81,
- "Announcing Yesod 1.0- a robust, developer friendly, high performance web framework for Haskell",
- "http://www.yesodweb.com/blog/2012/04/announcing-yesod-1-0"),
- Link(3, 30305, 1333968061.0, 270,
- "TIL about the Lisp Curse",
- "http://www.winestockwebdesign.com/Essays/Lisp_Curse.html"),
- Link(4, 59008, 1334016506.0, 19,
- "The Downfall of Imperative Programming. Functional Programming and the Multicore Revolution",
- "http://fpcomplete.com/the-downfall-of-imperative-programming/"),
- Link(5, 8712, 1333993676.0, 26,
- "Open Source - Twitter Stock Market Game - ",
- "http://www.twitstreet.com/"),
- Link(6, 48626, 1333975127.0, 63,
- "First look: Qt 5 makes JavaScript a first-class citizen for app development",
- "http://arstechnica.com/business/news/2012/04/an-in-depth-look-at-qt-5-making-javascript-a-first-class-citizen-for-native-cross-platform-developme.ars"),
- Link(7, 30172, 1334017294.0, 5,
- "Benchmark of Dictionary Structures", "http://lh3lh3.users.sourceforge.net/udb.shtml"),
- Link(8, 678, 1334014446.0, 7,
- "If It's Not on Prod, It Doesn't Count: The Value of Frequent Releases",
- "http://bits.shutterstock.com/?p=165"),
- Link(9, 29168, 1334006443.0, 18,
- "Language proposal: dave",
- "http://davelang.github.com/"),
- Link(17, 48626, 1334020271.0, 1,
- "LispNYC and EmacsNYC meetup Tuesday Night: Large Scale Development with Elisp ",
- "http://www.meetup.com/LispNYC/events/47373722/"),
- Link(101, 62443, 1334018620.0, 4,
- "research!rsc: Zip Files All The Way Down",
- "http://research.swtch.com/zip"),
- Link(12, 10262, 1334018169.0, 5,
- "The Tyranny of the Diff",
- "http://michaelfeathers.typepad.com/michael_feathers_blog/2012/04/the-tyranny-of-the-diff.html"),
- Link(13, 20831, 1333996529.0, 14,
- "Understanding NIO.2 File Channels in Java 7",
- "http://java.dzone.com/articles/understanding-nio2-file"),
- Link(15, 62443, 1333900877.0, 1244,
- "Why vector icons don't work",
- "http://www.pushing-pixels.org/2011/11/04/about-those-vector-icons.html"),
- Link(14, 30650, 1334013659.0, 3,
- "Python - Getting Data Into Graphite - Code Examples",
- "http://coreygoldberg.blogspot.com/2012/04/python-getting-data-into-graphite-code.html"),
- Link(16, 15330, 1333985877.0, 9,
- "Mozilla: The Web as the Platform and The Kilimanjaro Event",
- "https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/Y9v46wFeejA"),
- Link(18, 62443, 1333939389.0, 104,
- "github is making me feel stupid(er)",
- "http://www.serpentine.com/blog/2012/04/08/github-is-making-me-feel-stupider/"),
- Link(19, 6937, 1333949857.0, 39,
- "BitC Retrospective: The Issues with Type Classes",
- "http://www.bitc-lang.org/pipermail/bitc-dev/2012-April/003315.html"),
- Link(20, 51067, 1333974585.0, 14,
- "Object Oriented C: Class-like Structures",
- "http://cecilsunkure.blogspot.com/2012/04/object-oriented-c-class-like-structures.html"),
- Link(10, 23944, 1333943632.0, 188,
- "The LOVE game framework version 0.8.0 has been released - with GLSL shader support!",
- "https://love2d.org/forums/viewtopic.php?f=3&t=8750"),
- Link(22, 39191, 1334005674.0, 11,
- "An open letter to language designers: Please kill your sacred cows. (megarant)",
- "http://joshondesign.com/2012/03/09/open-letter-language-designers"),
- Link(21, 3777, 1333996565.0, 2,
- "Developers guide to Garage48 hackatron",
- "http://martingryner.com/developers-guide-to-garage48-hackatron/"),
- Link(24, 48626, 1333934004.0, 17,
- "An R programmer looks at Julia",
- "http://www.r-bloggers.com/an-r-programmer-looks-at-julia/")]
-
-# links is a list of Link objects. Links have a handful of properties. For
-# example, a Link's number of votes can be accessed by link.votes if "link" is a
-# Link.
-
-# make and populate a table
-db = sqlite3.connect(':memory:')
-db.execute('create table links ' +
- '(id integer, submitter_id integer, submitted_time integer, ' +
- 'votes integer, title text, url text)')
-for l in links:
- db.execute('insert into links values (?, ?, ?, ?, ?, ?)', l)
-
-# db is an in-memory sqlite database that can respond to sql queries using the
-# execute() function.
-#
-# For example. If you run
-#
-# c = db.execute("select * from links")
-#
-# c will be a "cursor" to the results of that query. You can use the fetchmany()
-# function on the cursor to convert that cursor into a list of results. These
-# results won't be Links; they'll be tuples, but they can be passed turned into
-# a Link.
-#
-# For example, to print all the votes for all of the links, do this:
-#
-# c = db.execute("select * from links")
-# for link_tuple in c:
-# link = Link(*link_tuple)
-# print link.votes
-#
-# QUIZ - make the function query() return the number of votes the link with ID = 2 has
-def query():
- c = db.execute("select * from links where id==2")
-
- link = Link(*c.fetchone())
- return link.votes
-
-
-def query2():
- c = db.execute("select * from links where submitter_id = 62443 and votes > 1000")
- link = Link(*c.fetchone())
- print(link.id)
- for link_tuple in c:
- link = Link(*link_tuple)
- print(link.id)
-
-query2()
diff --git a/languages/python/software_engineering_stringio.py b/languages/python/software_engineering_stringio.py
deleted file mode 100644
index bd39f7e9..00000000
--- a/languages/python/software_engineering_stringio.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import io
-MSG = "That man is depriving a village somewhere of a computer Scientist."
-
-f = io.StringIO(MSG)
-with f:
- print((f.read()))
diff --git a/languages/python/software_engineering_subprocess1.py b/languages/python/software_engineering_subprocess1.py
deleted file mode 100644
index ea13864e..00000000
--- a/languages/python/software_engineering_subprocess1.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import subprocess
-
-output_with_shell_true = subprocess.Popen("/bin/date;who;fortune",shell=True).wait()
-print('True', output_with_shell_true)
-output_with_shell_false = subprocess.Popen("/bin/date;who;fortune",shell=True).wait()
-print('False', output_with_shell_false)
diff --git a/languages/python/software_engineering_subprocess2.py b/languages/python/software_engineering_subprocess2.py
deleted file mode 100644
index 2670a62a..00000000
--- a/languages/python/software_engineering_subprocess2.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""
-Finding 'class' in every file python file in the directory.
-'out' and 'err' are string objects containing the standard output and,
-eventually, the error output.
-
-find -iname *.py|xargs grep class
-
-"""
-from subprocess import Popen, PIPE
-find_process = Popen(['find', '-iname', '*.py'], stdout=PIPE)
-grep_process = Popen(['xargs', 'grep', 'class'], stdin=find_process.stdout, stdout=PIPE)
-out, err = grep_process.communicate()
-print(out)
diff --git a/languages/python/software_engineering_subprocess3.py b/languages/python/software_engineering_subprocess3.py
deleted file mode 100644
index 189604a6..00000000
--- a/languages/python/software_engineering_subprocess3.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import subprocess
-import os
-ret_value= subprocess.Popen(['find','-name','*.py']).wait()
-print(ret_value)
-ret_value = os.system('find -name "*.py"')
-print(ret_value)
diff --git a/languages/python/software_engineering_subprocess4.py b/languages/python/software_engineering_subprocess4.py
deleted file mode 100644
index d35694e0..00000000
--- a/languages/python/software_engineering_subprocess4.py
+++ /dev/null
@@ -1,5 +0,0 @@
-import subprocess
-proc = subprocess.Popen(['date'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
-out,err = proc.communicate()
-print(out)
-print(err)
diff --git a/languages/python/software_engineering_subprocess5.py b/languages/python/software_engineering_subprocess5.py
deleted file mode 100644
index 7f6659ef..00000000
--- a/languages/python/software_engineering_subprocess5.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import subprocess
-f = file('data.out','w')
-ef = file('error.out','w')
-cmd = '/home/senthil/uthcode/python/somebigout'
-p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=ef)
-errcode = p.wait()
-f.close()
-ef.close()
-if errcode:
- with open('error.out') as ef:
- pass
- #errmess = p.stderr.read()
-with open('data.out') as f:
- pass
diff --git a/languages/python/software_engineering_test_codec01.py b/languages/python/software_engineering_test_codec01.py
deleted file mode 100644
index b97f234e..00000000
--- a/languages/python/software_engineering_test_codec01.py
+++ /dev/null
@@ -1,20 +0,0 @@
-if __name__ == '__main__':
- # define our Unicode string
- uni = "Hello\u001A\u0BC3\u1451\U0001D10CUnicode"
-
- # UTF-8 and UTF-16 can fully encode *any* unicode string
-
- print("UTF-8", repr(uni.encode('utf-8')))
- print("UTF-16", repr(uni.encode('utf-16')))
-
- # ASCII can only work with code values from 0-127. Below we tell Python
-
- print("ASCII ", uni.encode('ascii','replace'))
-
- # ISO-8859-1 is similar to ASCII
-
- print("ISO-8859-1 ", uni.encode('iso-8859-1','replace'))
-
- uni = uni.encode('utf-8')
- bstr = str(uni, 'utf-8')
- print("Back from UTF-8:", repr(bstr))
diff --git a/languages/python/software_engineering_test_codec02.py b/languages/python/software_engineering_test_codec02.py
deleted file mode 100644
index b7786442..00000000
--- a/languages/python/software_engineering_test_codec02.py
+++ /dev/null
@@ -1,7 +0,0 @@
-a = '\U0001ff00'
-
-print("Length: ", len(a))
-
-print("Chars: ")
-for c in a:
- print(repr(c))
diff --git a/languages/python/software_engineering_test_codec03.py b/languages/python/software_engineering_test_codec03.py
deleted file mode 100644
index 4675c5ad..00000000
--- a/languages/python/software_engineering_test_codec03.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# {PI} {Sigma} {Omega} as ISO-8859-7 encoded string
-b = '\xd0\xd3\xd9'
-
-# Convert to Unicode ('universal format')
-u = str(b, 'iso-8859-7')
-print(repr(u))
-
-# and back to ISO-8859-7
-c = u.encode('iso-8859-7')
-print(repr(c))
diff --git a/languages/python/software_engineering_test_dedent.py b/languages/python/software_engineering_test_dedent.py
deleted file mode 100644
index b85050e8..00000000
--- a/languages/python/software_engineering_test_dedent.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from textwrap import dedent
-
-def test():
- # end first line with \ to avoid the empty line!
- s = '''\
- hello
- world
- '''
- print(s)
- print(repr(s)) # prints ' hello\n world\n '
- print(repr(dedent(s))) # prints 'hello\n world\n'
-test()
diff --git a/languages/python/software_engineering_threading2.py b/languages/python/software_engineering_threading2.py
deleted file mode 100644
index 6d8c6377..00000000
--- a/languages/python/software_engineering_threading2.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import threading
-
-def appstart():
- print('Start your dev_appserver')
- # Do operations
-
-def coveragestart():
- print('Start your coverage')
- # Do operations
-
-t = threading.Thread(name='start', target=appstart)
-w = threading.Thread(name='stop', target=coveragestart)
-t.start()
-w.start()
-w.join() # Note that I am joing coveragestart first
-t.join()
diff --git a/languages/python/software_engineering_time_converter.py b/languages/python/software_engineering_time_converter.py
deleted file mode 100644
index ff166b45..00000000
--- a/languages/python/software_engineering_time_converter.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import time
-print(time.time())
-print(time.strftime("%m/%d/%y/%H:%M",time.gmtime(time.time())))
diff --git a/languages/python/software_engineering_tkintertimer.py b/languages/python/software_engineering_tkintertimer.py
deleted file mode 100644
index 1bdf854f..00000000
--- a/languages/python/software_engineering_tkintertimer.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import tkinter
-import time
-
-class App():
- def __init__(self,target):
- self.root = tkinter.Tk()
- self.label = tkinter.Label(text="")
- self.label.pack()
- self.update_clock()
- self.root.mainloop()
-
- def update_clock(self):
- now = time.strftime("%H:%M:%S")
- self.label.configure(text=now)
- self.root.after(1000, self.update_clock)
-
-HH = 23
-MM = 30
-
-now = time.localtime(time.time())
-hour = 23
-minutes = 30
-target = time.mktime((year,mon,mday,hour,minutes,sec,wday,yday,isdst))
-
-app=App(target)
diff --git a/languages/python/software_engineering_twitter_phidget.py b/languages/python/software_engineering_twitter_phidget.py
deleted file mode 100644
index cb1125bd..00000000
--- a/languages/python/software_engineering_twitter_phidget.py
+++ /dev/null
@@ -1,164 +0,0 @@
-#!/usr/bin/env python
-
-# Author: O.R.Senthil Kumaran
-# Credits: Example Python Snipppet from the Phidget Library.
-# Adapted from TextLCD-simple.py by 'Adam Stelmack'.
-
-
-from ctypes import *
-import sys
-from time import sleep
-
-#Phidget specific imports
-from Phidgets.Phidget import PhidgetID
-from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
-from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs
-from Phidgets.Devices.TextLCD import TextLCD, TextLCD_ScreenSize
-
-# for twitter
-
-import tweetstream
-import json
-import urllib.request, urllib.error, urllib.parse
-import re
-
-USER= "username"
-PASSWORD = "yourpassword"
-SEARCHTERM = "royalwedding"
-
-stream = tweetstream.TweetStream(USER, PASSWORD)
-
-#Create an TextLCD object
-try:
- textLCD = TextLCD()
-except RuntimeError as e:
- print(("Runtime Exception: %s" % e.details))
- print("Exiting....")
- exit(1)
-
-#Information Display Function
-def DisplayDeviceInfo():
- try:
- isAttached = textLCD.isAttached()
- name = textLCD.getDeviceName()
- serialNo = textLCD.getSerialNum()
- version = textLCD.getDeviceVersion()
- rowCount = textLCD.getRowCount()
- columnCount = textLCD.getColumnCount()
- except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- return 1
- print("|------------|----------------------------------|--------------|------------|")
- print("|- Attached -|- Type -|- Serial No. -|- Version -|")
- print("|------------|----------------------------------|--------------|------------|")
- print(("|- %8s -|- %30s -|- %10d -|- %8d -|" % (isAttached, name, serialNo, version)))
- print("|------------|----------------------------------|--------------|------------|")
- print(("Number of Rows: %i -- Number of Columns: %i" % (rowCount, columnCount)))
-
-#Event Handler Callback Functions
-def TextLCDAttached(e):
- attached = e.device
- print(("TextLCD %i Attached!" % (attached.getSerialNum())))
-
-def TextLCDDetached(e):
- detached = e.device
- print(("TextLCD %i Detached!" % (detached.getSerialNum())))
-
-def TextLCDError(e):
- source = e.device
- print(("TextLCD %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description)))
-
-#Main Program Code
-try:
- textLCD.setOnAttachHandler(TextLCDAttached)
- textLCD.setOnDetachHandler(TextLCDDetached)
- textLCD.setOnErrorhandler(TextLCDError)
-except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- print("Exiting....")
- exit(1)
-
-print("Opening phidget object....")
-
-try:
- textLCD.openPhidget()
-except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- print("Exiting....")
- exit(1)
-
-print("Waiting for attach....")
-
-try:
- textLCD.waitForAttach(10000)
-except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- try:
- textLCD.closePhidget()
- except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- print("Exiting....")
- exit(1)
- print("Exiting....")
- exit(1)
-else:
- DisplayDeviceInfo()
-
-display_tweet = []
-
-try:
- if textLCD.getDeviceID()==PhidgetID.PHIDID_TEXTLCD_ADAPTER:
- textLCD.setScreenIndex(0)
- textLCD.setScreenSize(TextLCD_ScreenSize.PHIDGET_TEXTLCD_SCREEN_2x8)
-
- for tweet in stream:
- if 'text' in tweet:
- text = tweet['text']
- if type(text) == str:
- if SEARCHTERM in text.lower():
- display_tweet.append(text)
- if display_tweet:
- item = display_tweet.pop()
-
- textLCD.setBacklight(True)
- print(item)
- row1 = item[:20]
- row2 = item[20:40]
- print("Writing to first row....")
- textLCD.setDisplayString(0, row1)
- print("Writing to second row....")
- textLCD.setDisplayString(1, row2)
- sleep(2)
-
- print("Turn on cursor....")
- textLCD.setCursor(True)
- sleep(2)
-
- print("Turn on cursor blink....")
- textLCD.setCursor(False)
- textLCD.setCursorBlink(True)
- sleep(2)
-
- print("No Tweets")
- textLCD.setBacklight(False)
- textLCD.setCursorBlink(True)
- textLCD.setDisplayString(0, "")
- textLCD.setDisplayString(1, "")
- if len(display_tweet) > 100:
- break
-
-except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- print("Exiting....")
- exit(1)
-
-textLCD.setDisplayString(0, "")
-textLCD.setDisplayString(1, "")
-textLCD.setBacklight(False)
-
-try:
- textLCD.closePhidget()
-except PhidgetException as e:
- print(("Phidget Exception %i: %s" % (e.code, e.details)))
- print("Exiting....")
- exit(1)
diff --git a/languages/python/software_engineering_xmlrpcclient.py b/languages/python/software_engineering_xmlrpcclient.py
deleted file mode 100644
index 96eb298a..00000000
--- a/languages/python/software_engineering_xmlrpcclient.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import xmlrpc.client
-proxy = xmlrpc.client.ServerProxy('http://localhost:9000')
-
-# Call expliciting registered function
-
-print('dir():',proxy.dir('/'))
-try:
- print('list_contents():', proxy.list_contents('/'))
-except:
- print('You should use a registered name.')
-
-# Call the standard functions registered with server
-print('BEFORE:', 'EXAMPLE' in proxy.dir.list('/tmp'))
-print('CREATE:', proxy.dir.create('/tmp/EXAMPLE'))
-print('SHOULD EXIST:', 'EXAMPLE' in proxy.dir.list('/tmp'))
-print('REMOVE:', proxy.dir.remove('/tmp/EXAMPLE'))
-print('AFTER', 'EXAMPLE' in proxy.dir.list('/tmp'))
-
-
-# Call the function (handler) which has space
-print(getattr(proxy,'my func')(5,5))
diff --git a/languages/python/software_engineering_xmlrpcserver.py b/languages/python/software_engineering_xmlrpcserver.py
deleted file mode 100644
index dcf50ba5..00000000
--- a/languages/python/software_engineering_xmlrpcserver.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from xmlrpc.server import SimpleXMLRPCServer
-import logging
-import os
-
-# Set up logging
-logging.basicConfig(level=logging.DEBUG)
-
-server = SimpleXMLRPCServer(('localhost',9000),logRequests=True,
- allow_none=True)
-
-# Expose a function
-
-def list_contents(dir_name):
- logging.debug('list_contents(%s)', dir_name)
- return os.listdir(dir_name)
-
-server.register_function(list_contents,'dir')
-
-# Register the Standard os functions
-
-server.register_function(os.listdir,'dir.list')
-server.register_function(os.mkdir,'dir.create')
-server.register_function(os.rmdir,'dir.remove')
-
-
-# Expose a function
-
-def my_func(a, b):
- return a * b
-
-# my func handler has space in between not
-# a valid function name, but still it can be called.
-
-server.register_function(my_func,'my func')
-
-try:
- print('Use Control-C to exit')
- server.serve_forever()
-except KeyboardInterrupt:
- print('Exiting!')
-
diff --git a/languages/python/text_manipulation_argparse1.py b/languages/python/text_manipulation_argparse1.py
deleted file mode 100755
index 8ba77094..00000000
--- a/languages/python/text_manipulation_argparse1.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import argparse
-import filecmp
-
-if __name__ == '__main__':
- parser = argparse.ArgumentParser(description="Directory comparison")
- parser.add_argument("--recurse", "-r", action="store_true", default=False)
- parser.add_argument('dirs', nargs=2)
- options = parser.parse_args()
-
- dd = filecmp.dircmp(options.dirs[0], options.dirs[1])
-
- if options.recurse:
- dd.report_full_closure()
- else:
- dd.report()
diff --git a/languages/python/trie.py b/languages/python/trie.py
deleted file mode 100644
index 797f8649..00000000
--- a/languages/python/trie.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""
-Simple Trie Implementation
-"""
-
-import json
-
-_end_marker = "*"
-
-def add_word(trie, word):
- word_trie = trie
-
- for ch in word:
- if ch in word_trie:
- word_trie = word_trie[ch]
- else:
- word_trie[ch] = {}
- word_trie = word_trie[ch]
-
- word_trie[_end_marker] = _end_marker
-
- return word_trie
-
-def make_trie(*words):
- trie = dict()
-
- for word in words:
- add_word(trie, word)
-
- return trie
-
-def is_word(trie, word):
- word_trie = trie
- for ch in word:
- if ch in word_trie:
- word_trie = word_trie[ch]
- else:
- return False
- return _end_marker in word_trie
-
-def is_prefix(trie, word):
- word_trie = trie
- for ch in word:
- if ch in word_trie:
- word_trie = word_trie[ch]
- else:
- return False
-
- return True
-
-def print_trie(trie):
- print(json.dumps(trie, sort_keys=True, indent=2))
-
-trie = make_trie("hi", "hello", "help")
-
-print_trie(trie)
-
-print(is_word(trie, "hello"))
-print(is_word(trie, "he"))
-print(is_prefix(trie, "he"))
\ No newline at end of file
diff --git a/languages/python/web_cgi_ex.py b/languages/python/web_cgi_ex.py
deleted file mode 100755
index 57900a89..00000000
--- a/languages/python/web_cgi_ex.py
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/local/bin/python
-# $Id$
-
-"""
-An Example CGI Program in Python.
-
-Important modules are cgitb - cgitraceback for traceback details when something
-fails.
-
-You will have to setup your environment properly for this to work.
-"""
-
-import os
-import time
-
-import cgitb
-cgitb.enable()
-
-print("Content-Type: text/html")
-print()
-
-print("")
-print("Python CGI Example
")
-filecontents = os.listdir(os.getcwd())
-print("You can use all Python functions:
")
-print("Like this one shows you the directory contents
")
-print(filecontents)
-print("The current time is %s
" % time.ctime())
-print("")
-
diff --git a/languages/python/web_cookielib_example.py b/languages/python/web_cookielib_example.py
deleted file mode 100644
index 3401f92a..00000000
--- a/languages/python/web_cookielib_example.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import http.cookiejar, urllib.request, urllib.error, urllib.parse
-
-cj = http.cookiejar.CookieJar()
-opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
-
-req = urllib.request.Request('https://www.idcourts.us/repository/start.do')
-res = opener.open(req)
-print(cj)
-for c in cj:
- cookie_str = "%s = %s" % (c.name, c.value)
-print(cookie_str)
-
-req = urllib.request.Request('https://www.idcourts.us/repository/partySearch.do')
-req.add_header("Cookie",cookie_str)
-opener.open(req)
-print(cj)
diff --git a/languages/python/web_crawl.py b/languages/python/web_crawl.py
deleted file mode 100644
index f3acacc6..00000000
--- a/languages/python/web_crawl.py
+++ /dev/null
@@ -1,123 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-import urllib.request, urllib.parse, urllib.error
-import urllib.parse
-import sys
-import re
-import optparse
-
-try:
- from BeautifulSoup import BeautifulSoup
-except ImportError:
- print("Pre-requsite not met - BeautifulSoup library")
- sys.exit(-1)
-
-try:
- import Image
-except ImportError:
- print("Pre-requisite not met - Python Imaging library")
- sys.exit(-1)
-
-URL = 'http://www.indochino.com/'
-
-parsed_url = urllib.parse.urlparse(URL) # for default
-global_url = []
-visited_url = []
-
-def getimages(page):
- images = []
- try:
- soup = BeautifulSoup(urllib.request.urlopen(page))
- for image in soup.findAll("img"):
- img = image["src"]
- if img.split('.')[-1] in ('jpg','png','jpeg','gif'):
- parsed_img = urllib.parse.urlparse(img)
- if not parsed_img.scheme:
- img = urllib.parse.urljoin(URL,parsed_img.path)
- images.append(img)
- except (IOError, KeyError, IndexError):
- pass
- return images
-
-def guess_product_page(page):
- try:
- soup = BeautifulSoup(urllib.request.urlopen(page))
- except (IOError,KeyError):
- return False
- american_currency = soup.findAll(text=re.compile('\$\d+(\.\d{2})?'))
- other_indicators = soup.findAll(text=['discount','free', 'product details','shipping'])
- if len(american_currency) > 2 or len(other_indicators) > 2:
- return True
- else:
- return False
-
-def childrenfun(node):
- if isinstance(node, list):
- return iter(node)
- else:
- links = []
- try:
- soup = BeautifulSoup(urllib.request.urlopen(node))
- for l in soup.findAll("a"):
- l = l["href"]
- parsed = urllib.parse.urlparse(l)
- if (parsed.scheme and (parsed.scheme in ('http','https')) and (parsed.netloc in parsed_url.netloc)):
- link = urllib.parse.urlunparse((parsed.scheme,parsed.netloc,parsed.path,'','',''))
- if not link in global_url:
- global_url.append(link)
- links.append(link)
- except (IOError, KeyError):
- pass
- return links
-
-def breadth_first(tree,children=childrenfun):
- """Traverse the nodes of a tree in breadth-first order.
- The first argument should be the tree root; children
- should be a function taking as argument a tree node and
- returning an iterator of the node's children.
- """
- yield tree
- last = tree
- for node in breadth_first(tree,children):
- for child in children(node):
- yield child
- last = child
- if last == node:
- return
-
-if __name__ == '__main__':
- option_parser = optparse.OptionParser()
- option_parser.add_option('-x','--height',dest='height',default=100,type="int")
- option_parser.add_option('-y','--width', dest='width', default=100,type="int")
- option_parser.add_option('-g',dest='guess',action='store_true',default=False)
-
- (options, args) = option_parser.parse_args()
-
- if len(args) == 0:
- node = URL
- else:
- node = args[0]
- try:
- parsed_url = urllib.parse.urlparse(node)
- except ValueError:
- print('Invalid URL', node)
- sys.exit(-1)
-
- for n in breadth_first(node):
- if n not in visited_url:
- visited_url.append(n)
- print('URL %s' % n, end=' ')
- if options.guess:
- product_page = guess_product_page(n)
- if product_page:
- print('is a Product Page')
- else:
- print('is not a Product Page')
- for img in getimages(n):
- tmp_loc, hdrs = urllib.request.urlretrieve(img)
- try:
- im = Image.open(tmp_loc)
- width, height = im.size
- if width >= options.height and height >= options.width:
- print('%d %d %s' % (width, height, img))
- except Exception as exc:
- print('Did not check size: %s' % img)
diff --git a/languages/python/web_crawl2.py b/languages/python/web_crawl2.py
deleted file mode 100644
index 4a59a15b..00000000
--- a/languages/python/web_crawl2.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# -*- coding: utf8 -*-
-import io as StringIO
-
-from twisted.internet import reactor
-from twisted.web.client import getPage
-from twisted.python.util import println
-from lxml import etree
-
-def parseHtml(html):
- parser = etree.HTMLParser(encoding='utf8')
- tree = etree.parse(StringIO.StringIO(html), parser)
- return tree
-
-def extractTitle(tree):
- titleText = str(tree.xpath("//title/text()")[0])
- return titleText
-
-d = getPage('http://www.google.com')
-d.addCallback(parseHtml)
-d.addCallback(extractTitle)
-d.addBoth(println)
-
-reactor.run()
diff --git a/languages/python/web_http_auth_header_code.py b/languages/python/web_http_auth_header_code.py
deleted file mode 100644
index 67d350bd..00000000
--- a/languages/python/web_http_auth_header_code.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-if __name__ == '__main__':
- theurl = "http://mail.google.com/mail/#inbox"
- req = urllib.request.Request(theurl)
- try:
- handle = urllib.request.urlopen(req)
- print('here')
- except IOError as e:
- if hasattr(e, 'code'):
- if e.code != 401:
- print('Its some other error!')
- print(e.code)
- else:
- print(e.headers)
- print(e.headers['www-authenticate'])
-
- print(handle.read())
-
diff --git a/languages/python/web_httplib_example_1.py b/languages/python/web_httplib_example_1.py
deleted file mode 100644
index abe86587..00000000
--- a/languages/python/web_httplib_example_1.py
+++ /dev/null
@@ -1,42 +0,0 @@
-import http.client
-
-USER_AGENT = "httplib-example-1.py"
-
-class Error:
- # Indicates an HTTP Error
- def __init__(self, url, errcode, errmsg, headers):
- self.url = url
- self.errcode = errcode
- self.headers = headers
-
- def __repr__(self):
- return (
- "" %
- (self.url, self.errcode, self.errmsg)
- )
-
-class Server:
- def __init__(self, host):
- self.host = host
- def fetch(self, path):
- http = http.client.HTTP(self.host)
-
- # Write header
- http.putheader("GET",path)
- http.putheader("User-Agent", USER_AGENT)
- http.putheader("Host", self.host)
- http.putheader("Accept", "*/*")
- http.endheaders()
-
- # get response
- errcode, errmsg, headers = http.getreply()
-
- if errcode != 200:
- raise Error(errcode, errmsg, headers)
-
- f = http.getfile()
- return f.read()
-
-if __name__ == '__main__':
- server = Server("www.pythonware.com")
- print(server.fetch("/index.htm"))
diff --git a/languages/python/web_httplib_example_2.py b/languages/python/web_httplib_example_2.py
deleted file mode 100644
index 29014680..00000000
--- a/languages/python/web_httplib_example_2.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import http.client
-import pudb
-pudb.set_trace()
-conn = http.client.HTTPConnection("www.python.org")
-conn.request("GET","/index.html")
-res = conn.getresponse()
-print(res.getheaders())
-print(res.getheader('server'))
-print(res.getheader('space','mine'))
diff --git a/languages/python/web_httplib_example_3.py b/languages/python/web_httplib_example_3.py
deleted file mode 100644
index 03712b02..00000000
--- a/languages/python/web_httplib_example_3.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import http.client
-conn = http.client.HTTPConnection("www.python.org")
-conn.request("GET","/index.html")
-res = conn.getresponse()
-print((res.getheaders()))
-print((res.getheader('server')))
-print((res.getheader('space','mine')))
diff --git a/languages/python/web_httplib_head.py b/languages/python/web_httplib_head.py
deleted file mode 100644
index 569d8e5f..00000000
--- a/languages/python/web_httplib_head.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import http.client
-conn = http.client.HTTPConnection("www.google.com")
-conn.request("HEAD","/index.html")
-res = conn.getresponse()
-for header,value in res.getheaders():
- print(header, value)
diff --git a/languages/python/web_scan_web.py b/languages/python/web_scan_web.py
deleted file mode 100644
index b20d457f..00000000
--- a/languages/python/web_scan_web.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import re
-import urllib.request, urllib.parse, urllib.error
-
-regex = re.compile(r'href="([^"]+)"')
-
-def matcher(url, max=10):
- """Print the first several URL references in the given URL"""
- data = urllib.request.urlopen(url).read()
- hits = regex.findall(data)
- for hit in hits[:max]:
- print(urllib.basejoin(url,hit))
-
-matcher("http://uthcode.sarovar.org")
diff --git a/languages/python/web_server.py b/languages/python/web_server.py
deleted file mode 100644
index c587fd34..00000000
--- a/languages/python/web_server.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import socket
-import sys
-
-def main():
- ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- port = int(sys.argv[1])
- ls.bind(('',port))
- ls.listen(1)
- (conn, addr) = ls.accept()
- while 1:
- l = input()
- conn.send(1)
-
-
-if __name__ == '__main__':
- main()
-
diff --git a/languages/python/web_simple_http_processor.py b/languages/python/web_simple_http_processor.py
deleted file mode 100644
index f0450426..00000000
--- a/languages/python/web_simple_http_processor.py
+++ /dev/null
@@ -1,56 +0,0 @@
-import sys
-import urllib.request, urllib.error, urllib.parse
-import http.cookiejar
-
-class HTTPMyDebugProcessor(urllib2.AbstractHTTPHandler):
- """Track HTTP Requests and responses with this custom handlers. Be sure to
- add it your build_opener call, or use: handler_order = 900 """
- def __init__(self, httpout = sys.stdout):
- self.httpout = httpout
- def http_request(self, request):
- if __debug__:
- host, full_url = request.get_host(), request.get_full_url()
- url_path = full_url[full_url.find(host) + len(host):]
- self.httpout.write("%s\n" % request.get_full_url())
- self.httpout.write("\n")
- self.httpout.write("%s %s\n" % (request.get_method(), url_path))
-
- for header in request.header_items():
- self.httpout.write("%s: %s\n" % header[:])
-
- self.httpout.write("\n")
-
- return request
-
- def http_response(self, request, response):
- if __debug__:
- code, msg, hdrs = response.code, response.msg, response.info()
- self.httpout.write("HTTP/1.x %s %s\n" % (code, msg))
- self.httpout.write(str(hdrs))
-
- return response
-
- https_request = http_request
- https_response = http_response
-
-# Example
-cjar = http.cookiejar.LWPCookieJar()
-opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar),HTTPMyDebugProcessor(),)
-#opener = urllib2.build_opener(HTTPMyDebugProcessor(),)
-urllib.request.install_opener(opener)
-##response = urllib2.urlopen("http://www.google.com")
-#response = urllib2.urlopen("https://www.idcourts.us/repository/start.do")
-#response = urllib2.urlopen("https://www.idcourts.us/repository/searchParty.do")
-req = urllib.request.Request('http://www.microsoft.com/windows/windows-7/default.aspx')
-#req = urllib2.Request('https://www.idcourts.us/repository/start.do')
-res = opener.open(req)
-
-print(cjar)
-for c in cjar:
- cookie_str = "%s=%s" % (c.name, c.value)
-print(cookie_str)
-
-req = urllib.request.Request('http://www.microsoft.com/windows/windows-xp/default.aspx')
-#req.add_header("Cookie",cookie_str)
-opener.open(req)
-print(cjar)
diff --git a/languages/python/web_urllib1.py b/languages/python/web_urllib1.py
deleted file mode 100644
index b39e9c1b..00000000
--- a/languages/python/web_urllib1.py
+++ /dev/null
@@ -1,2 +0,0 @@
-import urllib.request, urllib.parse, urllib.error
-urllib.request.urlopen('http://www.google.com')
diff --git a/languages/python/web_urllib2_1.py b/languages/python/web_urllib2_1.py
deleted file mode 100644
index 472e1a7b..00000000
--- a/languages/python/web_urllib2_1.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-o = urllib.request.urlopen('http://www.google.com')
-print(o)
-print(type(o))
diff --git a/languages/python/web_urllib2_add_data.py b/languages/python/web_urllib2_add_data.py
deleted file mode 100644
index d0433a24..00000000
--- a/languages/python/web_urllib2_add_data.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-URL = 'http://localhost/allowed.html'
-
-ah = urllib.request.HTTPDigestAuthHandler()
-ah.add_password('Realm','http://localhost/','senthil','kumaran')
-urllib.request.install_opener(urllib.request.build_opener(ah))
-r = urllib.request.Request(URL)
-r.add_data("1")
-obj = urllib.request.urlopen(r)
-print(obj.read())
-r.add_data("10")
-obj = urllib.request.urlopen(r)
-print(obj.read())
diff --git a/languages/python/web_urllib2_auth_ex1.py b/languages/python/web_urllib2_auth_ex1.py
deleted file mode 100644
index 017d3267..00000000
--- a/languages/python/web_urllib2_auth_ex1.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-authinfo = urllib.request.HTTPBasicAuthHandler()
-opener = urllib.request.build_opener(authinfo)
-urllib.request.install_opener(opener)
-f = urllib.request.urlopen('http://mail.google.com/a/spasticssocietyofkarnataka.org/#inbox')
-print(f.info())
diff --git a/languages/python/web_urllib2_basic1.py b/languages/python/web_urllib2_basic1.py
deleted file mode 100644
index 65f25b1d..00000000
--- a/languages/python/web_urllib2_basic1.py
+++ /dev/null
@@ -1,11 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-URL = 'http://localhost/basic.html'
-passwd = '550charpass50charpass50charpass50charpass50charpass0charpass'
-#passwd = 'senthil'
-ah = urllib.request.HTTPBasicAuthHandler()
-ah.add_password('Realm','http://localhost/basic.html','senthil',passwd)
-urllib.request.install_opener(urllib.request.build_opener(ah))
-r = urllib.request.Request(URL)
-obj = urllib.request.urlopen(r)
-print(obj.read())
diff --git a/languages/python/web_urllib2_basic2.py b/languages/python/web_urllib2_basic2.py
deleted file mode 100644
index 5e9746fc..00000000
--- a/languages/python/web_urllib2_basic2.py
+++ /dev/null
@@ -1,79 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-URL = 'http://localhost/basic.html'
-
-ah = urllib.request.HTTPBasicAuthHandler()
-ah.add_password('Realm','http://localhost/','username','veryverylongpassword')
-urllib.request.install_opener(urllib.request.build_opener(ah))
-r = urllib.request.Request(URL)
-obj = urllib.request.urlopen(r)
-print(obj.read())
-
-print('*********************************************************')
-import urllib.request, urllib.error, urllib.parse
-import sys
-import re
-import base64
-from urllib.parse import urlparse
-
-theurl = 'http://localhost/basic.html'
-# if you want to run this example you'll need to supply
-# a protected page with your username and password
-
-username = 'username'
-password = 'veryverylongpassword' # a very bad password
-
-req = urllib.request.Request(theurl)
-try:
- handle = urllib.request.urlopen(req)
-except IOError as e:
- # here we *want* to fail
- pass
-else:
- # If we don't fail then the page isn't protected
- print("This page isn't protected by authentication.")
- sys.exit(1)
-
-if not hasattr(e, 'code') or e.code != 401:
- # we got an error - but not a 401 error
- print("This page isn't protected by authentication.")
- print('But we failed for another reason.')
- sys.exit(1)
-
-authline = e.headers['www-authenticate']
-# this gets the www-authenticate line from the headers
-# which has the authentication scheme and realm in it
-
-
-authobj = re.compile(
- r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',
- re.IGNORECASE)
-# this regular expression is used to extract scheme and realm
-matchobj = authobj.match(authline)
-
-if not matchobj:
- # if the authline isn't matched by the regular expression
- # then something is wrong
- print('The authentication header is badly formed.')
- print(authline)
- sys.exit(1)
-
-scheme = matchobj.group(1)
-realm = matchobj.group(2)
-# here we've extracted the scheme
-# and the realm from the header
-if scheme.lower() != 'basic':
- print('This example only works with BASIC authentication.')
- sys.exit(1)
-
-base64string = base64.encodestring(
- '%s:%s' % (username, password))[:-1]
-authheader = "Basic %s" % base64string
-req.add_header("Authorization", authheader)
-try:
- handle = urllib.request.urlopen(req)
-except IOError as e:
- # here we shouldn't fail if the username/password is right
- print("It looks like the username or password is wrong.")
- sys.exit(1)
-thepage = handle.read()
diff --git a/languages/python/web_urllib2_basic3.py b/languages/python/web_urllib2_basic3.py
deleted file mode 100644
index b2bcde89..00000000
--- a/languages/python/web_urllib2_basic3.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-import base64
-
-URL = 'http://localhost/basic.html'
-passwd = '550charpass50charpass50charpass50charpass50charpass0charpass'
-#passwd = 'senthil'
-request = urllib.request.Request(URL)
-#base64.MAXBINSIZE=1000000
-base64string = base64.b64encode('%s:%s' %('senthil',passwd))[:-1]
-#base64string = base64.encodestring('%s:%s' %('senthil',passwd))[:-1]
-request.add_header('WWW-Authenticate', 'Basic realm=Realm')
-request.add_header("Authorization","Basic %s" % base64string)
-obj = urllib.request.urlopen(request)
-print(obj.read())
diff --git a/languages/python/web_urllib2_basic_digest1.py b/languages/python/web_urllib2_basic_digest1.py
deleted file mode 100644
index 9f5b8842..00000000
--- a/languages/python/web_urllib2_basic_digest1.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-basic_handler = urllib.request.HTTPBasicAuthHandler()
-basic_handler.add_password('Realm','http://localhost/','senthil','senthil')
-
-digest_handler = urllib.request.HTTPDigestAuthHandler()
-digest_handler.add_password('Realm','http://localhost/','senthil','kumaran')
-opener = urllib.request.build_opener(basic_handler, digest_handler)
-opener = urllib.request.build_opener(digest_handler, basic_handler)
-urllib.request.install_opener(opener)
-
-basic_url = r'http://localhost/basic.html'
-digest_url = r'http://localhost/allowed.html'
-
-print(urllib.request.urlopen(digest_url).read())
-print(urllib.request.urlopen(basic_url).read())
diff --git a/languages/python/web_urllib2_binary_upload.py b/languages/python/web_urllib2_binary_upload.py
deleted file mode 100644
index 10bb3fc2..00000000
--- a/languages/python/web_urllib2_binary_upload.py
+++ /dev/null
@@ -1,93 +0,0 @@
-import itertools
-import mimetools
-import mimetypes
-from io import StringIO
-import urllib.request, urllib.parse, urllib.error
-import urllib.request, urllib.error, urllib.parse
-
-class MultiPartForm(object):
- """Accumulate the data to be used when posting a form."""
-
- def __init__(self):
- self.form_fields = []
- self.files = []
- self.boundary = mimetools.choose_boundary()
- return
-
- def get_content_type(self):
- return 'multipart/form-data; boundary=%s' % self.boundary
-
- def add_field(self, name, value):
- """Add a simple field to the form data."""
- self.form_fields.append((name, value))
- return
-
- def add_file(self, fieldname, filename, fileHandle, mimetype=None):
- """Add a file to be uploaded."""
- body = fileHandle.read()
- if mimetype is None:
- mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
- self.files.append((fieldname, filename, mimetype, body))
- return
- def __str__(self):
- """Return a string representing the form data, including attached files."""
- # Build a list of lists, each containing "lines" of the
- # request. Each part is separated by a boundary string.
- # Once the list is built, return a string where each
- # line is separated by '\r\n'.
- parts = []
- part_boundary = '--' + self.boundary
-
- # Add the form fields
- parts.extend(
- [ part_boundary,
- 'Content-Disposition: form-data; name="%s"' % name,
- '',
- value,
- ]
- for name, value in self.form_fields
- )
- # Add the files to upload
- parts.extend(
- [ part_boundary,
- 'Content-Disposition: file; name="%s"; filename="%s"' % \
- (field_name, filename),
- 'Content-Type: %s' % content_type,
- '',
- body,
- ]
- for field_name, filename, content_type, body in self.files
- )
-
- # Flatten the list and add closing boundary marker,
- # then return CR+LF separated data
- flattened = list(itertools.chain(*parts))
- flattened.append('--' + self.boundary + '--')
- flattened.append('')
- return '\r\n'.join(flattened)
-
-if __name__ == '__main__':
- # Create the form with simple fields
- form = MultiPartForm()
- form.add_field('firstname', 'Doug')
- form.add_field('lastname', 'Hellmann')
-
- # Add a fake file
- form.add_file('biography', 'bio.txt',
- fileHandle=StringIO('Python developer and blogger.'))
-
- # Build the request
- request = urllib.request.Request('http://localhost:8080/')
- request.add_header('User-agent', 'PyMOTW (http://www.doughellmann.com/PyMOTW/)')
- body = str(form)
- request.add_header('Content-type', form.get_content_type())
- request.add_header('Content-length', len(body))
- request.add_data(body)
-
- print()
- print('OUTGOING DATA:')
- print(request.get_data())
-
- print()
- print('SERVER RESPONSE:')
- print(urllib.request.urlopen(request).read())
diff --git a/languages/python/web_urllib2_debug_headers.py b/languages/python/web_urllib2_debug_headers.py
deleted file mode 100644
index dce7f293..00000000
--- a/languages/python/web_urllib2_debug_headers.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import http.cookiejar
-import urllib.request, urllib.error, urllib.parse
-
-cookiejar = http.cookiejar.LWPCookieJar()
-http_handler = urllib.request.HTTPHandler(debuglevel=1)
-opener = urllib.request.build_opener(http_handler,urllib.request.HTTPCookieProcessor(cookiejar))
-urllib.request.install_opener(opener)
-#url = 'https://www.orange.sk/'
-url = 'https://www.idcourts.us/repository/start.do'
-req = urllib.request.Request(url, None)
-cookie = cookiejar[0]
-print(cookie.value)
-"""
-s = opener.open(req)
-print cookiejar
-url = 'https://www.idcourts.us/repository/partySearch.do'
-req = urllib2.Request(url, None)
-s = opener.open(req)
-print cookiejar
-url = 'https://www.idcourts.us/repository/start.do'
-req = urllib2.Request(url, None)
-s = opener.open(req)
-print cookiejar
-url = 'https://www.idcourts.us/repository/partySearch.do'
-req = urllib2.Request(url, None)
-s = opener.open(req)
-print cookiejar
-"""
diff --git a/languages/python/web_urllib2_digest.py b/languages/python/web_urllib2_digest.py
deleted file mode 100644
index 7315a71c..00000000
--- a/languages/python/web_urllib2_digest.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-URL = 'http://localhost/allowed.html'
-
-ah = urllib.request.HTTPDigestAuthHandler()
-ah.add_password('Realm','http://localhost/','senthil','kumaran')
-urllib.request.install_opener(urllib.request.build_opener(ah))
-r = urllib.request.Request(URL)
-obj = urllib.request.urlopen(r)
-print(obj.read())
diff --git a/languages/python/web_urllib2_digest2.py b/languages/python/web_urllib2_digest2.py
deleted file mode 100644
index 696f696f..00000000
--- a/languages/python/web_urllib2_digest2.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-import getpass
-
-URL = 'http://livejournal.com/users/phoe6/data/rss?auth=digest'
-
-ah = urllib.request.HTTPDigestAuthHandler()
-password = getpass.getpass()
-ah.add_password('lj','http://phoe6.livejournal.com/','phoe6',password)
-urllib.request.install_opener(urllib.request.build_opener(ah))
-r = urllib.request.Request(URL)
-obj = urllib.request.urlopen(r)
-print(obj.read())
diff --git a/languages/python/web_urllib2_headers_ex1.py b/languages/python/web_urllib2_headers_ex1.py
deleted file mode 100644
index 4e161771..00000000
--- a/languages/python/web_urllib2_headers_ex1.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-import urllib.request, urllib.parse, urllib.error
-
-url = 'http://www.someserver.com/cgi-bin/register.cgi'
-user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
-values = {'name':'Micheal Frood',
- 'location':'Northampton',
- 'language':'Python'
- }
-headers = {'User-Agent':user_agent}
-
-data = urllib.parse.urlencode(values)
-req = urllib.request.Request(url, data, headers)
-response = urllib.request.urlopen(req)
-the_page = response.read()
-print(the_page)
diff --git a/languages/python/web_urllib2_proxy_auth.py b/languages/python/web_urllib2_proxy_auth.py
deleted file mode 100644
index 019af450..00000000
--- a/languages/python/web_urllib2_proxy_auth.py
+++ /dev/null
@@ -1,11 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-proxy = urllib.request.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport',
- 'https': 'https://username:password@proxyurl:proxyport'}
- )
-auth = urllib.request.HTTPBasicAuthHandler()
-opener = urllib.request.build_opener(proxy, auth, urllib.request.HTTPHandler)
-urllib.request.install_opener(opener)
-
-conn = urllib.request.urlopen('http://python.org')
-return_str = conn.read()
diff --git a/languages/python/web_urllib2_test.py b/languages/python/web_urllib2_test.py
deleted file mode 100644
index 97a9aad0..00000000
--- a/languages/python/web_urllib2_test.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import urllib.request, urllib.error, urllib.parse
-
-
-class FixedPasswordMgr:
- def __init__(self, user, password):
- self.user = user
- self.password = password
-
- def add_password(self, realm, uri, user, passwd):
- pass
-
- def find_user_password(self, realm, authuri):
- print('auth: ' + authuri + ' ' + self.user)
- return self.user, self.password
-
-
-authhandler = urllib.request.HTTPDigestAuthHandler(FixedPasswordMgr('phoe6', 'xxxxx'))
-
-opener = urllib.request.build_opener(authhandler)
-urllib.request.install_opener(opener)
-
-for user in ['shortcipher', 'numberland', 'adrian2084', 'rocketjon', 'si1entdave', 'nightshade37']:
- url = 'http://' + user + '.livejournal.com/data/atom?auth=digest'
- pagehandle = urllib.request.urlopen(url)
- print('ok ' + user)
diff --git a/pyproject.toml b/pyproject.toml
deleted file mode 100644
index 9fb20b32..00000000
--- a/pyproject.toml
+++ /dev/null
@@ -1,14 +0,0 @@
-[tool.poetry]
-name = "learntosolveit"
-version = "0.1.0"
-description = ""
-authors = ["Senthil Kumaran "]
-readme = "README.md"
-
-[tool.poetry.dependencies]
-python = "^3.9"
-
-
-[build-system]
-requires = ["poetry-core"]
-build-backend = "poetry.core.masonry.api"
diff --git a/requirements.txt b/requirements.txt
index 32c9a15e..af80e1a8 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,7 +1,4 @@
sphinx
-pydata-sphinx-theme
-sphinx_bootstrap_theme
+sphinx-wagtail-theme
sphinx-autobuild
breathe
-piccolo_theme
-sphinx-pdj-theme
diff --git a/source/Ads.txt b/source/Ads.txt
new file mode 100644
index 00000000..fc885ab1
--- /dev/null
+++ b/source/Ads.txt
@@ -0,0 +1 @@
+google.com, pub-8197049942123554, DIRECT, f08c47fec0942fa0
\ No newline at end of file
diff --git a/source/_static/uthcode-logo-transparent.png b/source/_static/uthcode-logo-transparent.png
new file mode 100644
index 00000000..9e3c6402
Binary files /dev/null and b/source/_static/uthcode-logo-transparent.png differ
diff --git a/source/_templates/layout.html b/source/_templates/layout.html
index 5af62434..774730ce 100644
--- a/source/_templates/layout.html
+++ b/source/_templates/layout.html
@@ -1,4 +1,10 @@
{% extends "!layout.html" %}
+
+{% block extrahead %}
+
+{% endblock %}
+
{% block content %}
{{ super() }}
@@ -24,5 +30,7 @@
+
+
{%- endblock %}
diff --git a/source/conf.py b/source/conf.py
index 4b55408f..a7f2d269 100644
--- a/source/conf.py
+++ b/source/conf.py
@@ -11,49 +11,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys
-import os
from datetime import date
-# At the top.
-import sphinx_bootstrap_theme
-
-# ...
-
-# Activate the theme.
-
-import sphinx_pdj_theme
-html_theme = 'sphinx_pdj_theme'
-html_theme_path = [sphinx_pdj_theme.get_html_theme_path()]
-
-
-#html_theme = 'piccolo_theme'
-#html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
-
-#html_theme_options = {
-# "show_prev_next": True
-#}
-
-#html_theme_options = {
-# "source_url": 'https://github.com/uthcode/learntosolveit'
-#}
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.append(os.path.abspath('.'))
-
-# -- General configuration -----------------------------------------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
-# 'sphinx.ext.todo', 'sphinx.ext.coverage',
-# 'sphinx.ext.extlinks', 'sphinx.ext.pngmath',
-# 'sphinxcontrib.runcode']
-
-extensions = ['sphinx.ext.extlinks']
-
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -63,124 +22,36 @@
# The encoding of source files.
# source_encoding = 'utf-8-sig'
-# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Learn To Solve It'
copyright = f'{date.today().year} Senthil Kumaran'
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
version = '2022-01-06'
# The full version, including alpha/beta/rc tags.
release = ''
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%d %b of %y'
# List of documents that shouldn't be included in the build.
-#unused_docs = []
+unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
-# The reST default role (used for this markup: `text`) to use for all documents.
-
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'friendly'
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-# Links for edit
-
-# :c-suggest-improve:`name.c`
-# :c-better-explain:`name.rst`
-# :python-suggest-improve:`name.py`
-# :python-better-explain:`name.rst`
-
-extlinks = {
- 'c-suggest-improve': (
- 'https://github.com/uthcode/learntosolveit/'
- 'edit/master/languages/cprogs/%s',
- "Suggest a Code Improvement: "),
- 'c-better-explain': (
- 'https://github.com/uthcode/learntosolveit/'
- 'edit/master/source/cprogramming/%s',
- "Suggest a better explanation for "),
- 'python-suggest-improve': (
- "https://github.com/uthcode/learntosolveit/"
- "edit/master/languages/python/%s",
- "Suggest a Code Improvement:"),
- 'python-better-explain': (
- "https://github.com/uthcode/learntosolveit/"
- "edit/master/source/python/%s",
- "Suggest a better explanation for "),
-}
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. See the documentation for
-# a list of builtin themes.
-#sys.path.append(os.path.abspath('_themes'))
-#html_theme_path = ['_themes']
-#html_theme = 'flask'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-# html_theme_options = {'headerbg':'white','footerbg':'white'}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# " v documentation".
html_title = 'Learn To Solve It'
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'Learn To Solve It'
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-# html_logo = '_static/learntosolveit2.png'
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
+html_extra_path = ["Ads.txt"]
+
# These paths are either relative to html_static_path
# or fully qualified paths (eg. https://...)
@@ -191,36 +62,43 @@
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%d %b, %y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {'index': ['indexsidebar.html', 'searchbox.html']}
-#html_additional_pages = {'index': 'index.html', 'foo' : 'foo.html', 'bar': 'bar.html'}
-
html_sidebars = {'**': ['logo.html', 'globaltoc.html']}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
# If false, no module index is generated.
html_use_modindex = False
# If false, no index is generated.
html_use_index = False
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
# If true, links to the reST sources are added to the pages.
-html_show_sourcelink = False
+html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-html_show_sphinx = True
+html_show_sphinx = False
# Output file base name for HTML help builder.
htmlhelp_basename = 'uthcodedoc'
+
+try:
+ extensions
+except NameError:
+ extensions = []
+
+extensions.append('sphinx_wagtail_theme')
+html_theme = 'sphinx_wagtail_theme'
+
+project = ""
+# These are options specifically for the Wagtail Theme.
+html_theme_options = dict(
+ project_name ="Learn To Solve It",
+ logo = "uthcode.png",
+ logo_alt = "",
+ github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/",
+ logo_height = 59,
+ logo_url = "/",
+ logo_width = 45,
+ header_links = "Computer Science Courses|https://courses.learntosolveit.com/, Anki| https://ankiweb.net/decks, Projects|https://projects.learntosolveit.com/, Just Do Beaver|https://www.justdobeaver.com/",
+ footer_links = ",".join([
+ "Senthil Kumaran|https://senthil.learntosolveit.com/",
+ ]),
+)
\ No newline at end of file
diff --git a/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst b/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst
deleted file mode 100644
index 98451917..00000000
--- a/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-=======================================================
-Exercise 1.10 - Explicit Tabs, Backslash and Backspaces
-=======================================================
-
-Question
---------
-
-Write a Program to copy its input to its output, replacing each tab by \t,each
-backspace by \b, and each backslash by \\. This makes tabs and backspaces
-visible in an unambiguous way.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.10_TbsBlnkSpaces.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.10_TbsBlnkSpaces.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-If the program encounters a special character like ``\t`` (tab) or ``\b`` (blank) or
-``\\`` (backslash), we explicitly handle that and print a ``\`` , using
-putchar('\\') and then the literal character. For rest of the characters we
-simply putchar that.
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.10_TbsBlnkSpaces.c`
- * :c-better-explain:`Ex_1.10_TbsBlnkSpaces.rst`
-
diff --git a/source/cprogramming/Ex_1.11_test_word_count.rst b/source/cprogramming/Ex_1.11_test_word_count.rst
deleted file mode 100644
index 79eebcaf..00000000
--- a/source/cprogramming/Ex_1.11_test_word_count.rst
+++ /dev/null
@@ -1,45 +0,0 @@
-=======================================
-Exercise 1.11 - Test Word count program
-=======================================
-
-Question
-========
-
-How would you test the word count program? What kinds of input
-are most likely to uncover bugs if there are any?
-
-Program
-=======
-
-.. literalinclude:: ../../languages/cprogs/sec_1.5.4_word_counting.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/sec_1.5.4_word_counting.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-Testing the word count program involves, giving three kinds of inputs.
-
-1. Valid Inputs.
-2. Boundary Condition Inputs.
-3. Invalid Inputs.
-
-For Valid Inputs, it could be any stream of space separate text. It has valid
-space, newline and tab characters. For Boundary conditions, a file entirely
-consisting of \n, or a file entirely consisting of \t character or a empty file.
-
-For invalid Inputs, an unclosed file which does not have EOF, which is tricky to
-provide can be given to this program. A unicode character file can be given and
-see if getchar() handles it properly. We tested it and it works.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`sec_1.5.4_word_counting.c`
- * :c-better-explain:`Ex_1.11_test_word_count.rst`
diff --git a/source/cprogramming/Ex_1.12_word_per_line.rst b/source/cprogramming/Ex_1.12_word_per_line.rst
deleted file mode 100644
index 4b5a51ce..00000000
--- a/source/cprogramming/Ex_1.12_word_per_line.rst
+++ /dev/null
@@ -1,30 +0,0 @@
-=================================================
-Exercise 1.12 - Print the input one word per line
-=================================================
-
-Question
---------
-
-
-Write a program that prints its input one word per line.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.12_word_per_line.c
- :language: c
- :tab-width: 2
-
-
-Explanation
-===========
-
-In this program, we read the one character at a time and check if the character
-is a space ' ', we print newline character, '\n' thus going to next line in the
-output, otherwise we simply print the character c.
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.12_word_per_line.c`
- * :c-better-explain:`Ex_1.12_word_per_line.rst`
diff --git a/source/cprogramming/Ex_1.13.2_His_vertical.rst b/source/cprogramming/Ex_1.13.2_His_vertical.rst
deleted file mode 100644
index e8c91d05..00000000
--- a/source/cprogramming/Ex_1.13.2_His_vertical.rst
+++ /dev/null
@@ -1,104 +0,0 @@
-====================================
-Exercise 1.13.2 - Vertical Histogram
-====================================
-
-Question
---------
-
-
-Write a program to print a histogram of the lengths of words in its input. Draw
-the histogram with the bars vertical.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.13.2_His_vertical.c
- :language: c
- :tab-width: 2
-
-
-.. runcode:: ../../languages/cprogs/Ex_1.13.2_His_vertical.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The objective of this program is the print a vertical histogram.
-For e.g. if the same input as the previous program is given.
-
-Input **I love C programming**
-
-The desired output is::
-
- *
- *
- *
- *
- *
- *
- *
- * *
- * *
- * *
- * * * *
-
-Printing the vertical histogram is tricky for number of reasons.
-
-*Printing usually happens from top to botton and left to right.*
-
-We have to know this limitation when we write the output. In the program, we
-predetermine and store maximum number of words in a sentence (MAXNO 25) and
-maximum length of the word (MAXWL 25). So, if our input exceeds those, our
-above program may give incorrect output.
-
-Then we go about finding the word length of each word and store it in a WORD
-Array. The way we do this is, initialize all the word lengths to 0 first, and
-then count each word length using a while loop. Use a variable, nc to count the
-number of characters in a word and store it in **WORD[nw]** and if we find a
-space character, then we say it is the next word and start counting the length
-of the next (by resetting nc back to 0)
-
-So for the above example input, we will have.
-
-First step: WORD[0, 0, 0, 0]
-
-And then we we count the words and store their lengths.
-
-We would have got: WORD[1,4,1, 11]
-
-Next we use the WORD array above and we go about printing from left to right. We
-we start left, we can see if our left position (j) is <= WORD value in that
-position, WORD[j]. This is accomplished in the for loop `if j <= word[j]` if it
-is, then we print * otherwise we print space ''.
-
-Like in the first line above, when j == 11,. we will print ' ' for position 1,
-' ' for position 2, and ' ' for position 3 but '*' for position 4.
-
-So our output will look like::
-
- ' '' '' ''*'
- ' '' '' ''*'
- ' '' '' ''*'
- ' '' '' ''*'
-
-We will keep going for this till we get j == 4 and at that moment, our output
-will be::
-
- ' ''*''' '*'
-
-And when j hits 1 (for all one character words like *I* and *C* in the input),
-we will have hit the bottom of the histogram::
-
-
- '*''*''*''*'
-
-Combing them all, we would have drawn the horizontal histogram like above.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.13.2_His_vertical.c`
- * :c-better-explain:`Ex_1.13.2_His_vertical.rst`
-
diff --git a/source/cprogramming/Ex_1.13_His_Horizontal.rst b/source/cprogramming/Ex_1.13_His_Horizontal.rst
deleted file mode 100644
index 3ea7501f..00000000
--- a/source/cprogramming/Ex_1.13_His_Horizontal.rst
+++ /dev/null
@@ -1,47 +0,0 @@
-====================================
-Exercise 1.13 - Horizontal Histogram
-====================================
-
-Question
---------
-
-
-Write a program to print a histogram of the lengths of words in its input. It is
-easy to draw the histogram with the bars horizontal.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.13_His_Horizontal.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.13_His_Horizontal.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-We desire the histogram like the following.
-
-If the input is **I love C programming**
-
-The output should be.::
-
- *
- ****
- *
- ***********
-
-The way it is accomplished in the above program, read each character using
-getchar, if it is special character like a space, tab or newline, go to next
-line by printing `\n` otherwise print a `*` character.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.13_His_Horizontal.c`
- * :c-better-explain:`Ex_1.13_His_Horizontal.rst`
-
diff --git a/source/cprogramming/Ex_1.14_Hist_Freq.rst b/source/cprogramming/Ex_1.14_Hist_Freq.rst
deleted file mode 100644
index 1111698d..00000000
--- a/source/cprogramming/Ex_1.14_Hist_Freq.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-====================================================
-Exercise 1.14 - Histogram of Frequency of Characters
-====================================================
-
-Question
---------
-
-
-Write a program to print a histogram of the frequencies of different characters
-in its input.
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.14_Hist_Freq.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.14_Hist_Freq.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-We define a label TNOCHAR 128 for total number of printable characters in ascii
-tabel (0 to 127) and we create an array ` int character[TNOCHAR]` to hold the
-number of occurances of those characters. As we get each character from the
-input, we increment it's count in the character array.
-
-We print the histogram at the end, by looping through the characters of the
-array, printing the character and then printing `*` for number of times that
-character had occurred.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.14_Hist_Freq.c`
- * :c-better-explain:`Ex_1.14_Hist_Freq.rst`
-
diff --git a/source/cprogramming/Ex_1.15_tempconv.rst b/source/cprogramming/Ex_1.15_tempconv.rst
deleted file mode 100644
index 1483c0cb..00000000
--- a/source/cprogramming/Ex_1.15_tempconv.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-=========================================================
-Exercise 1.15 - Temperature Convertor using function call
-=========================================================
-
-Question
---------
-
-
-Rewrite the temperature conversion program of Section 1.2 to use a function for
-conversion.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.15_tempconv.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.15_tempconv.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-In this program we are going to convert a given Fahrenheit temperature to
-Celsius or Celsius temperature to Fahrenheit temperature using the formula
-C=(5/9)(F-32 ). We retain most of the program from section 1.4. In addition
-This program contains functions such as fahrtocelsius and celsiustofhar. The
-functions fahrtocelsius and celsiustofhar are used to make the program more
-dynamic by giving choices to the users for conversion between 1 - Fahrenheit to
-Celsius Conversion 2 - Celsius to Fahrenheit Converion.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.15_tempconv.c`
- * :c-better-explain:`Ex_1.15_tempconv.rst`
-
-
diff --git a/source/cprogramming/Ex_1.16_LongLine.rst b/source/cprogramming/Ex_1.16_LongLine.rst
deleted file mode 100644
index cbd4a41c..00000000
--- a/source/cprogramming/Ex_1.16_LongLine.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-=========================================================
-Exercise 1.16 - Print length of arbitrary long input line
-=========================================================
-
-Question
---------
-
-
-Revise the main routine of the longest-line program so it will correctly print
-the length of arbitrary long input lines, and as much as possible of the text.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.16_LongLine.c
- :language: c
- :tab-width: 4
-
-
-.. runcode:: ../../languages/cprogs/Ex_1.16_LongLine.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-A string in C is a character array which ends in `\0`. getline is a function in
-our program, which reads one character at a time using getchar and stores it in
-a character array called s[] and it returns the length of the array.
-
-We keep track of each line and it's length using a variable, `max`. If the
-length of the line is greater than `max`, then we copy that line into the
-`maxline` using a copy routine.
-
-At the end of the program, whichever was the longest line that was copied in
-maxline array, we just print that.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.16_LongLine.c`
- * :c-better-explain:`Ex_1.16_LongLine.rst`
-
diff --git a/source/cprogramming/Ex_1.17_lengt80.rst b/source/cprogramming/Ex_1.17_lengt80.rst
deleted file mode 100644
index d14d3ef0..00000000
--- a/source/cprogramming/Ex_1.17_lengt80.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-=========================================================
-Exercise 1.17 - Print lines that are longer than 80 chars
-=========================================================
-
-Question
---------
-
-
-Write a program to print all input lines that are longer than 80 characters.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.17_lengt80.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.17_lengt80.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-A string in C is a character array which ends in ``\0``. getline is a function in
-our program, which reads one character at a time using getchar and stores it in
-a character array called s[] and it returns the length of the array.
-
-When an array is sent as argument to the function, like ``line[MAXLINE]`` is sent
-to ``getline`` function, the value is passed by reference, which means that any
-changes the function makes will be available to the main program.
-
-``getline`` returns the length of the line and in our main program, if the length
-is greater than 80 characters we print it.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.17_lengt80.c`
- * :c-better-explain:`Ex_1.17_lengt80.rst`
diff --git a/source/cprogramming/Ex_1.18_remtrailbt.rst b/source/cprogramming/Ex_1.18_remtrailbt.rst
deleted file mode 100644
index 405fac98..00000000
--- a/source/cprogramming/Ex_1.18_remtrailbt.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-===============================================
-Exercise 1.18 - Remove trailing blanks and tabs
-===============================================
-
-Question
---------
-
-
-Write a program to remove trailing blanks and tabs from each line of input, and
-to delete entirely blank lines.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.18_remtrailbt.c
- :language: c
- :tab-width: 2
-
-
-.. runcode:: ../../languages/cprogs/Ex_1.18_remtrailbt.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-In the removetrail function, we go to the very end of the line and the trace
-back to the find the character which is not a space, tab and then replace it
-with \0. This eliminates the trailing blanks in a line. For the empty lines
-whose length is 0, we simply skip that from output and thus removing it.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.18_remtrailbt.c`
- * :c-better-explain:`Ex_1.18_remtrailbt.rst`
-
diff --git a/source/cprogramming/Ex_1.19_reversestr.rst b/source/cprogramming/Ex_1.19_reversestr.rst
deleted file mode 100644
index 338a2bf1..00000000
--- a/source/cprogramming/Ex_1.19_reversestr.rst
+++ /dev/null
@@ -1,57 +0,0 @@
-================================
-Exercise 1.19 - reverse a string
-================================
-
-Question
---------
-
-
-Write a function reverse(s) that reverses the character string s. Use it to
-write a program that reverses its input a line at a time.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.19_reversestr.c
- :language: c
- :tab-width: 2
-
-
-.. runcode:: ../../languages/cprogs/Ex_1.19_reversestr.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-A string in C is a character array which ends in `\0`. **getline** is a function
-in our program, which reads one character at a time using getchar and stores it
-in a character array called s[] and it returns the length of the array. We call
-the reverse function on our line. In the reverse function, we calculate the
-length of the line minus `\0` and `\n` if that is present. This determines the
-ultimate printable characters in the line from where we have to reverse.
-
-We have to two incides, j=0 and i the last printable character and run through
-the program of swapping those characters till `j < i`.
-This reverses the contents of our string.
-
-The crux of the program is this::
-
- j = 0;
-
- while(j < i)
- {
- temp = rline[j];
- rline[j] = rline[i];
- rline[i] = temp;
- --i;
- ++j;
- }
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.19_reversestr.c`
- * :c-better-explain:`Ex_1.19_reversestr.rst`
-
diff --git a/source/cprogramming/Ex_1.1_exp_helloworld.rst b/source/cprogramming/Ex_1.1_exp_helloworld.rst
deleted file mode 100644
index a4f9d695..00000000
--- a/source/cprogramming/Ex_1.1_exp_helloworld.rst
+++ /dev/null
@@ -1,60 +0,0 @@
-===================================
-Exercise 1.1 - testing hello, world
-===================================
-
-Question
-========
-
-Run the `hello, world` program on your system. Experiment with leaving out
-parts of the program, to see what error messages you get.
-
-.. literalinclude:: ../../languages/cprogs/sec_1.1_helloworld.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/sec_1.1_helloworld.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-1. Leaving out `#include`
-
-The program still compiles and it gives the warning stating that it is using a
-built-in function printf.
-
-::
-
- helloworld.c:5: warning: incompatible implicit declaration of built-in function ‘printf’
-
-
-2. Leaving out `int` or `void` or *both*
-
-The program compiles and runs without any warning.
-We know that spaces and indentation is not important, so we can strip them out.
-
-3. The smallest program that compiles **with warning**, but executes is this.
-
-::
-
- main(){printf("hello,world\n");}
-
-4. Any part of the string "hello,world\n" can be left out without any error,
- just the program output will be different.
-
-5. Leaving any other part the program will now result in **compilation error.**
-
-For e.g. After removing **;** in the above program, we got the compilation
-error.
-
-::
-
- error: expected `;` before the '}' token
-
-
-.. seealso::
-
- * :c-suggest-improve:`sec_1.1_helloworld.c`
- * :c-better-explain:`Ex_1.1_exp_helloworld.rst`
-
diff --git a/source/cprogramming/Ex_1.20_detab.rst b/source/cprogramming/Ex_1.20_detab.rst
deleted file mode 100644
index d79fc6b0..00000000
--- a/source/cprogramming/Ex_1.20_detab.rst
+++ /dev/null
@@ -1,81 +0,0 @@
-================================================
-Exercise 1.20 - detab, replaces tabs with spaces
-================================================
-
-Question
---------
-
-
-Write a program detab that replaces tabs in the input with the proper number of
-blanks to space to the next tab stop. Assume a fixed set of tab stops, say every
-n columns. Should n be a variable or a symbolic parameter?
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.20_detab.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.20_detab.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-We declare TABINC as 8 in #define TABINC 8 as the number of spaces which make a
-TAB.
-
-We start counting the pos from 1 for every new line and we increment pos for all
-the characters and print the character, which are not tabs. This is
-demonstrated by the else statements in our program.
-
-When we hit a tab \t character, then we need to determine how many spaces we
-need to replace the \t with.
-
-For e.g.::
-
- hello | I press a tab and reach |
- hello###| It should be substibuted with 3 #,
-
-The way 3 # is calculated by `TABINC - length of ('hello')`
-that is 8 - 5 = 3.
-
-This explains well, if hello is the starting word. The way to determine the tabs
-to spaces later in the line is by keeping track of the number of characters in
-the line (that is variable pos in our program.)
-
-For e.g
-
-::
-
- hello world is great
- hello###world###is######great
-
-
-To determine the number of tabs to spaces between **is** and **great**
-
-We track the pos till **s**, we encounter the tab position at be 19.
-
-::
-
- nb = TABINC - (( pos - 1) % TABINC);
- nb = TABINC - ((19 - 1)) % TABINC);
- nb = TABINC - (18 % TABINC);
- nb = TABINC - (18 % 8);
- nb = TABINC - 2;
- nb = 8 - 2;
- nb = 6
-
-Once we determine the nb, we simply print # character to denote a visible space
-and increment the position each character.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.20_detab.c`
- * :c-better-explain:`Ex_1.20_detab.rst`
-
diff --git a/source/cprogramming/Ex_1.21_entab.rst b/source/cprogramming/Ex_1.21_entab.rst
deleted file mode 100644
index 6343624f..00000000
--- a/source/cprogramming/Ex_1.21_entab.rst
+++ /dev/null
@@ -1,55 +0,0 @@
-================================================
-Exercise 1.21 - entab, replaces spaces with tabs
-================================================
-
-Question
---------
-
-Write a program entab that replaces strings of blanks by the minimum number of
-tabs and blanks to achieve the same spacing. Use the same tab stops as for
-detab. When either a tab or a single blank would suffice to reach a tab stop,
-which should be given preference?
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.21_entab.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.21_entab.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-1. We declare TABINC as 8 in `#define TABINC 8` as the number of spaces which
-make a TAB.
-
-2. We declare two variables **nb** for number of spaces and **nt** for number of
-tabs.
-
-3. We get the current character by calling getchar() and storing it in variable
-c and keep track of the position.
-
-4. As soon as a space character is found, we increment the number of spaces or
-number of tabs. We increment the spaces by pos, if the space is not divisible by
-TABINC. If the space occurance is divisible by TABINC, we increment the number
-of tabs. This step collects the minimum number of tabs and blanks.
-
-5. In the else part, when non space is found, we first print the all remaining
-tabs, then remaining spaces, then print the character. And We reset the position
-accordingly. If it is a newline, we reset the pos, if it is a tab character, we
-reset it to previous tab character - 1. This step replaces the spaces with
-minimum tabs and spaces.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.21_entab.c`
- * :c-better-explain:`Ex_1.21_entab.rst`
-
diff --git a/source/cprogramming/Ex_1.22_fold.rst b/source/cprogramming/Ex_1.22_fold.rst
deleted file mode 100644
index 6d5f8b6a..00000000
--- a/source/cprogramming/Ex_1.22_fold.rst
+++ /dev/null
@@ -1,73 +0,0 @@
-===============================
-Exercise 1.22 - fold long lines
-===============================
-
-Question
---------
-
-
-Write a program to ``fold`` long input lines into two or more shorter lines
-after the last non-blank character that occurs before the n-th column of input.
-Make sure your program does something ntelligent with very long lines, and if
-there are no blanks or tabs before the specified column.
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.22_fold.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.22_fold.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-1. We determine the column to fold in the MAXCOL variable.
-
-2. Since tab character can occur too and folding a tab character means folding
-it in mid-way, we also replace the tabs in the line with spaces.
-
-3. Every character of the file is filled into a ``line[MAXCOL]`` array and that
-line is acted upon by the program.
-
-4. We start at ``pos=0`` and take each character and place it in ``line[pos]`` and
-then we analyze the character to act upon the condition.
-
-6. If the character is ``\t``. We go and expand the tab character in the
-``line[pos]`` and get newposition. So, when line[\t] at pos = 0, it will be now
-``line[' ', ' ', ' ',' ',' ',' ',' ',' '] and pos = 8``
-
-7. If character is ``\n`` then we print the entire line contents reset the ``pos``
-back to 0.
-
-8. *otherwise*, we get into our program.
-
-When we are folding, we should not be folding in between the word. So we have to
-track the previous space occuring in a line. The logic follows.
-
-1. When our position is greater than MAXCOL, then we look for previous blank
-space by using ``getblank`` and we get the position of that blank.
-
-2. We then ``fold``, getblank will return the pos which is not greater than
-MAXCOL. So, the print the characters we have in line and then print newline.
-
-3. We determine the new position based the return value of getblank. If the
-return value of getblank was greater than MAXCOL, then our new position is 0,
-which is a newline. We will replace the contents of line starting from 0, mark
-this as ``i``, and place the folded contents by the last ``for loop`` in the program
-and after placing the folded contents we return the new value of ``i``, which is
-our updated ``pos``.
-
-With our new position we continue with the rest of the program.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.22_fold.c`
- * :c-better-explain:`Ex_1.22_fold.rst`
-
diff --git a/source/cprogramming/Ex_1.23_remcomments.rst b/source/cprogramming/Ex_1.23_remcomments.rst
deleted file mode 100644
index 5e21d3c1..00000000
--- a/source/cprogramming/Ex_1.23_remcomments.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-================================================
-Exercise 1.23 - Remove comments from a C program
-================================================
-
-Question
---------
-
-
-Write a program to remove all comments from a C program. Don't forget to handle
-quoted strings and character constants properly. C comments don't nest.
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.23_remcomments.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.23_remcomments.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-If two subsequent characters start with `/` and `*`, we say we are in-comment,
-If we find two characters which are `/` and `/`, we will print the first
-character and start treating the second `/` as the possible start of comment. In
-the same manner, if we encouter a single quote or a double quote character, then
-we understand we are inside a quoted string, so we putchar everything before we
-find the matching character again. Within a quoted string, if we encouter a
-special character, then we try to read them literally as two characters and
-print them.
-
-If / is followed by any other character, we simply print them.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.23_remcomments.c`
- * :c-better-explain:`Ex_1.23_remcomments.rst`
diff --git a/source/cprogramming/Ex_1.24_synerrors.rst b/source/cprogramming/Ex_1.24_synerrors.rst
deleted file mode 100644
index f7005c77..00000000
--- a/source/cprogramming/Ex_1.24_synerrors.rst
+++ /dev/null
@@ -1,52 +0,0 @@
-==============================================================
-Exercise 1.24 - Check rudimentary Syntax Errors in a C Program
-==============================================================
-
-Question
---------
-
-
-Write a program to check a C program for rudimentary syntax errors like
-unmatched parentheses,brackets and braces. Don't forget about quotes, both
-single and double, escape sequences, and comments. (This program is hard if you
-do it in full generality.)
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.24_synerrors.c
- :language: c
- :tab-width: 4
-
-
-.. runcode:: ../../languages/cprogs/Ex_1.24_synerrors.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-We divide the program up into 3 parts. The text of the program when it is in-
-comment, in-quote and rest of the program text. We don't to have worry about the
-part when we are in-comment or in-quote because we can find non-matching
-brankets or braces in those parts. It is only the rest that we care about.
-
-When a two sequence characters starts with ``/*`` we enter in-comment block and
-continue till we end up with ``*/``
-
-When a single quote ``'`` or a double quote ``"`` character is found, we do the same
-and continue till we find it's match.
-
-For the rest of the program, when we first match a brace, bracket or
-parenthesis, we mark it as -1 and when we find it's match, we negate it back to
-0. If these values end up being anythign other than 0, we say that we found a
-mismatch.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.24_synerrors.c`
- * :c-better-explain:`Ex_1.24_synerrors.rst`
diff --git a/source/cprogramming/Ex_1.2_exp_printf_c.rst b/source/cprogramming/Ex_1.2_exp_printf_c.rst
deleted file mode 100644
index 1320c887..00000000
--- a/source/cprogramming/Ex_1.2_exp_printf_c.rst
+++ /dev/null
@@ -1,54 +0,0 @@
-=====================================
-Exercise 1.2 - Experiment with printf
-=====================================
-
-Question
-========
-
-Experiment to find out what happens when prints's argument string contains \c,
-where c is some character not listed above.
-
-Solution
-========
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.2_exp_printf_c.c
- :language: c
- :tab-width: 4
-
-
-Explanation
-===========
-
-For the invalid characters, the compiler will output a warning statement.
-
-::
-
- warning: unknown escape sequence \d
-
-The other interesting warning statements are mentioned beside in the program.
-The rest of the control characters took effect and this is the output from the
-program.
-
-::
-
- a:b:c:cd:de:f:g:gh:hi:ij:jk:kl:lm:mn:
- o:op:pq:qr:
- s:st: u:☃v:w:wx:
- y:yz:zA:AB:BC:CD:DE:F:FG:GH:HI:IJ:JK:KL:LM:MN:NO:OP:PQ:QR:RS:ST:RU:☃V:VW:WX:XY:YZ:Z0:1:2:3:4:5:6:7:8:89:9~:~`:`!:!@:@#:#$:$%^:^&:&*:*(:():)_:_-:-+:+{:{[:[}:}]:]|:|:\a::::;:;":"':'<:<,:,>:>.:.?:?/:/
-
-
-References
-==========
-
-* `Discussion on U Codepoint`_
-* `Valid escape characters`_
-
-.. _Discussion on U Codepoint: http://stackoverflow.com/questions/21241224/unicode-codepoint-of-the-format-unnnnnnnn/
-.. _Valid escape characters: http://en.cppreference.com/w/cpp/language/escape
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.2_exp_printf_c.c`
- * :c-better-explain:`Ex_1.2_exp_printf_c.rst`
-
diff --git a/source/cprogramming/Ex_1.3_fahr2celheading.rst b/source/cprogramming/Ex_1.3_fahr2celheading.rst
deleted file mode 100644
index daa22809..00000000
--- a/source/cprogramming/Ex_1.3_fahr2celheading.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-====================================
-Exercise 1.3 - Temperature Convertor
-====================================
-
-Question
---------
-
-
-Modify the temperature conversion program to print a heading above the table.
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.3_fahr2celheading.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.3_fahr2celheading.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-In this program we are going to convert a given Fahrenheit temperature to
-Celsius temperature using the formula C=(5/9)(F-32) To do this we declare some
-variables in the beginning of the program so that they can be used in the later
-stages of the program. The variables in this program are: lower,upper,step,
-celsius,fahr. The variable lower is assigned the value 0 similarly upper to 300,
-step to 20, and fahr to lower. So when the program enters the while loop it
-checks whether fahr <= upper is true, if it is true then it assigns the variable
-celsius 5 * (fahr - 32) / 9 and then it prints output.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.3_fahr2celheading.c`
- * :c-better-explain:`Ex_1.3_fahr2celheading.rst`
-
diff --git a/source/cprogramming/Ex_1.4_cel2fahr.rst b/source/cprogramming/Ex_1.4_cel2fahr.rst
deleted file mode 100644
index 81bbb157..00000000
--- a/source/cprogramming/Ex_1.4_cel2fahr.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-====================================
-Exercise 1.4 - Temperature Convertor
-====================================
-
-Question
---------
-
-
-Write a program to print the corresponding Celsius to Fahrenheit table.
-
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.4_cel2fahr.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.4_cel2fahr.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-In the previous exercise we converted Fahrenheit temperature to Celsius
-temperature. In this program we are going to convert a given Celsius temperature
-to Fahrenheit temperature using the formula C=(5/9)(F-32) To do this we declare
-some variables in the beginning of the program so that they can be used in the
-later stages of the program. The variables in this program are:
-lower,upper,step, celsius,fahr. The variable lower is assigned the value 0
-similarly upper to 300, step to 20, and Celsius to lower. So when the program
-enters the while loop it checks whether celsius <= upper is true if it is true
-then it assigns the variable fahr (9.0/5.0) * celsius + 32.0 and then it prints
-out put.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.4_cel2fahr.c`
- * :c-better-explain:`Ex_1.4_cel2fahr.rst`
-
diff --git a/source/cprogramming/Ex_1.5_reverse.rst b/source/cprogramming/Ex_1.5_reverse.rst
deleted file mode 100644
index d9bf55ee..00000000
--- a/source/cprogramming/Ex_1.5_reverse.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-===============================================
-Exercise 1.5 - Temperature Convertor in Reverse
-===============================================
-
-Question
---------
-
-
-Modify the temperature conversion program to print the table in reverse order,
-that is, from 300 degrees to 0.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.5_reverse.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.5_reverse.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-In the previous exercise we converted Fahrenheit temperature to Celsius
-temperature. In this program we are going to print the table in reverse order,
-that is, from 300 degrees to 0. To do this we declare some variables in the
-beginning of the program so that they can be used in the later stages of the
-program. The variables in this program are: lower,upper,step, celsius,fahr. The
-variable lower is assigned the value 0 similarly upper to 300, step to 20, and
-Celsius to lower. So when the program enters the while loop it checks whether
-celsius <= upper is true if it is true then it assigns the variable fahr
-(9.0/5.0) * celsius + 32.0 and then it prints out put.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.5_reverse.c`
- * :c-better-explain:`Ex_1.5_reverse.rst`
-
-
diff --git a/source/cprogramming/Ex_1.6_verifyeof.rst b/source/cprogramming/Ex_1.6_verifyeof.rst
deleted file mode 100644
index 3630e718..00000000
--- a/source/cprogramming/Ex_1.6_verifyeof.rst
+++ /dev/null
@@ -1,58 +0,0 @@
-======================================
-Exercise 1.6 - Verify the value of EOF
-======================================
-
-Question
---------
-
-Verify the expression `getchar() !=EOF` is 0 or 1.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.6_verifyeof.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.6_verifyeof.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-1. This program is similar to the previous one Ex 1.5, wherein after it gets the
-input, it prints the value of the expression getchar() != EOF.
-
-2. For a file with this contents
-
-::
-
- $cat afile
- contents
-
-
-3. We compile and run the program.
-
-::
-
- $gcc Ex1.6_verifyeof.c -o eof
- $ ./eof < afile
- 1 c1 o1 n1 t1 e1 n1 t1 s1
-
- 0
-
-4. We see that when char is not EOF, it is printing 1 and when it is EOF, 0 is
-printed.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.6_verifyeof.c`
- * :c-better-explain:`Ex_1.6_verifyeof.rst`
-
-
-
-
-
diff --git a/source/cprogramming/Ex_1.7_eofval.rst b/source/cprogramming/Ex_1.7_eofval.rst
deleted file mode 100644
index 6e2c9a01..00000000
--- a/source/cprogramming/Ex_1.7_eofval.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-===========================
-Exercise 1.7 - Value of EOF
-===========================
-
-Question
---------
-
-Write a Program to print the value of EOF.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.7_eofval.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.7_eofval.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-1. Since EOF is an integer, we can print it with %d format in the printf. 2. EOF
-value is printed as -1.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.7_eofval.c`
- * :c-better-explain:`Ex_1.7_eofval.rst`
-
diff --git a/source/cprogramming/Ex_1.8_count_blanks_etc.rst b/source/cprogramming/Ex_1.8_count_blanks_etc.rst
deleted file mode 100644
index 86c09702..00000000
--- a/source/cprogramming/Ex_1.8_count_blanks_etc.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-==============================================
-Exercise 1.8 - Count blanks, tabs and newlines
-==============================================
-
-Question
---------
-
-Write a program to count blanks, tabs, and newlines.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.8_count_blanks_etc.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_1.8_count_blanks_etc.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-In this program we are going to count the number of Blanks, tabs and new lines
-present in the input. To do this the program, while reading the characters
-checks for the condition c = getchar !=EOF which means if the character is not
-end of file continue counting Blanks tabs and newlines. Example input:
-
-I like programming
-In C
-And the out put shall be:
-Blanks: 4
-Tabs: 0
-Newlines: 1
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.8_count_blanks_etc.c`
- * :c-better-explain:`Ex_1.8_count_blanks_etc.rst`
-
diff --git a/source/cprogramming/Ex_1.9_SinBlank.rst b/source/cprogramming/Ex_1.9_SinBlank.rst
deleted file mode 100644
index e256efbf..00000000
--- a/source/cprogramming/Ex_1.9_SinBlank.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-===========================================================
-Exercise 1.9 - Replace Continous blanks with a single blank
-===========================================================
-
-Question
---------
-
-
-Write a program to copy its input to its output, replacing each string of one or
-more blanks by a single blank.
-
-Solution
---------
-
-.. literalinclude:: ../../languages/cprogs/Ex_1.9_SinBlank.c
- :language: c
- :tab-width: 2
-
-.. runcode:: ../../languages/cprogs/Ex_1.9_SinBlank.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The essence of this program is, while reading the characters, if the last
-character that we encoutered is a blank, then we skip printing it.
-
-::
-
- if(lastc!=' ')
- putchar(c);
-
-This means that if the last character is not a blank, *only* then print it. We
-store the last character in the lastc variable in the line `lastc = c`. For rest
-of the characters we simplying print it by `putchar (c)`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_1.9_SinBlank.c`
- * :c-better-explain:`Ex_1.9_SinBlank.rst`
-
diff --git a/source/cprogramming/Ex_2.10_lowercondit.rst b/source/cprogramming/Ex_2.10_lowercondit.rst
deleted file mode 100644
index 7e51e4d7..00000000
--- a/source/cprogramming/Ex_2.10_lowercondit.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-================================================
-Exercise 2.10 - upper case letters to lower case
-================================================
-
-Question
-========
-
-Rewrite the function lower, which converts upper case letters to lower case,
-with a conditional expression instead of if-else.
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.10_lowercondit.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.10_lowercondit.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-In this program we are going to convert upper case letters to lower case. We
-declare a function called lower in the beginning of the program. When the
-program enters the while loop it each character it gets to lower::
-
- while((c=getchar())!=EOF)
- {
- putchar(lower(c));
- }
-
-The lower function checks for all the uppercase characters and prints everything
-in the lowercase. It does this by a conditional statement, where if a upper case
-character is found, it subtracts 'A' to get relative index, adds it to 'a' to
-return corresponding smaller case character, if a lower case character is found,
-it is simply returned::
-
- return c>='A' && c<='Z'? c+'a'-'A':c;
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.10_lowercondit.c`
- * :c-better-explain:`Ex_2.10_lowercondit.rst`
diff --git a/source/cprogramming/Ex_2.1_cal_limits.rst b/source/cprogramming/Ex_2.1_cal_limits.rst
deleted file mode 100644
index b21623dc..00000000
--- a/source/cprogramming/Ex_2.1_cal_limits.rst
+++ /dev/null
@@ -1,135 +0,0 @@
-===============================
-Exercise 2.1 - Count the Ranges
-===============================
-
-Question
-========
-
-Write a program to determine the ranges of char, short, int, and long variables,
-both signed and unsigned, by printing appropriate values from standard headers
-and by direct computation. Harder if you compute them: determine the ranges of
-the various floating-point types.
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.1_cal_limits.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.1_cal_limits.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-The execution of the above program will give::
-
- Minimum Signed Char -128
- Maximum Signed Char 127
- Minimum Signed Short -32768
- Maximum Signed Short 32767
- Minimum Signed Int -2147483648
- Maximum Signed Int 2147483647
- Minimum Signed Long -2147483648
- Maximum signed Long 2147483647
- Maximum Unsigned Char 255
- Maximum Unsigned Short 65535
- Maximum Unsigned Int 4294967295
- Maximum Unsigned Long 4294967295
-
-
-In order explain how we calculate the maximum values, we will have to do some
-bit arthimetic. Let's start by calculating the maximum unsigned char.
-
-Sign bit is usually the left most bit of the type. To make it unsigned, we
-remove the sign bit and store 0 in it's place.
-
-To represent (unsigned char) 0 = **0000 0000**
-To represent it's complement, (unsigned char) ~0 = **1111 1111**
-
-Right Shift 1 will shift that entire sequence to the right and insert 0 from the
-left side, so it will give 0111 1111
-
-Converting 0111 1111 to integer will be::
-
- 0 * 2^7 + 1 * 2^ 6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 *2^2 + 1 * 2^1 + 1 * 2^0
- = 0 * 0 + 1 * 64 + 1 * 32 + 1 * 16 + 1 * 8 + 1 * 4 + 1 * 2 + 1 * 1
- = 0 + 64 + 32 + 16 + 8 + 4 + 2 + 1
- = 127
-
-That is the maximum signed char value. To get the minimum signed char value, we
-look for the number in the other end of the number line.
-
-That is got by, multiplying it by -1 and going one number further to the left in
-the number line::
-
- = - 127 -1
- = -128
-
-So our range is displayed like this::
-
- -128..-2..-1..0 1 2 3 4... 127
-
-Maximum signed short
---------------------
-
-To get the maximum signed short number, we start with unsigned short type again
-and repeat the same operations like we did above.
-
-(short)((unsigned short)~0 >> 1)
-
-In our compiler, a short is 2 bytes
-
-(unsigned short) 0 means **0000 0000 0000 0000**
-(unsigned short) ~0 means **1111 1111 1111 1111**
-
-Logical right shift, is we are eliminating the sign bit, which is the left most
-bit in the sequence.
-
-(unsigned short)~0 >> 1)
-
-Take this portion ``1111 1111 1111 111`` 1 and place it as **1111 1111 1111 111**
-And then add 0 to the left **0** 1111 1111 1111 111
-Rearranging we get **0111 1111 1111 1111**
-
-What is value of 0111 1111 1111 1111 ?
-
-Similar to above::
-
- = 0 * 2^15 + 1 * 2^14 + 1 * 2^13 + 1 * 2^12
- + 1 * 2^11 + 1* 2^10 + 1 * 2^9 + 1 * 2^8
- + 1*2^7 + 1 * 2^6 + 1*2^5 + 1*2^4
- + 1* 2^3 + 1*2^2 + 1* 2^1 +1*2^0
-
- = 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2
- = + 1 32767
-
-So, our maximum unsigned short is 32767
-
-Mininum unsigned short will be the negative of that number going one step
-further, i.e::
-
- = -32767 - 1 = -32768
-
-Similarily, we can calculate for int and long types.
-
-For unsigned types, we do not do the shifting (to remove the sign) but simply
-print the value of all 1s of the type
-
-(unsigned char)~0;
-
-can be represented as (unsigned char) ~0 = 1111 1111
-
-::
-
- = 1 * 2^7 + 1 * 2^ 6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 *2^2 + 1 * 2^1 + 1 * 2^0
- = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
- = 255
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.1_cal_limits.c`
- * :c-better-explain:`Ex_2.1_cal_limits.rst`
diff --git a/source/cprogramming/Ex_2.2_getline_without_and_or.rst b/source/cprogramming/Ex_2.2_getline_without_and_or.rst
deleted file mode 100644
index d70ba6e3..00000000
--- a/source/cprogramming/Ex_2.2_getline_without_and_or.rst
+++ /dev/null
@@ -1,60 +0,0 @@
-=======================================================
-Exercise 2.2 - Write getline without && and || operator
-=======================================================
-
-Question
-========
-
-For example, here is a loop from the input function getline that we
-wrote in Chapter 1::
-
- for (i=0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
- s[i] = c;
-
-
-Write a loop equivalent to the for loop above without using && or ||.
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.2_getline_without_and_or.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.2_getline_without_and_or.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-We use mgetline instead of getline, so that our compiler does not get confused
-with the builtin getline function.
-
-The crux of the program is this.
-
-::
-
- for(i=0; i < lim - 1 ;++i) {
- c = getchar();
- if (c == EOF)
- break;
- if (c == '\n')
- break;
- s[i] = c;
- }
-
-
-Here we removed `c = getchar()` from the loop condition testing and we **enter**
-the loop and then check for conditions like EOF and \n. If we encounter those
-undesirable condition, we simply break out of the for loop.
-
-This is equivalent to the for loop above in the question which uses && condition
-to check.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.2_getline_without_and_or.c`
- * :c-better-explain:`Ex_2.2_getline_without_and_or.rst`
-
diff --git a/source/cprogramming/Ex_2.3_htoi.rst b/source/cprogramming/Ex_2.3_htoi.rst
deleted file mode 100644
index 41a68eea..00000000
--- a/source/cprogramming/Ex_2.3_htoi.rst
+++ /dev/null
@@ -1,98 +0,0 @@
-==========================================================
-Exercise 2.3 - Converting Hexadecimal Digits Into Integers
-==========================================================
-
-Question
-========
-
-Write a function htoi(s), which converts a string of hexadecimal digits
-(including an optional 0x or 0X) into its equivalent integer value. The
-allowable digits are 0 through 9, a through f,and A through F.
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.3_htoi.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.3_htoi.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-In this program we are going to convert a string of hexadecimal digits into
-integer value. If give input as `F` then the output should be 15. This is done
-by the htoi function::
-
- int htoi(char s[])
- {
- int hexdigit,i,inhex,n;
- i = 0;
- if( s[i] == '0')
- {
- ++i;
- if(s[i] == 'x' || s[i] == 'X')
- ++i;
- }
-
- n = 0;
- inhex = YES;
-
- for(;inhex==YES;++i)
- {
- if(s[i] >='0' && s[i] <='9')
- hexdigit= s[i] - '0';
- else if(s[i] >='a' && s[i] <='f')
- hexdigit= s[i] -'a' + 10;
- else if(s[i] >='A' && s[i] <='F')
- hexdigit= s[i] -'A' + 10;
- else
- inhex = NO;
-
- if(inhex == YES)
- n = 16 * n + hexdigit;
- }
- return n;
- }
-
-In the above fragment of the program we declare some variables such as hexdigit
-for storing each digit in hexadecimal ,i as a counter,inhex as flag to see if we
-are still looking a hexadecimal and finally n where we store our converted
-hexadecimal number.
-
-First we strip off any characters which look like `0x` or `0X` and then we enter
-to convert rest of the characters. Then we start the conversion process, we set
-the flag index to YES and n to 0.
-
-Then in the for loop as long as index is YES, then we check each character 0 to
-9, a to f or A to F. If we find 0 to 9, we store the value char - `0`, if we
-find a character between a to f, we store char - `a` + 10, becase hexadecimal
-'a' is decimal 10 and similar for character range capital A to F.
-
-Then we take each hex digit and for it's position or previous value stored in n,
-we mutiply by 16 and add hexdigit.
-
- if(inhex == YES)
- n = 16 * n + hexdigit;
-
-For example to convert **0XAF**.
-
-1. We strip off 0X.
-2. For A, we get the value hexdigit = 10
-3. n = 16 * 0 + 10
- = 10
-4. We gather F, we store hexdigit = 'F' - 'A' + 10;
- = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A)
- = 15
-5. n = 16 * n + hexdigit
- = 16 * 10 + 15
- = 160 + 15
- = 175
-
-**175**
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.3_htoi.c`
- * :c-better-explain:`Ex_2.3_htoi.rst`
diff --git a/source/cprogramming/Ex_2.4_squeezess.rst b/source/cprogramming/Ex_2.4_squeezess.rst
deleted file mode 100644
index 57a29f2b..00000000
--- a/source/cprogramming/Ex_2.4_squeezess.rst
+++ /dev/null
@@ -1,52 +0,0 @@
-============================================================
-Exercise 2.4 - Compare S1, S2 To Delete Same Character in S1
-============================================================
-
-Question
-========
-
-Write an alternative version of squeeze(s1,s2) that deletes each character in s1
-that matches any character in the string s2.
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.4_squeezess.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.4_squeezess.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Let's take the two inputs strings as:
-
- s1: HelloWorld
-
- s2: ol
-
-Our desired output is::
-
- HeWrd
-
-This has removed the characters `o` and `l` from the first string. The way
-squeeze works is, it take each character from the first string and if there is
-no match found, stores it with a new index `k`. If there is a match found in
-**s2**, it simply skips it. The way it skips is realized by the following::
-
- for(j=0; (s1[i]!=s2[j]) && s2[j]!='\0' ;++j)
- ;
- if(s2[j]=='\0')
- s1[k++] = s1[i];
-
-When the match is found **s1[i] == s2[j]** so our first for loop will **end**.
-The second **if condtion** will fail too as s2 is not iterated till the end, so
-we do not place the character in **s1[k++]** and we have successfully skipped
-it.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.4_squeezess.c`
- * :c-better-explain:`Ex_2.4_squeezess.rst`
diff --git a/source/cprogramming/Ex_2.5_any.rst b/source/cprogramming/Ex_2.5_any.rst
deleted file mode 100644
index c3668e48..00000000
--- a/source/cprogramming/Ex_2.5_any.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-======================================================================
-Exercise 2.5 - return the first location in the string s1 comparing s2
-======================================================================
-
-Question
-========
-
-Write the function any(s1,s2), which returns the first location in a string s1
-where any character from the string s2 occurs, or -1 if s1 contains no
-characters from s2. (The standard library function strpbrk does the same job but
-returns a pointer to the location.)
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.5_any.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.5_any.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-The important part of the program is the function `any` which takes two strings
-`s1` and `s2` and tries to find if any character in `s2` matches `s1`. We set a
-**flag**, `check_next_char` which is toggled to **0** if we find the match,
-otherwise we have it as 1.
-
-The first for loop iterates through all the characters in s1 while the condition
-`check_next_char` is 1. In the second for loop, if we find that a char in s2
-matches s1, that is `s2[j] == s1[i]` and s2 has not reached EOL, then we set
-check_next_char to 0. That is we found a match at **i** and we return that.
-
-If we dont find a match in s2, we increment i and take the next character from
-s1. If dont find a match at all, then we return -1.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.5_any.c`
- * :c-better-explain:`Ex_2.5_any.rst`
-
diff --git a/source/cprogramming/Ex_2.6_setbits.rst b/source/cprogramming/Ex_2.6_setbits.rst
deleted file mode 100644
index bb7e0e16..00000000
--- a/source/cprogramming/Ex_2.6_setbits.rst
+++ /dev/null
@@ -1,160 +0,0 @@
-===========================================
-Exercise 2.6 - Setting bits at a position n
-===========================================
-
-Question
-========
-
-Write a function setbits(x,p,n,y) that returns x with the n bits that begin at
-position p set to the rightmost n bits of y, leaving the other bits unchanged.
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.6_setbits.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.6_setbits.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The important piece of the program is this::
-
- (x & ~(~(~0 << n) << (p+1-n))) | ( y & (~(~0<> n;
- x = x | rbit;
-
- For the same example.
-
-::
-
- n is between 0 - wordlength()
-
- condition 1.when (n == 0) or (n == wordlength())
-
- rightrot(x, 0) == x
-
- condition 2. when (n > 0) and (n < wordlength()) like n = 3
-
- x = 0001 1001
- the right n bits will be 001.
- the right rightrot(x,n)result should be 0010 0011
-
- x << (wordlength() - n) = 0001 1001 << (8 - 3)
- = 0001 1001 << 5
- = 0010 0000
-
-So we have got the right most n bits set.Now we right x by 1 and OR the rbit with x.
-
-::
-
- x >> n = 0001 1001 >> 3
- = 0000 0011
-
- x | rbit = 0000 0011 | 0010 0000
- = 0010 0011
-
-Which is our expected result.
-
-::
-
- condition 3. when (n > wordlength()) like n = 12
-
-The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then see "n" as condition 2.
-The result should be correct too!
-
-::
- condition 4. when n < 0 (which is not Often use)
-
-The result will mirror the function,the rightrot(x,n) function will move the left most n(n > 0)bits to the right
-side ,the function should called leftrot(x,n).
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.8_rightrot.c`
- * :c-better-explain:`Ex_2.8_rightrot.rst`
diff --git a/source/cprogramming/Ex_2.9_bitcount2s.rst b/source/cprogramming/Ex_2.9_bitcount2s.rst
deleted file mode 100644
index b73a9079..00000000
--- a/source/cprogramming/Ex_2.9_bitcount2s.rst
+++ /dev/null
@@ -1,155 +0,0 @@
-=============================================
-Exercise 2.9 - two's complement number system
-=============================================
-
-Question
-========
-
-In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in
-x. Explain why. Use this observation to write a faster version of bitcount.
-
-.. literalinclude:: ../../languages/cprogs/Ex_2.9_bitcount2s.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_2.9_bitcount2s.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-**ones** complement is a system used in some computers to represent negative
-numbers. To negate a number, each bit of the number is inverted (zeros are
-replaced with ones and vice versa).
-
-::
-
- ...
- 000...00011 = +3
- 000...00010 = +2
- 000...00001 = +1
- 000...00000 = +0
- 111...11111 = -0
- 111...11110 = -1
- 111...11101 = -2
- 111...11100 = -3
- ...
-
-This has the consequence that there are two reperesentations for zero, either
-all zeros or all ones.
-
-In **twos complement** each bit of the number is inverted (zeros are replaced
-with ones and vice versa), as for ones complement, but then one (000...0001) is
-added (ignoring overflow). This avoids the two representations for zero found in
-ones complement by using all ones to represent -1
-
-::
-
- ...
- 000...00011 = +3
- 000...00010 = +2
- 000...00001 = +1
- 000...00000 = 0
- 111...11111 = -1
- 111...11110 = -2
- 111...11101 = -3
- ...
-
-This representation simplifies the logic required for addition and subtraction,
-at the expense of a little extra complexity for negation.
-
-For e.g
-
-We want to calculate -4 + 5 = 1
-
-In order to represent, -4, we can use two's complement.
-
-
-::
-
- 4 = 0000 0100
- 1's complement of 4 = 1111 1011
- 2's complement of 4 = 1111 1100
-
- 5 = 0000 0101
-
- -4 + 5 = 1111 1100
- + 0000 0101
- -----------
- 0000 0001
-
- with 1 overflow which is ignored.
-
- So the answer is 0000 0001 = 1 that we expected.
-
-
-The question asks us to explain why *x &= (x-1)* deletes the right most bit.
-
-::
-
- x &= (x-1) can be written as x = x & (x - 1)
-
- x - 1 is any binary number subtrated by 0000 0001
- x - 1 has the property of changing the right most 1 to 0.
- and right most 0 to 1 by using borrows.
-
-
-To get concrete::
-
- x = 1 = 0000 0001
-
- x-1 = 0000 0001
- - 0000 0001
- ------------
- 0000 0000
- ------------
-
- x = 2 = 0000 0010
-
- x - 1 = 0000 0010
- -0000 0001
- ----------
- 0000 0001
- ----------
-
- x = 5 = 0000 0101
-
- x -1 = 0000 0101
- -0000 0001
- ----------
- 0000 0100
- ----------
-
-We see that x-1 has the property of inverting the last bit. So, *x & x -1* will
-always set the last bit to 0.
-
-
-If we use the property of **x & x-1** setting the last bit to 0, then we can we
-use this to count the number of bits. This is done in our bitcount's for loop.
-
-::
-
- for(b=0; x!=0; x &= x-1)
- ++b;
-
-This gives the number of 1 bits in our program. **AND** operation is faster than
-shifting, because all bits of the number are **not** moved and thereby makes our
-program more efficient.
-
-
-References
-==========
-
-* `Ones complement`_
-* `Twos complement`_
-
-.. _Ones complement: http://foldoc.org/ones+complement
-.. _Twos complement: http://foldoc.org/twos+complement
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_2.9_bitcount2s.c`
- * :c-better-explain:`Ex_2.9_bitcount2s.rst`
diff --git a/source/cprogramming/Ex_3.1_binsearch-2.rst b/source/cprogramming/Ex_3.1_binsearch-2.rst
deleted file mode 100644
index bf8db706..00000000
--- a/source/cprogramming/Ex_3.1_binsearch-2.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-======================================================================
-Exercise 3.1 - Binsearch function, writing minimum tests inside a loop
-======================================================================
-
-Question
-========
-
-Our binary search makes two tests inside the loop, when one would suffice (at
-the price of more tests outside.) Write a version with only one test inside the
-loop and measure the difference in runtime.
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.1_binsearch-2.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.1_binsearch-2.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
- The program demonstrates a binsearch function which
- takes element (x) to search for, an array of integers and the length of the array as arguments.
-
- The program determines the position of the element(x) by doing a binary search. Binary search can only
- be used for sorted arrays. Program compares search element (x) with mid element of the given array. If mid element is greater than search
- element then search continues among the rest of the elements towards left of current mid element.
- Search continues in similar fashion. If found, program returns the position of search element in the array.
-
- In the example above search element is 9. Program returns 4 which is the position of search element
- in the given array.
-
-
-
- .. seealso::
-
- * :c-suggest-improve:`Ex_3.1_binsearch-2.c`
- * :c-better-explain:`Ex_3.1_binsearch-2.rst`
diff --git a/source/cprogramming/Ex_3.2_escape.rst b/source/cprogramming/Ex_3.2_escape.rst
deleted file mode 100644
index fcdda5e4..00000000
--- a/source/cprogramming/Ex_3.2_escape.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-========================================================
-Exercise 3.2 - escape sequences into the real characters
-========================================================
-
-Question
-========
-
-Write a function escape(s,t) that converts characters like newline and tab into
-visible escape sequences like \n and \t as it copies the string t to s. Use a
-switch. Write a function for the other direction as well, converting escape
-sequences into the real characters.
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.2_escape.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.2_escape.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-C Program interpreters ``\n`` and ``\t`` as space characters and outputs them. Our
-intention is to capture the ``\n`` and ``\t`` characters and display them visibly as
-**\n** or **\t**. In order to do that we need to *escape* them, the escaping is
-done by adding ``\`` character.
-
-So in the program as soon as we see a ``\n`` character, in the array where we are
-copying to, we copy ``\\`` character and add a ``n`` character and similarly, when
-we see a ``\t`` character, in the array where we are copying to, we copy ``\\``
-character and add a ``t`` character.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.2_escape.c`
- * :c-better-explain:`Ex_3.2_escape.rst`
diff --git a/source/cprogramming/Ex_3.3_expand.rst b/source/cprogramming/Ex_3.3_expand.rst
deleted file mode 100644
index c6f11afa..00000000
--- a/source/cprogramming/Ex_3.3_expand.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-==============================================================
-Exercise 3.3 - expand short hand notation in s1 into string s2
-==============================================================
-
-Question
-========
-
-Write a function expand(s1,s2) that expands shorthand notations like a-z in the
-string s1 into the equivalent complete list abc...xyz in s2. Allow for letters
-of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9
-and -a-z. Arrange that a leading or trailing -is taken literally.
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.3_expand.c
- :language: c
- :tab-width: 4
-
-
-.. runcode:: ../../languages/cprogs/Ex_3.3_expand.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-Here we expand the strings like a-z from s1 into an expanded form in s2. We
-utilize the ascii table property that the second character is higher than the
-first character and it is incremental.
-
-In the outer while loop, we get the character in c, and then check if the next
-character is ``-`` and character beyond that (i+1) is greater than c. With this
-check, we ascertain that we are in a range like ``a-z``.
-
-To expand the range, we keep incrementing the character in **c**, till it hits
-the end character, storing all the characters in s2.
-
-s2 will now have the expanded string.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.3_expand.c`
- * :c-better-explain:`Ex_3.3_expand.rst`
diff --git a/source/cprogramming/Ex_3.4_itoa-2.rst b/source/cprogramming/Ex_3.4_itoa-2.rst
deleted file mode 100644
index 08b19b71..00000000
--- a/source/cprogramming/Ex_3.4_itoa-2.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-======================================================
-Exercise 3.4 - itoa to handle largest negative integer
-======================================================
-
-Question
-========
-
-In a two's complement number representation, our version of itoa does not handle
-the largest negative number, that is, the value of n equal to -(2wordsize-1).
-Explain why not. Modify it to print that value correctly, regardless of the
-machine on which it runs.
-
-The previous version of itoa was this::
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-previous.c
- :language: c
- :tab-width: 4
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-2.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.4_itoa-2.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-In this version of itoa, which involves a largest negative number, we first
-store the number itself in an integer called sign. Then get numbers from
-unittest by doing `n%10`, get the unsigned number by doing a `abs` value and get
-character by adding it to `0`.
-
-Thus we go about converting each digit starting from unit place to a character.
-Once this process is over. We check if we were converting negative number, by
-checking if the sign is less than 0, if it was, we add a `-` to the string.
-
-And then we do a simple `reverse` of the string to get our `itoa`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.4_itoa-2.c`
- * :c-better-explain:`Ex_3.4_itoa-2.rst`
diff --git a/source/cprogramming/Ex_3.5_itob.rst b/source/cprogramming/Ex_3.5_itob.rst
deleted file mode 100644
index e8593a06..00000000
--- a/source/cprogramming/Ex_3.5_itob.rst
+++ /dev/null
@@ -1,42 +0,0 @@
-==============================================================
-Exercise 3.5 - function itob, converts a integer into a string
-==============================================================
-
-Question
-========
-
-Write the function itob(n,s,b) that converts the integer n into a base b
-character representation in the string s. In particular, itob(n,s,16) formats s
-as a hexadecimal integer in s.
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.5_itob.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.5_itob.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-In this, we are specifically targetting the conversion to base 16, though we
-should be able to extend the program to any base.
-
-As before we get the number and store it in sign, then we get the remainder of
-the number after dividing by base `b`. We covert the number we have gotten to
-hexadecimal by this expression ` (j <= 9)?j+'0':j+'a'-10`, which states that if
-the number is less than 10, return the string representation of it, otherwise
-subtract 10 from it and add 'a' to get the hexadecimal representation of 10 to
-15 that (a,b,c,d,e,f).
-
-We store these in a string and it number was a negative number, we append '-'
-sign to it. We get the result, by reversing the string which we constructed.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.5_itob.c`
- * :c-better-explain:`Ex_3.5_itob.rst`
diff --git a/source/cprogramming/Ex_3.6_itoa-3.rst b/source/cprogramming/Ex_3.6_itoa-3.rst
deleted file mode 100644
index 04883c3f..00000000
--- a/source/cprogramming/Ex_3.6_itoa-3.rst
+++ /dev/null
@@ -1,53 +0,0 @@
-====================================
-Exercise 3.6 - itoa with field width
-====================================
-
-Question
-========
-
-Write a version of itoa that accepts three arguments instead of two. The third
-argument is a minimum field width; the converted number must be padded with
-blanks on the left if necessary to make it wide enough.
-
-.. literalinclude:: ../../languages/cprogs/Ex_3.6_itoa-3.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.6_itoa-3.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Note: For negative numbers the negative sign is written close to the number
-instead of before the padded width. This is ``itoa`` conversion with padding. We
-specify the width of the number we want in ``w`` and as before, we proceed with
-``itoa``, wherein extract the unit digit (n ``% 10``), convert it to character and
-store it in a character array. If it were a negative number we store the sign
-too. We keep track of number of digits in the number in a variable, ``i`` and for
-the remaining digits, for ``i < w``, we append the space character " ".
-
-We reverse the string thus constructed for our result.
-
-
-Visualize It
-============
-
-.. raw:: html
-
-
-
-Run It
-======
-
-.. raw:: html
-
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.6_itoa-3.c`
- * :c-better-explain:`Ex_3.6_itoa-3.rst`
diff --git a/source/cprogramming/Ex_4.10_calculator_getline.rst b/source/cprogramming/Ex_4.10_calculator_getline.rst
deleted file mode 100644
index c857b000..00000000
--- a/source/cprogramming/Ex_4.10_calculator_getline.rst
+++ /dev/null
@@ -1,89 +0,0 @@
-========================================
-Exercise 4.10 - Calculator using getline
-========================================
-
-Question
-========
-
-An alternate organization uses getline to read an entire input line; this makes
-getch and ungetch unnecessary. Revise the calculator to use this approach.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.10_calculator_getline.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.10_calculator_getline.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program uses `mgetline` to get the characters and operands from the input
-and and proceeds with the RPN calculator logic.
-
-This is the main part of the program.
-
-
-::
-
- /* getop: get next operator or numeric operand */
-
- int getop(char s[])
- {
- int c,i;
-
- if(line[li] == '\0')
- if(mgetline(line,MAXLINE) == 0)
- return EOF;
- else
- li =0;
-
- while((s[0] = c = line[li++]) == ' ' || c == '\t')
- ;
-
- s[1] = '\0';
-
- if(!isdigit(c) && c!= '.')
- return c;
-
- i = 0;
-
- if(isdigit(c))
- while(isdigit(s[++i] = c = line[li++]))
- ;
- if( c == '.')
- while(isdigit(s[++i] = c = line[li++]))
- ;
-
- s[i] = '\0';
-
- li--;
-
- return NUMBER;
- }
-
-
-From the mgetline function, it takes the input in the line character array, and
-if if the line is `\0` only, then we define that as EOF and return `EOF`. Then
-we assign to `c` the value present at `line` and look for various conditions
-like, if line is a space or tab character, we simply skip it. If we encouter c
-which is not a digit or not a `.` character, we return `c` immediately. At the
-end if it is valid number, we return a NUMBER, which is then pushed onto the
-stack of the RPN calculator.
-
-An example execution will look like this.
-
-::
-
- 10 10 +
- 20
- 10.1 20.2 +
- 30.3
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.10_calculator_getline.c`
- * :c-better-explain:`Ex_4.10_calculator_getline.rst`
diff --git a/source/cprogramming/Ex_4.11_getch_static.rst b/source/cprogramming/Ex_4.11_getch_static.rst
deleted file mode 100644
index 05aeedb5..00000000
--- a/source/cprogramming/Ex_4.11_getch_static.rst
+++ /dev/null
@@ -1,87 +0,0 @@
-====================================
-Exercise 4.11 - getline using static
-====================================
-
-Question
-========
-
-Modify getop so that it doesn't need to use ungetch. Hint: use an internal
-static variable.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.11_getch_static.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.11_getch_static.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The point of illustration of this program is the static variable, `lastc`, which
-gets initialized once as a static variable and maintains its state at each
-invocation. The `getop` function declares the variable `lastc` and proceeds as
-before. It calles `getch` to get the last character and if it is a `EOF` it
-returns the EOF, if it a space ignores and if not a number, it returns
-immediately and ensures that it parses a valid number.
-
-At the end, it verifies that the character read is not `EOF` and the stores the
-last character which was read using `getch` in the `lastc` variable.
-
-
-::
-
-
-
- int getop(char s[])
- {
- int c,i;
- static int lastc = 0;
-
- if(lastc == 0)
- c = getch();
- else
- {
- c = lastc;
- lastc = 0;
- }
-
- while((s[0]=c) == ' ' || c == '\t')
- c = getch();
-
- s[1]='\0';
-
- if(!isdigit(c) && c!= '.')
- return c;
-
- i = 0;
- if(isdigit(c))
- while(isdigit(s[++i] =c=getch()))
- ;
- if(c=='.')
- while(isdigit(s[++i] =c=getch()))
- ;
- s[i]='\0';
-
- if(c!=EOF)
- lastc=c;
-
- return NUMBER;
- }
-
-The program execution looks like this.
-
-::
-
- 10 10 +
- 20
- 201 305 + 20 *
- 10120
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.11_getch_static.c`
- * :c-better-explain:`Ex_4.11_getch_static.rst`
diff --git a/source/cprogramming/Ex_4.12_recursive_itoa.rst b/source/cprogramming/Ex_4.12_recursive_itoa.rst
deleted file mode 100644
index da74b830..00000000
--- a/source/cprogramming/Ex_4.12_recursive_itoa.rst
+++ /dev/null
@@ -1,62 +0,0 @@
-========================================================================
-Exercise 4.12 - convert integer into string by calling recursive routine
-========================================================================
-
-Question
-========
-
-Adapt the ideas of printd to write a recursive version of itoa; that is, convert
-an integer into a string by calling a recursive routine.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.12_recursive_itoa.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.12_recursive_itoa.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The main part of this program is the `itoa` routine, which takes an `integer n`
-and `string s` and is called recursively.
-
-::
-
- void itoa(int n,char s[])
- {
- static int i;
-
- if(n/10)
- itoa(n/10,s);
- else
- {
- i = 0;
- if( n < 0)
- s[i++]='-';
- }
-
- s[i++] = abs(n) % 10 + '0';
-
- s[i] = '\0';
-
- }
-
-
-In the first invocation from the main program, this is called with `n = 1723`
-and within the program the number n is divided by 10 (until it is less than 10),
-and the new number (which is old number / 10) is called with `itoa` again. When
-we reach the first digit of the number, the number is converted to a string
-using `abs(n) % 10 + '0'` and stored in the s array. The array is closed with
-`\0`, in subsequent recurssion, the next values like 7,2,3 will override \0
-stored from the previous iteration and in the last call of the recursion, the
-number the complete number is transformed from integer to string. `s` will look
-like `['1','7','2','8','\0']` and this will be printed in the main program.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.12_recursive_itoa.c`
- * :c-better-explain:`Ex_4.12_recursive_itoa.rst`
diff --git a/source/cprogramming/Ex_4.13_reverse_string.rst b/source/cprogramming/Ex_4.13_reverse_string.rst
deleted file mode 100644
index 99e5076c..00000000
--- a/source/cprogramming/Ex_4.13_reverse_string.rst
+++ /dev/null
@@ -1,56 +0,0 @@
-====================================
-Exercise 4.13 - reverse the string s
-====================================
-
-Question
-========
-
-Write a recursive version of the function reverse(s), which reverses the string
-s in place.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.13_reverse_string.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.13_reverse_string.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The main part of this program is the reverser function.
-
-::
-
- void reverser(char s[],int i,int len)
- {
- int c,j;
-
- j = len - (i + 1);
-
- if( i < j )
- {
- c = s[i];
- s[i] = s[j];
- s[j] = c;
-
- reverser(s,++i,len);
- }
- }
-
-
-The string to be reversed is taken in the character array `s` and the first
-invocation is called with `i=0`. The value `len` stands for the length of the
-string. During each invocation, `j` is calculated as `len - (i+1)`, which is the
-character from the end which needs to be swapped and characters at `i is
-swapped with j`. And then reverser is called again with the next value of i,
-i.e, `++i`. This whole operation is done till i (from left hand side of the
-string) is less than j (from the right end), i.e, `i < j`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.13_reverse_string.c`
- * :c-better-explain:`Ex_4.13_reverse_string.rst`
diff --git a/source/cprogramming/Ex_4.14_swap_t_x_y.rst b/source/cprogramming/Ex_4.14_swap_t_x_y.rst
deleted file mode 100644
index ea10100d..00000000
--- a/source/cprogramming/Ex_4.14_swap_t_x_y.rst
+++ /dev/null
@@ -1,48 +0,0 @@
-==============================================================
-Exercise 4.14 - swap that interchanges two arguments of type t
-==============================================================
-
-Question
-========
-
-Define a macro swap(t,x,y) that interchanges two arguments of type t.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.14_swap_t_x_y.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.14_swap_t_x_y.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-There are two types of macros in C namely object-like and function-like. In
-object type, we do substitution and in function macros we can send a variable as
-argument. In this program we are going to use function-like macro to swap.
-
-We do this by defining macro::
-
- #define swap(t,x,y) { t _z; \
- _z = x;\
- x = y;\
- y = _z; }
-
-In the macro, we send type `t` as an argument and two variables `x` and `y` to
-swap. We create a temperorary variable called `_z` of type `t` and use it to
-swap `x` and `y`.
-
-References
-==========
-
-* `More on C macros`_
-
-.. _More on C macros: http://en.wikipedia.org/wiki/C_preprocessor#Macro_definition_and_expansion
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.14_swap_t_x_y.c`
- * :c-better-explain:`Ex_4.14_swap_t_x_y.rst`
diff --git a/source/cprogramming/Ex_4.1_strindex_rightmost.rst b/source/cprogramming/Ex_4.1_strindex_rightmost.rst
deleted file mode 100644
index f201d1f6..00000000
--- a/source/cprogramming/Ex_4.1_strindex_rightmost.rst
+++ /dev/null
@@ -1,51 +0,0 @@
-========================================================
-Exercise 4.1- strindex which returns rightmost occurance
-========================================================
-
-Question
-========
-
-Write the function strindex(s,t) which returns the position of the rightmost
-occurrence of t in s, or -1 if there is none.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.1_strindex_rightmost.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.1_strindex_rightmost.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-We find the rightmost of index of our substring in this program. If we ask to
-look for pattern "abc" in the line "abcdedfabcde", the program should correctly
-identify the rightmost occurance which happens at position 7.
-
-This is done by our `mstringindex` function and in this loop.
-
-::
-
- result = -1;
-
- for(i=0;s[i]!='\0';i++)
- {
- for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
- ;
- if(k>0 && t[k] == '\0')
- result = i;
- }
-
-The outer loop goes over each character in string `s` and in the inner we check
-if we find a substring `t` matching in the outer loop. If we find a substring
-match, we **dont break** the loop, but record the position `i` and proceed
-further. Thus our right most match is noted. If no search is found, then the
-result, `-1` is returned.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.1_strindex_rightmost.c`
- * :c-better-explain:`Ex_4.1_strindex_rightmost.rst`
diff --git a/source/cprogramming/Ex_4.2_atof_scientific.rst b/source/cprogramming/Ex_4.2_atof_scientific.rst
deleted file mode 100644
index ec118ea8..00000000
--- a/source/cprogramming/Ex_4.2_atof_scientific.rst
+++ /dev/null
@@ -1,36 +0,0 @@
-========================================================
-Exercise 4.2 - Extend atof to handle scientific notation
-========================================================
-
-Question
-========
-
-Extend atof to handle scientific notation of the form 123.45e-6 where a
-floating-point number may be followed by e or E and an optionally signed
-exponent.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.2_atof_scientific.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.2_atof_scientific.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-For the input::
-
- 1.0e10
-
-We might get the output::
-
- 1410065408.000000
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.2_atof_scientific.c`
- * :c-better-explain:`Ex_4.2_atof_scientific.rst`
diff --git a/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst b/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst
deleted file mode 100644
index e4f67cd2..00000000
--- a/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst
+++ /dev/null
@@ -1,62 +0,0 @@
-========================================================
-Exercise 4.3 - RPN modulus operator and negative numbers
-========================================================
-
-Question
-========
-
-Given the basic framework, it's straightforward to extend the calculator. Add
-the modulus (%) operator and provisions for negative numbers.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.3_rpn_modulus_negative.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.3_rpn_modulus_negative.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program has number of helper functions like getop, push and pop, which we
-use to the implement the reverse polish notation calculator.
-
-The function getop takes a string and determines if it is number. If it is a
-number, both integer or decimal, it will store that number in the array and
-return a flag NUMBER which states that number is found. It will push that number
-to the stack. If it getop returns an operator like +, -, * or /, it will pop two
-numbers out of the stack and operate on it. When it encounters a /, it ensures
-that the second operand is not 0 and disallows.
-
-It pushes each number to the stack and when it finds an operand, it will pop out
-two numbers in the stack and operate on it and push the result back into the
-stack. When it encounters a `\n` it will pop out the last stored number in the
-stack and gives the result.
-
-Thus our operation of the RPN calculator for few inputs look like this.
-
-
-::
-
- 10 10 + 100 + 2 *
- 240
- 500 2 *
- 1000
- 100 3 /
- 33.333333
- -10 -10 -
- 0
- 20 -10 +
- 10
- -20 10 +
- -10
- -10 -10 +
- -20
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.3_rpn_modulus_negative.c`
- * :c-better-explain:`Ex_4.3_rpn_modulus_negative.rst`
diff --git a/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst b/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst
deleted file mode 100644
index 098fef5a..00000000
--- a/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst
+++ /dev/null
@@ -1,73 +0,0 @@
-===================================================================================
-Exercise 4.4 - RPN Calculator - print two top elements of the stack without popping
-===================================================================================
-
-Question
-========
-
-Add the commands to print the top elements of the stack without popping, to
-duplicate it, and to swap the top two elements. Add a command to clear the
-stack.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.4_rpn_top_two_elements.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.4_rpn_top_two_elements.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program has number of helper functions like getop, push and pop, which we
-use to the implement the reverse polish notation calculator. It enhances the RPN
-calculator with additional features like `d` to double the entries of the top
-two elements, `s` to swap the entries of the top two elements, `?` to display
-the top element and finally `c` to clear the stack.
-
-The function getop takes a string and determines if it is number. If it is a
-number, both integer or decimal, it will store that number in the array and
-return a flag NUMBER which states that number is found. It will push that number
-to the stack. If it getop returns an operator like +, -, * or /, it will pop two
-numbers out of the stack and operate on it. When it encounters a /, it ensures
-that the second operand is not 0 and disallows.
-
-It pushes each number to the stack and when it finds an operand, it will pop out
-two numbers in the stack and operate on it and push the result back into the
-stack. When it encounters a n it will pop out the last stored number in the
-stack and gives the result.
-
-On d, It doubles the characters.
-
-On s, It swaps the characters.
-
-On c, It clears the characters in the stack.
-
-On ?, It goes to the top element of the stack.
-
-So here is how the expression is evaluated.
-
-::
-
- 1 d + 3 s ?
- 2
- 2
- ?
- 3
- 3
- ?
-
-It takes 1 and `d` doubles it. So our stack will be `1 1`. And then when it sees
-`+`, it will add the two values and substitute with the result. So our stack
-will now be `2`. We push 3 to the stack and `s` swaps it. Our stack will be `3
-2`. So when we input `?` and enter. We get the top element `2` out. And then
-pressing `?` again will pop next element `3`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.4_rpn_top_two_elements.c`
- * :c-better-explain:`Ex_4.4_rpn_top_two_elements.rst`
-
diff --git a/source/cprogramming/Ex_4.5_calculator_math_functions.rst b/source/cprogramming/Ex_4.5_calculator_math_functions.rst
deleted file mode 100644
index cd88a5ce..00000000
--- a/source/cprogramming/Ex_4.5_calculator_math_functions.rst
+++ /dev/null
@@ -1,59 +0,0 @@
-=========================================================
-Exercise 4.5 - RPN Calculator with mathematical functions
-=========================================================
-
-Question
-========
-
-Add access to library functions like sin, exp, and pow.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.5_calculator_math_functions.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.5_calculator_math_functions.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The RPN calculator has addition features like doing mathematical functions. In the input, if a string is given then the
-calculator identifies it as a NAME and goes to the mathfun.
-
-In the mathfun, the string input is compared with "sin" and if it is a sin, the mathematical function `sin` is called on
-the popped value. If the intput is `cos`, the cosine function is called and if the input is "pow", then first value is
-popped and stored in `op2` and second value is raised to the power of op2.
-
-
-The curx of program is in this function.
-
-::
-
- void mathfnc(char s[])
- {
- double op2;
-
- if(strcmp(s,"sin")==0)
- push(sin(pop()));
- else if(strcmp(s,"cos")==0)
- push(cos(pop()));
- else if(strcmp(s,"exp")==0)
- push(exp(pop()));
- else if(strcmp(s,"pow")==0)
- {
- op2 = pop();
- push(pow(pop(),op2));
- }
- else
- printf("error: %s is not supported\n",s);
- }
-
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.5_calculator_math_functions.c`
- * :c-better-explain:`Ex_4.5_calculator_math_functions.rst`
diff --git a/source/cprogramming/Ex_4.6_calculator_variables.rst b/source/cprogramming/Ex_4.6_calculator_variables.rst
deleted file mode 100644
index a3667eec..00000000
--- a/source/cprogramming/Ex_4.6_calculator_variables.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-============================================
-Exercise 4.6 - RPN Calculator with variables
-============================================
-
-Question
-========
-
-Add commands for handling variables. (It's easy to provide twenty-six variables
-with single-letter names.) Add a variable for the most recently printed value.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.6_calculator_variables.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.6_calculator_variables.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This adds variables to our RPN calculator. An example execution goes like this.
-
-::
-
- 10 A = 20 B = A B +
- 30
- v
- 30
-
-
-The RPN notation for assigning to variables is like this `10 A =`. When an `=`
-sign is encountered the previous value is popped and the value that is stored in
-`var` variable (that is the previous one is taken) and then it's value is
-assigned to the next popped variable. Thus two variables `A` and `B` are set in
-the above expression.
-
-Then `A B +` acts as if we are acting on two numbers. A special variable `v` is
-used to assign to the last printed value.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.6_calculator_variables.c`
- * :c-better-explain:`Ex_4.6_calculator_variables.rst`
diff --git a/source/cprogramming/Ex_4.7_ungets.rst b/source/cprogramming/Ex_4.7_ungets.rst
deleted file mode 100644
index d4fab0cb..00000000
--- a/source/cprogramming/Ex_4.7_ungets.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-==================================================================================
-Exercise 4.7 - Function ungets that will push back an entire string onto the input
-==================================================================================
-
-Question
-========
-
-Write a routine ungets(s) that will push back an entire string onto the input.
-Should ungets know about buf and bufp, or should it just use ungetch?
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.7_ungets.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.7_ungets.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program defines `ungets(s)`, which takes a string as an input and and
-removes one character at a time from the back of the string and puts them into a
-the buffer BUF. It does this, till all the characters from the input string are
-placed onto the buffer. It uses the function `ungetch` to place to the buffer.
-
-When getch() is called, the characters from the buffer are read first and it is
-output on the screen.
-
-So, when we write something like this.
-
-::
-
- $ ./a.out
- this is a sentence
- this is a sentence
-
-The first sentence is read as input and placed in the BUF and the next sentence
-is read using `getch()` from the BUF array.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.7_ungets.c`
- * :c-better-explain:`Ex_4.7_ungets.rst`
diff --git a/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst b/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst
deleted file mode 100644
index c273d583..00000000
--- a/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-============================================================
-Exercise 4.8 - getch and ungetch handling pushback character
-============================================================
-
-Question
-========
-
-Suppose that there will never be more than one character of pushback. Modify
-getch and ungetch accordingly.
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.8_getch_ungetch_pushback.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.8_getch_ungetch_pushback.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program maintains a character buffer `char buf=0` which holds a single
-character from the input. The function `ungetch(c)` when called places the
-character in the input and `getch()`, if it finds the character in the buf,
-returns it or it calls `getchar` to get character from the user.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.8_getch_ungetch_pushback.c`
- * :c-better-explain:`Ex_4.8_getch_ungetch_pushback.rst`
diff --git a/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst b/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst
deleted file mode 100644
index 1b674e02..00000000
--- a/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-=======================================================
-Exercise 4.9 - getch and ungetch handling EOF Character
-=======================================================
-
-Question
-========
-
-Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what
-their properties ought to be if an EOF is pushed back, then implement your
-design.
-
-.. literalinclude:: ../../languages/cprogs/Ex_4.9_getch_ungetch_eof.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_4.9_getch_ungetch_eof.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZ]`.
-This has a limitation wherein the when an `EOF` character is encountered, it
-wont be stored in the buffer. The EOF character is an integer type. This problem
-can be solved by declaring our buf to be of integer type, like `int
-buf[BUFSIZE]` and `ungetch(c)` will store the character c, including EOF, now in
-an integer array.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_4.9_getch_ungetch_eof.c`
- * :c-better-explain:`Ex_4.9_getch_ungetch_eof.rst`
diff --git a/source/cprogramming/Ex_5.10_exprcmd.rst b/source/cprogramming/Ex_5.10_exprcmd.rst
deleted file mode 100644
index 88f73ec4..00000000
--- a/source/cprogramming/Ex_5.10_exprcmd.rst
+++ /dev/null
@@ -1,41 +0,0 @@
-====================================================
-Exercise 5.10 - expr, evaluate rpn from command line
-====================================================
-
-Question
-========
-
-Write the program expr, which evaluates a reverse Polish expression from the
-command line, where each operator or operand is a separate argument.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.10_exprcmd.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.10_exprcmd.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program reads the input to our rpn calculator from the command line itself.
-`2 3 4 + *` and then goes about doing the RPN caculator work on it.
-
-The main function has a signature now, that is `int main(int argc, char
-*argv[])`, that is it takes the command line args, **argc** for count of the
-args and **argv** is the array which stores the arguments.
-
-So, 2, 3, 4, +, * will be stored in the array **agrv** as strings. In this
-program, we go about by getting each argument from argv and then giving that as
-the input to our RPN calculator, like the program in sec_4.3. If we find an
-operand, using the push function, we push it to the stack and when we find a
-operator in the input, we pop() the two operands out of the stack and do the
-operation.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.10_exprcmd.c`
- * :c-better-explain:`Ex_5.10_exprcmd.rst`
diff --git a/source/cprogramming/Ex_5.11_conddetab.rst b/source/cprogramming/Ex_5.11_conddetab.rst
deleted file mode 100644
index f5a62afa..00000000
--- a/source/cprogramming/Ex_5.11_conddetab.rst
+++ /dev/null
@@ -1,47 +0,0 @@
-=======================================================
-Exercise 5.11 - entab and detab which accepts arguments
-=======================================================
-
-Question
-========
-
-Modify the program entab and detab (written as exercises in Chapter 1) to accept
-a list of tab stops as arguments. Use the default tab settings if there are no
-arguments.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.11_conddetab.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.11_conddetab.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program is about accepting the arguments for entab and entab as command
-line args. So the main program accepts argc and argv.
-
-The program is to take an argument like -m +n, which means tab stops every n
-columns;starting at column m.
-
-So, the main program sends it to esettab function, both argc, argv and a
-character array tab[MAXLINE-1];
-
-If we had not given, m or n, it takes the TABINC of 8 and starts with the first
-colummn and marking every TABINC position as tab (setting the value to YES) in
-character array tab. If we give the values for m and n, it marks the
-corresponding position in tab as 'yes'.
-
-This function only implements detab, which replaces the tab with spaces. So,
-when a sentence is read with detab, the function consults `tabpos` function to
-see if it s tab. If it is tab, then till it meets the next tab, it will output
-space ' ', thus converting the tabs to spaces.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.11_conddetab.c`
- * :c-better-explain:`Ex_5.11_conddetab.rst`
diff --git a/source/cprogramming/Ex_5.12_condientab.rst b/source/cprogramming/Ex_5.12_condientab.rst
deleted file mode 100644
index 28e8097b..00000000
--- a/source/cprogramming/Ex_5.12_condientab.rst
+++ /dev/null
@@ -1,63 +0,0 @@
-==================================================
-Exercise 5.12 - entab -m + which accepts arguments
-==================================================
-
-Question
-========
-
-Extend entab and detab to accept the shorthand.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.12_condientab.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.12_condientab.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program is similar to the Exercise 5.11, where we send the arguments to
-entab and detab. So the main program accepts argc and argv. The program is to
-take an argument like -m +n, which means tab stops every n columns;starting at
-column m.
-
-The main program sends it to esettab function, both argc, argv and a character
-array `tab[MAXLINE-1]`.
-
-esettab function's purpose is to fill the character array `tab` with values YES
-(1) or NO(0). It determines from the arguments the -m , which is the POS and +n,
-the increment, and marks at each `m`, the tab value as YES, and then increments
-by `n`, and marks the next tab value as YES. If m and n are not provided, it
-goes with sane defaults.
-
-The entab function implemented in this program, converts the spaces to tab
-characters. So, the entab function, when it encounters a space character c, like
-`if(c == ' ')`, it checks the corresponding position in the previously formed
-`tab`, if the position value is `YES` or `NO`. If it is YES, then it increments
-the tab count, `++nt`, if it is not tab position, it increments the blank count
-`++nb`.
-
-When it encounters a first non-space character, then it checks it internal
-variables, nt and nb. If `nt` is greater than 0, it meansm that we have tabs to
-print, so it prints the tab characters for each nt count. It also prints the
-literal tabs, it encounters.
-
-After printing it all the tabs, it checks the variable, `nb`, namely if we have
-determined any blanks. If there blanks to be printed, it prints them out too.
-
-And finally, the prints the character using `putchar(c)`.
-
-We also have to handle cases when we encounter a newline character. When we
-encounter a newline, like `\n`, we print the new line, but reset the position,
-so that our position, `pos`, now becomes 0. When we encounter a tab character,
-we increment the position (pos) to the next tab, so that when we encounter the
-next space, we can verify it for the new position.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.12_condientab.c`
- * :c-better-explain:`Ex_5.12_condientab.rst`
diff --git a/source/cprogramming/Ex_5.13_tailn.rst b/source/cprogramming/Ex_5.13_tailn.rst
deleted file mode 100644
index 038da37a..00000000
--- a/source/cprogramming/Ex_5.13_tailn.rst
+++ /dev/null
@@ -1,53 +0,0 @@
-=====================================================
-Exercise 5.13 - tail prints the last n lines of input
-=====================================================
-
-Question
-========
-
-Write the program tail, which prints the last n lines of its input.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.13_tailn.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.13_tailn.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program is to print the last n lines of a file, with default being last 10
-lines. The program sets aside an array of character pointers (strings) to store
-the n lines. The LINES value below being the maximum number of lines that can
-be printed, the default value being 100.
-
-::
-
- char *lineptr[LINES]; /* pointer to lines read */
-
-The program works by first allocating enough memory for the last n lines in a
-buffer. Gets each line using `mgetline(line, MAXLEN)` and then copies each line
-to an index entry in the lineptr array.
-
-::
-
- strcpy(lineptr[last],line);
-
-It advances the pointer `last` at each copy, and when it exceed the maximum
-count, it just rolls over, starting from 0.
-
-Next, we have to define the logic to print the last n lines. We offset line
-value appropriately to the number of lines. It is either `last - n` lines and if
-that value goes negative, then we increment it to max lines LINES. We start at
-first value of line and as long as the the line number count represented by n
-exists, we print the line, decrementing the count at each step.
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.13_tailn.c`
- * :c-better-explain:`Ex_5.13_tailn.rst`
diff --git a/source/cprogramming/Ex_5.14_sortrevnum.rst b/source/cprogramming/Ex_5.14_sortrevnum.rst
deleted file mode 100644
index 8cff5b02..00000000
--- a/source/cprogramming/Ex_5.14_sortrevnum.rst
+++ /dev/null
@@ -1,116 +0,0 @@
-=====================================================
-Exercise 5.14 - sorting in reverse (decreasing) order
-=====================================================
-
-Question
-========
-
-Modify the sort program to handle a -r flag, which indicates sorting in reverse
-(decreasing) order. Be sure that -r works with -n.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.14_sortrevnum.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.14_sortrevnum.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program when executed with flags `-nr` and when given an input in any order
-will sort the arguments and print the numbers in reverse order.
-
-For .e.g, when given an input
-
-::
-
- $ ./mysort -nr
- 10
- 40
- 242
- 42
- 52
-
-The output was::
-
- 242
- 52
- 42
- 40
- 10
-
-
-The program works by implementing a version of quicksort. In quicksort, we give
-two indices, left value (starting 0) and right value (nlines, the number of
-lines), we send the array of strings (`char *lineptr[]`) to be sorted and then
-we send a comparator function as a pointer too.
-
-The declartion of myqsort looks like this.
-
-::
-
- void myqsort(void *v[],int left,int right,int (*comp)(void *,void *));
-
-The comparator function, `numcmp` will return -1, if the first argument is less
-than second, it will return 1, if the first argument is greater, otherwise it
-will 0. This is a standard way in which many comparator functions are defined.
-
-In the execution of quicksort, it partitions the array into 2, and recursively,
-sorts the left half and then the right half.
-
-Since we have to sort it "in-place", the details of the implementation needs
-careful analysis.
-
-We choose the middle element and move it to extreme left (position 0), the
-compare the values, starting with next element (at position 1) upto our right
-pointer, the middle of the array.
-
-If we find any values which are less than our element (position 0), we swap it
-to left, next to our left element and keep that counter as the last value.
-
-Thus for all the values less then our first element, we might have moved them to
-left.
-
-For e.g.
-
-If our first iteration starts like this.
-
-::
-
- 40 45 55 30 10 60
- ^
- left
-
-Our first few iterations will be::
-
- 40 30 45 55 10 60
- ^ ^
- left last
-
- 40 30 10 45 55 60
- ^ ^
- left last
-
-And then finally we swap the left and last::
-
- 10 30 40 45 55 60
- ^ ^
- last left
-
-Thus we have a partially sorted left side. Thus by carefully moving the pointers
-we sorted the left side comparing each element with the middle element.
-Similarly, we do the same for the right half of the array, and then recursively
-divide each half to sort it.
-
-The curx of the program is in `myqsort`` function and once that is sorted, the
-program displays the output as we desire.
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.14_sortrevnum.c`
- * :c-better-explain:`Ex_5.14_sortrevnum.rst`
diff --git a/source/cprogramming/Ex_5.15_sortfnr.rst b/source/cprogramming/Ex_5.15_sortfnr.rst
deleted file mode 100644
index fb0c482d..00000000
--- a/source/cprogramming/Ex_5.15_sortfnr.rst
+++ /dev/null
@@ -1,29 +0,0 @@
-==================================================
-Exercise 5.15 - fold upper and lower case together
-==================================================
-
-Question
-========
-
-Add the option -f to fold upper and lower case together, so that case
-distinctions are not made during sorting; for example, a and A compare equal.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.15_sortfnr.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.15_sortfnr.c
- :language: c
- :codesite: ideone
-
-
-Explanation
-===========
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.15_sortfnr.c`
- * :c-better-explain:`Ex_5.15_sortfnr.rst`
diff --git a/source/cprogramming/Ex_5.16_sort_dfnr.rst b/source/cprogramming/Ex_5.16_sort_dfnr.rst
deleted file mode 100644
index a5faf76c..00000000
--- a/source/cprogramming/Ex_5.16_sort_dfnr.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-===============================================================
-Exercise 5.16 - -d makes comparison on letters, numbers, blanks
-===============================================================
-
-Question
-========
-
-Add the -d (``directory order``) option, which makes comparisons only on
-letters, numbers and blanks. Make sure it works in conjunction with -f.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.16_sort_dfnr.c`
- * :c-better-explain:`Ex_5.16_sort_dfnr.rst`
diff --git a/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst b/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst
deleted file mode 100644
index 7c9ea9fd..00000000
--- a/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst
+++ /dev/null
@@ -1,29 +0,0 @@
-====================================
-Exercise 5.17 - Sorting with options
-====================================
-
-Question
-========
-
-Add a field-searching capability, so sorting may bee done on fields within
-lines, each field sorted according to an independent set of options. (The index
-for this book was sorted with -df for the index category and -n for the page
-numbers.)
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.17_sortdfnr-withoption.c`
- * :c-better-explain:`Ex_5.17_sortdfnr-withoption.rst`
diff --git a/source/cprogramming/Ex_5.18_dcl-errorec.rst b/source/cprogramming/Ex_5.18_dcl-errorec.rst
deleted file mode 100644
index 5d9c903a..00000000
--- a/source/cprogramming/Ex_5.18_dcl-errorec.rst
+++ /dev/null
@@ -1,26 +0,0 @@
-=========================================
-Exercise 5.18 - recover from input errors
-=========================================
-
-Question
-========
-
-Make dcl recover from input errors.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.18_dcl-errorec.c`
- * :c-better-explain:`Ex_5.18_dcl-errorec.rst`
diff --git a/source/cprogramming/Ex_5.19_undcl.rst b/source/cprogramming/Ex_5.19_undcl.rst
deleted file mode 100644
index bb81749f..00000000
--- a/source/cprogramming/Ex_5.19_undcl.rst
+++ /dev/null
@@ -1,26 +0,0 @@
-========================================================
-Exercise 5.19 - undcl does not add redundant parentheses
-========================================================
-
-Question
-========
-
-Modify undcl so that it does not add redundant parentheses to declarations.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.19_undcl.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.19_undcl.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.19_undcl.c`
- * :c-better-explain:`Ex_5.19_undcl.rst`
diff --git a/source/cprogramming/Ex_5.1_getint.rst b/source/cprogramming/Ex_5.1_getint.rst
deleted file mode 100644
index 1645b708..00000000
--- a/source/cprogramming/Ex_5.1_getint.rst
+++ /dev/null
@@ -1,86 +0,0 @@
-==================================================
-Exercise 5.1 - get next integer from input to \*pn
-==================================================
-
-Question
-========
-
-As written, getint treats a + or - not followed by a digit as a valid
-representation of zero. Fix it to push such a character back on the input.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.1_getint.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.1_getint.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-We are to explain the function ``getint(int *)`` which takes a pointer to an
-integer as the argument. We also use ``getch`` and ``ungetch`` as two functions,
-from chapter 4, which work on ``buf`` of ``BUFSIZE`` sharing a global variable
-called ``bufp``. ``ungetch`` function returns the character read to ``buf`` while
-``getch`` tries to read that character to our program and if no character is
-present, it uses ``getchar`` to get the character.
-
-In this program, we declare an ``array`` of size of 1000, and we send each digit
-of the array to getint using a call like ``getint(&array[n])``. Our intention is
-to load the characters in array with a valid integer format like ``+/-1234EOF``,
-that is + or - 1234 and ending with EOF character.
-
-In getint function, we get a character and if it's space, we simply ignore it.
-And this snippet.
-
-::
-
- if(!isdigit(c) && c !=EOF && c!='+' && c!='-')
- {
- ungetch(c); /* it's not a number */
- return 0;
- }
-
-Ensures that if we get a character which is not +,-, digit, EOF, then we return
-0 and in the main loop we end the program. That is, we strictly look for
-characters that can be converted to integer in this program. So the only valid
-inputs are like this.
-
-::
-
- 123
- +123
- -123
-
-And if we get any invalid input.
-
-::
-
- abc
- %**
-
-Then the program will immediately end.
-
-
-So, on a valid input, the initial check is done to see if there is a ``sign`` and
-if yes, it stores the ``sign`` and then it goes about finding the next digit in a
-for loop and calculates the number using this expression.
-
-::
-
- *pn = 10 * *pn + (c-'0')
-
-This is responsible for converting the character like ``1`` to integer 1 and store
-it in ``*pn``, the place in the array. We multiply the number by sign and when we
-find EOF, we store that EOF, so that the program terminates correctly.
-
-Once the getint sees an EOF, we end the program and print the contents of the
-array.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.1_getint.c`
- * :c-better-explain:`Ex_5.1_getint.rst`
diff --git a/source/cprogramming/Ex_5.20_dcl-funcargs.rst b/source/cprogramming/Ex_5.20_dcl-funcargs.rst
deleted file mode 100644
index a98cdde0..00000000
--- a/source/cprogramming/Ex_5.20_dcl-funcargs.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-==================================================================================
-Exercise 5.20 - dcl handling declarations with function argument types, qualifiers
-==================================================================================
-
-Question
-========
-
-Expand dcl to handle declarations with function argument types, qualifiers like
-const, and so on.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.20_dcl-funcargs.c`
- * :c-better-explain:`Ex_5.20_dcl-funcargs.rst`
diff --git a/source/cprogramming/Ex_5.2_getfloat.rst b/source/cprogramming/Ex_5.2_getfloat.rst
deleted file mode 100644
index 8abd6408..00000000
--- a/source/cprogramming/Ex_5.2_getfloat.rst
+++ /dev/null
@@ -1,67 +0,0 @@
-================================================
-Exercise 5.2 - get next float from input to \*pn
-================================================
-
-Question
-========
-
-Write getfloat, the floating-point analog of getint. What type does getfloat
-return as its function value?
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.2_getfloat.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.2_getfloat.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-The function `getfloat` is similar to the `getint` function, wherein instead of
-getting an integer, we get a float value.
-
-We declare an array, `float array[SIZE]` in which we store the float values and
-the the float value is got from the function `int getfloat(float *);`
-
-The function getfloat, sends a pointer to the float and stores a float value in
-the array. The mechanism of how it gets a float is defined in the `getfloat`
-function.
-
-The curx of how the float is got is in this snippet. The function reads all the
-characters and converts to a float and stores them in the `*pn` pointer. Then it
-reads the decimal part and for all the digits after the decimal point, it
-increments the power by 10. For e.g. if the decimal was `0.123` for 3 decimal
-digits, the power will be 10 * 10 * 10 = 1000.
-
-
-::
-
- for(*pn = 0.0 ; isdigit(c);c=getch())
- *pn = 10.0 * *pn + (c - '0');
- if( c == '.')
- c = getch();
-
- for(power=1.0;isdigit(c);c=getch())
- {
- *pn = 10.0 * *pn + (c - '0'); /* fractional part */
- power *= 10.0;
- }
-
- *pn *= sign / power;
-
-
-Finally to get the decimal representation along with sign, then the number in pn
-is divided by power and multiplied by sign, i.e, `*pn = ((*pn * sign) / power)`
-and thus the correct float value is obtained.
-
-The float value is stored in the array index that was sent from the main
-program.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.2_getfloat.c`
- * :c-better-explain:`Ex_5.2_getfloat.rst`
diff --git a/source/cprogramming/Ex_5.3_strcat.rst b/source/cprogramming/Ex_5.3_strcat.rst
deleted file mode 100644
index 9c54d787..00000000
--- a/source/cprogramming/Ex_5.3_strcat.rst
+++ /dev/null
@@ -1,55 +0,0 @@
-==============================================================
-Exercise 5.3 - strcat(s,t) copies the string t to the end of s
-==============================================================
-
-Question
-========
-
-Write a pointer version of the function strcat that we showed in Chapter 2:
-strcat(s,t) copies the string t to the end of s.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.3_strcat.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.3_strcat.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This is a string concatenation program using pointers. The function mystrcat is
-defined to take two strings as character pointers `mystrcat(char *s, char *t)`
-and this function returns the concatenated string in `s` itself.
-
-The way it does is, the position in `s` is advanced till we meet a `\0`
-character and then we append the characters from the string `t` to `s`, starting
-from the `\0` character till we hit the end of the string `t` which is a `\0`
-again.
-
-
-
-::
-
- void mystrcat(char *s,char *t)
- {
- while(*s!='\0')
- s++;
- s--; /* goes back to \0 char */
- while((*s=*t)!='\0')
- {
- s++;
- t++;
- }
- }
-
-
-The construct `while((*s=*t)!='\0')` assigns the character in `t` to `s` and then checks if the character is `\0`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.3_strcat.c`
- * :c-better-explain:`Ex_5.3_strcat.rst`
diff --git a/source/cprogramming/Ex_5.4_strend.rst b/source/cprogramming/Ex_5.4_strend.rst
deleted file mode 100644
index 3864c899..00000000
--- a/source/cprogramming/Ex_5.4_strend.rst
+++ /dev/null
@@ -1,85 +0,0 @@
-=============================================================================
-Exercise 5.4 - strend returns 1 if string t occurs at the end of the string s
-=============================================================================
-
-Question
-========
-
-Write the function strend(s,t), which returns 1 if the string t occurs at the
-end of the string s, and zero otherwise.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.4_strend.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.4_strend.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program determines if the string `t` occurs at the end of string `s`. So
-the output of the program will look like.
-
-::
-
- $ ./a.out
- something
- thing
- 1
-
- $ ./a.out
- something
- non
- 0
-
-
-The primary part of this program is the `strend` function, which takes two
-character pointers, `s` and `t`. It calculates the length of t and stores in the
-variable len. And then, we back off till the last characters in both s and t.
-
-::
-
- while(*s!='\0')
- ++s;
- --s;
-
- while(*t!='\0')
- ++t;
-
- --t;
-
-
-And then we look for the match from the end. This is checked in this while loop.
-While the len is > 0, check if s and t are same and back off one character at a
-time.
-
-::
-
-
- while(len > 0)
- {
- if(*t==*s)
- {
- --t;
- --s;
- --len;
- }
- else
- return 0;
- }
- if( len == 0)
- return 1;
-
-
-If the string t exhausts, that is, it's length, len becomes 0, then we known
-that string `t` occurs at the end of string `s` and we return 1. Otherwise, we
-return 0.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.4_strend.c`
- * :c-better-explain:`Ex_5.4_strend.rst`
diff --git a/source/cprogramming/Ex_5.5_strncpy.rst b/source/cprogramming/Ex_5.5_strncpy.rst
deleted file mode 100644
index f610d8bf..00000000
--- a/source/cprogramming/Ex_5.5_strncpy.rst
+++ /dev/null
@@ -1,52 +0,0 @@
-===============================================================
-Exercise 5.5 - simple versions of strncpy, strncat, and strncmp
-===============================================================
-
-Question
-========
-
-Write versions of the library functions strncpy, strncat, and strncmp, which
-operate on at most the first n characters of their argument strings.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.5_strncpy.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.5_strncpy.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-mystrlen assigns the address of s to p in `char *p = s` and then goes one
-character at a time, till it reaches \0. When it is at the end of the word, it
-subtracts the current address s with intial address p, which thus returns the
-len of string.
-
-mystrncpy copies n characters of source string to destination. It does this by
-copying or overwriting one character a time from source to destination and
-keeps track of count n. When source is exhausted or n characters are copied, it
-checks if there further characters in destination, if it exists, it goes past
-them without over-writing and then closes the string by \0.
-
-mystrncat, takes three arguments, str1, str2 and dest. It concatenates n
-characters from str2 to str1 into a new string dest. It does this by copying all
-characters from str1 to dest and then keeps a track of count n, and copies n
-characters of str2 to dest. After copying n characters, it closes the dest
-string by `\0` character.
-
-mystrncmp, compares the lhs string with rhs string. It compares one character at
-a time and as long as both characters are same, it keeps going and if the lhs is
-exhaused before n characters are compared, it means we still satisfy the
-criteria and we return 0. Otherwise, it returns the difference between lhs
-character and rhs character, which will be 0 if they are equal, negative if lhs
-is smaller than rhs or positive value if lhs is greater than rhs.
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.5_strncpy.c`
- * :c-better-explain:`Ex_5.5_strncpy.rst`
diff --git a/source/cprogramming/Ex_5.6_findpattern.rst b/source/cprogramming/Ex_5.6_findpattern.rst
deleted file mode 100644
index 480d3574..00000000
--- a/source/cprogramming/Ex_5.6_findpattern.rst
+++ /dev/null
@@ -1,82 +0,0 @@
-==============================================
-Exercise 5.6 - Find the pattern using pointers
-==============================================
-
-Question
-========
-
-Rewrite appropriate programs from earlier chapters and exercises with pointers
-instead of array indexing. Good possibilities include getline (Chapters 1 and
-4), atoi, itoa, and their variants (Chapters 2, 3, and 4), reverse (Chapter 3),
-and strindex and getop (Chapter 4).
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.6_findpattern.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.6_findpattern.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-mgetline takes a string ``(char *)`` and MAXLINE, the maximum length of the line. It
-gets one character at a time using getchar() and as long as we are under limit
-(less than MAXLINE) and it is not \n character. It stores the charaacters in the
-line, advancing the pointer for each character.
-
-When it hits \n, it adds \n and closes the line with \0. mgetline returns the
-length of the line, subtracting the last address with initial address.
-
-
-atoi - the gets the sign and then read each read each character using the
-pointer, checks if it is digit and converts it to integer. The curx of this
-function is::
-
- for(n=0;isdigit(*s);s++)
- n = 10 *n + *s - '0';
-
-itoa - takes the number, converts it into a string, by adding '0' and stores
-them to a character pointer, advancing the pointer after each assignment. When
-the assignments are done, it adds a null character to form a valid C string::
-
- do
- {
- *s++ = n % 10 + '0';
- } while ((n /= 10) > 0);
-
- if(sign < 0)
- *s++ = '-';
- *s='\0';
-
-
-reverse takes a ``char *s`` as argument and uses a temporary string ``char *t``, to
-swap the characters from the end to the front. It uses another intermediate
-character ``c`` to do the swap.
-
-strindex takes two strings ``char *s`` and ``char *t`` and determines the start of
-the string t in s. It stores the s position in the base, b and then advances s
-and for each advance checks if the substring t is contained in s. If the
-substring is contained, it returns the current position - base position, that ``s
--b``, otherwise it returns -1.
-
-getop works by taking a ``char *s`` as it's argument. It reads the character and
-stores it in s. It skips the whitespaces and then checks if it isdigit.
-If it not a digit, it closes the string using \0 and returns the character.
-
-If it is digit, then it reads both real and decimal part, along with dot, closes
-the string using \0 and the returns that it found a NUMBER.
-
-Since checking of the character, happens after reading, an extra character is
-read when our condition fails (that is we have completely read the NUMBER) In
-that case, we do a ungetch, to return the character back to buffer and return
-that we found a NUMBER.
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.6_findpattern.c`
- * :c-better-explain:`Ex_5.6_findpattern.rst`
diff --git a/source/cprogramming/Ex_5.7_readlines_using_array.rst b/source/cprogramming/Ex_5.7_readlines_using_array.rst
deleted file mode 100644
index 88fdcfac..00000000
--- a/source/cprogramming/Ex_5.7_readlines_using_array.rst
+++ /dev/null
@@ -1,32 +0,0 @@
-====================================
-Exercise 5.7 - Readlines using array
-====================================
-
-Question
-========
-
-Rewrite readlines to store lines in an array supplied by main, rather than
-calling alloc to maintain storage. How much faster is the program?
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This uses the same qsort program. But instead of calculating the memory required
-using the alloc operator. It sends a predefined amount of memory from the main
-program.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.7_readlines_using_array.c`
- * :c-better-explain:`Ex_5.7_readlines_using_array.rst`
diff --git a/source/cprogramming/Ex_5.8_day_date.rst b/source/cprogramming/Ex_5.8_day_date.rst
deleted file mode 100644
index aa996ad3..00000000
--- a/source/cprogramming/Ex_5.8_day_date.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-==============================================================
-Exercise 5.8 - program which has day of the year and month day
-==============================================================
-
-Question
-========
-
-There is no error checking in day_of_year or month_day. Remedy this defect.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.8_day_date.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.8_day_date.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Given a calendar date, we will determine how many days from the start of the
-year is that date; we will also do the reverse, wherein give the days from the
-start of the year, which date and month does it fall.
-
-We define the function `int day_of_year(int year,int month,int day)` which takes
-the calendar date details like year, month and day. Using the year, it
-determines if it is leap year. A year is a leap year, if it divisible by 4 and
-but not by 100, except when it is divisible by 400. If it is leap year, we use
-29 days in feb, otherwise it is 28. We store the number of days each month in a
-static array `char daytab`, which we use in our calculations.
-
-In day_of_year, we add the days in eac month till our current month and then add
-remain days and return.
-
-In the `month_day` function, we subtract days of each month from the day, till
-the day is lesser than days in that month and then print the result that we got
-after conversion.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.8_day_date.c`
- * :c-better-explain:`Ex_5.8_day_date.rst`
diff --git a/source/cprogramming/Ex_5.9_day_date_using_pointers.rst b/source/cprogramming/Ex_5.9_day_date_using_pointers.rst
deleted file mode 100644
index c42b90cd..00000000
--- a/source/cprogramming/Ex_5.9_day_date_using_pointers.rst
+++ /dev/null
@@ -1,34 +0,0 @@
-=============================================================================
-Exercise 5.9 - program which has day of the year and month day using pointers
-=============================================================================
-
-Question
-========
-
-Rewrite the routines day_of_year and month_day with pointers instead of
-indexing.
-
-.. literalinclude:: ../../languages/cprogs/Ex_5.9_day_date_using_pointers.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_5.9_day_date_using_pointers.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-This program is same as the previous program Exercise 5.8 and we calculate the
-day of the year as before and return it to be printed in the main function.
-
-In the month_day, we send two additional pointers `int *pmonth,int *pday` and
-after calculating the number of months and days, we return it using the pointers
-itself to the main function instead of printing them in the function.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_5.9_day_date_using_pointers.c`
- * :c-better-explain:`Ex_5.9_day_date_using_pointers.rst`
diff --git a/source/cprogramming/Ex_6.1_getword.rst b/source/cprogramming/Ex_6.1_getword.rst
deleted file mode 100644
index 68e16335..00000000
--- a/source/cprogramming/Ex_6.1_getword.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-======================
-Exercise 6.1 - getword
-======================
-
-Question
-========
-
-Our version of getword does not properly handle underscores, string constants,
-comments, or preprocessor control lines. Write a better version.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.1_getword.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.1_getword.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.1_getword.c`
- * :c-better-explain:`Ex_6.1_getword.rst`
diff --git a/source/cprogramming/Ex_6.2_identical_variables.rst b/source/cprogramming/Ex_6.2_identical_variables.rst
deleted file mode 100644
index 4c141d39..00000000
--- a/source/cprogramming/Ex_6.2_identical_variables.rst
+++ /dev/null
@@ -1,30 +0,0 @@
-==================================
-Exercise 6.2 - Identical Variables
-==================================
-
-
-Question
-========
-
-Write a program that reads a C program and prints in alphabetical order each
-group of variable names that are identical in the first 6 characters, but
-different somewhere thereafter. Don't count words within strings and comments.
-Make 6 a parameter that can be set from the command line.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.2_identical_variables.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.2_identical_variables.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.2_identical_variables.c`
- * :c-better-explain:`Ex_6.2_identical_variables.rst`
diff --git a/source/cprogramming/Ex_6.3.rst b/source/cprogramming/Ex_6.3.rst
deleted file mode 100644
index bf31e59a..00000000
--- a/source/cprogramming/Ex_6.3.rst
+++ /dev/null
@@ -1,61 +0,0 @@
-===============================
-Exercise 6.3 - Cross Referencer
-===============================
-
-Question
-========
-
-Write a cross-referencer that prints a list of all words in a document, and for
-each word, a list of the line numbers on which it occurs. Remove noise words
-like ``the, and`` and so on.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.3.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.3.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Here is an example execution of this program.
-
-::
-
- This is a
- cross reference
- word
- document
- creator
- lists words and their line numbers.
- Gets the word and puts their line numbers.
- x
-
- Words with line numbers
-
- Gets :6,
- This :0,
- a :0,
- and :5,6,
- creator :4,
- cross :1,
- document :3,
- is :0,
- line :5,6,
- lists :5,
- numbers :5,6,
- puts :6,
- reference :1,
- the :6,
- their :5,6,
- word :2,6,
- words :5,
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.3.c`
- * :c-better-explain:`Ex_6.3.rst`
diff --git a/source/cprogramming/Ex_6.4.rst b/source/cprogramming/Ex_6.4.rst
deleted file mode 100644
index b71e878f..00000000
--- a/source/cprogramming/Ex_6.4.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-==================================
-Exercise 6.4 - Words and Frequency
-==================================
-
-Question
-========
-
-Write a program that prints the distinct words in its input sorted into
-decreasing order of frequency of occurrence. Precede each word by its count.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.4.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.4.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-::
-
- ab
- ab
- bc
- cd
- ef
- gh
- ab
- x
- Words and their frequencies:
- bc->1
- cd->1
- ef->1
- gh->1
- ab->3
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.4.c`
- * :c-better-explain:`Ex_6.4.rst`
diff --git a/source/cprogramming/Ex_6.5.rst b/source/cprogramming/Ex_6.5.rst
deleted file mode 100644
index 43cc6ab9..00000000
--- a/source/cprogramming/Ex_6.5.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-===========================================================
-Exercise 6.5 - undef: remove name and definition from table
-===========================================================
-
-Question
-========
-
-Write a function undef that will remove a name and definition from the table
-maintained by lookup and install.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.5.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.5.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Sample run of this program.
-
-::
-
- key1->value1
- key2->value2
- key3->value3
- key not found
- key1->value1
- key2->value2
- key not found
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.5.c`
- * :c-better-explain:`Ex_6.5.rst`
diff --git a/source/cprogramming/Ex_6.6.rst b/source/cprogramming/Ex_6.6.rst
deleted file mode 100644
index 30da0777..00000000
--- a/source/cprogramming/Ex_6.6.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-===============================
-Exercise 6.6 - define processor
-===============================
-
-Question
-========
-
-Implement a simple version of the #define processor (i.e., no arguments)
-suitable for use with C programs, based on the routines of this section. You may
-also find getch and ungetch helpful.
-
-.. literalinclude:: ../../languages/cprogs/Ex_6.6.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_6.6.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-Example output.
-
-::
-
- #define key value x
- key->value
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_6.6.c`
- * :c-better-explain:`Ex_6.6.rst`
diff --git a/source/cprogramming/Ex_7.1_lower-upper.rst b/source/cprogramming/Ex_7.1_lower-upper.rst
deleted file mode 100644
index e017181a..00000000
--- a/source/cprogramming/Ex_7.1_lower-upper.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-=========================================================
-Exercise 7.1 - upper case to lower or lower case to upper
-=========================================================
-
-Question
-========
-
-Write a program that converts upper case to lower or lower case to upper,
-depending on the name it is invoked with, as found in argv[0]
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.1_lower-upper.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.1_lower-upper.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.1_lower-upper.c`
- * :c-better-explain:`Ex_7.1_lower-upper.rst`
diff --git a/source/cprogramming/Ex_7.2_nongraphic.rst b/source/cprogramming/Ex_7.2_nongraphic.rst
deleted file mode 100644
index 6a0d50da..00000000
--- a/source/cprogramming/Ex_7.2_nongraphic.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-===================================================================
-Exercise 7.2 - print non-graphic characters in octal or hexadecimal
-===================================================================
-
-Question
-========
-
-Write a program that will print arbitrary input in a sensible way. As a minimum,
-it should print non-graphic characters in octal or hexadecimal according to
-local custom, and break long text lines.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.2_nongraphic.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.2_nongraphic.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.2_nongraphic.c`
- * :c-better-explain:`Ex_7.2_nongraphic.rst`
diff --git a/source/cprogramming/Ex_7.3_minprintf.rst b/source/cprogramming/Ex_7.3_minprintf.rst
deleted file mode 100644
index f2230fc8..00000000
--- a/source/cprogramming/Ex_7.3_minprintf.rst
+++ /dev/null
@@ -1,26 +0,0 @@
-=======================================================
-Exercise 7.3 - minprintf to handle facilities of printf
-=======================================================
-
-Question
-========
-
-Revise minprintf to handle more of the other facilities of printf.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.3_minprintf.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.3_minprintf.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.3_minprintf.c`
- * :c-better-explain:`Ex_7.3_minprintf.rst`
diff --git a/source/cprogramming/Ex_7.4.rst b/source/cprogramming/Ex_7.4.rst
deleted file mode 100644
index c8447ba2..00000000
--- a/source/cprogramming/Ex_7.4.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-=======================================
-Exercise 7.4 - private version of scanf
-=======================================
-
-
-Question
-========
-
-Write a private version of scanf analogous to minprintf from the previous
-section.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.4.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.4.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.4.c`
- * :c-better-explain:`Ex_7.4.rst`
diff --git a/source/cprogramming/Ex_7.5.rst b/source/cprogramming/Ex_7.5.rst
deleted file mode 100644
index 6145d545..00000000
--- a/source/cprogramming/Ex_7.5.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-=============================================
-Exercise 7.5 - Postfix calculator using scanf
-=============================================
-
-Question
-========
-
-Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do the
-input and number conversion.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.5.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.5.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.5.c`
- * :c-better-explain:`Ex_7.5.rst`
diff --git a/source/cprogramming/Ex_7.6.rst b/source/cprogramming/Ex_7.6.rst
deleted file mode 100644
index 3a7d6f34..00000000
--- a/source/cprogramming/Ex_7.6.rst
+++ /dev/null
@@ -1,26 +0,0 @@
-================================
-Exercise 7.6 - Compare Two files
-================================
-
-Question
-========
-
-Write a program to compare two files, printing the first line where they differ.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.6.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.6.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.6.c`
- * :c-better-explain:`Ex_7.6.rst`
diff --git a/source/cprogramming/Ex_7.7.rst b/source/cprogramming/Ex_7.7.rst
deleted file mode 100644
index b7e28eeb..00000000
--- a/source/cprogramming/Ex_7.7.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-==================================================
-Exercise 7.7 - Pattern matching program with files
-==================================================
-
-Question
-========
-
-Modify the pattern finding program of Chapter 5 to take its input from a set of
-named files or, if no files are named as arguments, from the standard input.
-Should the file name be printed when a matching line is found?
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.7.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.7.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.7.c`
- * :c-better-explain:`Ex_7.7.rst`
diff --git a/source/cprogramming/Ex_7.8.rst b/source/cprogramming/Ex_7.8.rst
deleted file mode 100644
index 0dc5915f..00000000
--- a/source/cprogramming/Ex_7.8.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-===================================
-Exercise 7.8 - Print Pages to Files
-===================================
-
-Question
-========
-
-Write a program to print a set of files, starting each new one on a new page,
-with a title and a running page count for each file.
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.8.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.8.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.8.c`
- * :c-better-explain:`Ex_7.8.rst`
diff --git a/source/cprogramming/Ex_7.9.rst b/source/cprogramming/Ex_7.9.rst
deleted file mode 100644
index 519e095d..00000000
--- a/source/cprogramming/Ex_7.9.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-=================================================
-Exercise 7.9 - Analyze implementations of isupper
-=================================================
-
-Question
-========
-
-Functions like isupper can be implemented to save space or to save time. Explore
-both possibilities.
-
-.. literalinclude:: ../../languages/cprogs/Ex_7.9.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_7.9.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_7.9.c`
- * :c-better-explain:`Ex_7.9.rst`
diff --git a/source/cprogramming/Ex_8.1_mycat.rst b/source/cprogramming/Ex_8.1_mycat.rst
deleted file mode 100644
index 8df9a607..00000000
--- a/source/cprogramming/Ex_8.1_mycat.rst
+++ /dev/null
@@ -1,26 +0,0 @@
-============================================================
-Exercise 8.1 - program cat using read, write, open and close
-============================================================
-
-Question
-========
-
-Rewrite the program cat from Chapter 7 using read, write, open, and close
-instead of their standard library equivalents. Perform experiments to determine
-the relative speeds of the two versions.
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.1_mycat.c
- :language: c
- :tab-width: 4
-
-
-Explanation
-===========
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.1_mycat.c`
- * :c-better-explain:`Ex_8.1_mycat.rst`
diff --git a/source/cprogramming/Ex_8.2.rst b/source/cprogramming/Ex_8.2.rst
deleted file mode 100644
index 0f4d7ecd..00000000
--- a/source/cprogramming/Ex_8.2.rst
+++ /dev/null
@@ -1,29 +0,0 @@
-=====================================================
-Exercise 8.2 - Rewrite fopen and _fillbuf with fields
-=====================================================
-
-Question
-========
-
-Rewrite fopen and _fillbuf with fields instead of explicit bit operations.
-Compare code size and execution speed.
-
-**inprogress**
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.2.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.2.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.2.c`
- * :c-better-explain:`Ex_8.2.rst`
diff --git a/source/cprogramming/Ex_8.3.rst b/source/cprogramming/Ex_8.3.rst
deleted file mode 100644
index dd730aa1..00000000
--- a/source/cprogramming/Ex_8.3.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-===========================================
-Exercise 8.3 - _flushbuf, fflush and fclose
-===========================================
-
-Question
-========
-
-Design and write _flushbuf, fflush, and fclose.
-
-**inprogress**
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.3.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.3.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.3.c`
- * :c-better-explain:`Ex_8.3.rst`
diff --git a/source/cprogramming/Ex_8.4.rst b/source/cprogramming/Ex_8.4.rst
deleted file mode 100644
index c24fb5f1..00000000
--- a/source/cprogramming/Ex_8.4.rst
+++ /dev/null
@@ -1,31 +0,0 @@
-==============================
-Exercise 8.4 - implement fseek
-==============================
-
-Question
-========
-
-The standard library function:
-
- ``int fseek(FILE *fp, long offset, int origin)``
-
-**inprogress**
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.4.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.4.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.4.c`
- * :c-better-explain:`Ex_8.4.rst`
diff --git a/source/cprogramming/Ex_8.5_fsize.rst b/source/cprogramming/Ex_8.5_fsize.rst
deleted file mode 100644
index fd9cd2af..00000000
--- a/source/cprogramming/Ex_8.5_fsize.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-==========================
-Exercise 8.5 - inode entry
-==========================
-
-Question
-========
-
-Modify the fsize program to print the other information contained in the inode
-entry.
-
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.5_fsize.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.5_fsize.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.5_fsize.c`
- * :c-better-explain:`Ex_8.5_fsize.rst`
diff --git a/source/cprogramming/Ex_8.6_calloc.rst b/source/cprogramming/Ex_8.6_calloc.rst
deleted file mode 100644
index 98f084b3..00000000
--- a/source/cprogramming/Ex_8.6_calloc.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-==============================================
-Exercise 8.6 - Write calloc, by calling malloc
-==============================================
-
-Question
-========
-
-The standard library function calloc(n,size) returns a pointer to n objects of
-size size, with the storage initialized to zero. Write calloc, by calling malloc
-or by modifying it.
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.6_calloc.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.6_calloc.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.6_calloc.c`
- * :c-better-explain:`Ex_8.6_calloc.rst`
diff --git a/source/cprogramming/Ex_8.7_malloc.rst b/source/cprogramming/Ex_8.7_malloc.rst
deleted file mode 100644
index e653e385..00000000
--- a/source/cprogramming/Ex_8.7_malloc.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-=======================================
-Exercise 8.7 - Error checking by malloc
-=======================================
-
-Question
-========
-
-Malloc accepts a size request without checking its plausibility; free believes
-that the block it is asked to free contains a valid size field. Improve these
-routines so they make more pains with error checking.
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.7_malloc.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.7_malloc.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.7_malloc.c`
- * :c-better-explain:`Ex_8.7_malloc.rst`
diff --git a/source/cprogramming/Ex_8.8_bfree.rst b/source/cprogramming/Ex_8.8_bfree.rst
deleted file mode 100644
index 9320d33c..00000000
--- a/source/cprogramming/Ex_8.8_bfree.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-=========================================
-Exercise 8.8 - bfree maintained by malloc
-=========================================
-
-Question
-========
-
-Write a routine bfree(p,n) that will free any arbitrary block p of n characters
-into the free list maintained by malloc and free. By using bfree, a user can add
-a static or external array to the free list at any time.
-
-.. literalinclude:: ../../languages/cprogs/Ex_8.8_bfree.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_8.8_bfree.c
- :language: c
- :codesite: ideone
-
-Explanation
-===========
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_8.8_bfree.c`
- * :c-better-explain:`Ex_8.8_bfree.rst`
diff --git a/source/cprogramming/Fibonacci.rst b/source/cprogramming/Fibonacci.rst
deleted file mode 100644
index 96e218d9..00000000
--- a/source/cprogramming/Fibonacci.rst
+++ /dev/null
@@ -1,16 +0,0 @@
-=========
-Fibonacci
-=========
-
-*Fibonacci.c*
-
-.. literalinclude:: ../../languages/cprogs/Fibonacci.c
- :language: c
- :tab-width: 4
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Fibonacci.c`
- * :c-better-explain:`Fibonacci.rst`
diff --git a/source/cprogramming/alloc_afree.rst b/source/cprogramming/alloc_afree.rst
deleted file mode 100644
index a0bfc890..00000000
--- a/source/cprogramming/alloc_afree.rst
+++ /dev/null
@@ -1,16 +0,0 @@
-===========
-alloc_afree
-===========
-
-*alloc_afree.c*
-
-.. literalinclude:: ../../languages/cprogs/alloc_afree.c
- :language: c
- :tab-width: 4
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`alloc_afree.c`
- * :c-better-explain:`alloc_afree.rst`
diff --git a/source/cprogramming/anylonglinelen.rst b/source/cprogramming/anylonglinelen.rst
deleted file mode 100644
index c579a1e3..00000000
--- a/source/cprogramming/anylonglinelen.rst
+++ /dev/null
@@ -1,16 +0,0 @@
-==============
-anylonglinelen
-==============
-
-*anylonglinelen.c*
-
-.. literalinclude:: ../../languages/cprogs/anylonglinelen.c
- :language: c
- :tab-width: 4
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`anylonglinelen.c`
- * :c-better-explain:`anylonglinelen.rst`
diff --git a/source/cprogramming/append_identifiers.py b/source/cprogramming/append_identifiers.py
deleted file mode 100644
index b4cb1d63..00000000
--- a/source/cprogramming/append_identifiers.py
+++ /dev/null
@@ -1,11 +0,0 @@
-import glob
-list_of_files = glob.glob("*.rst")
-for file_name in list_of_files:
- if file_name.startswith('Ex') or file_name.startswith('sec') or file_name == 'append_identifiers.py':
- continue
- progname = file_name.split('.')[0]
- with open(file_name, 'a') as fhandle:
- fhandle.write("\n\n\n")
- fhandle.write(".. seealso::\n\n")
- fhandle.write("\t* :c-suggest-improve:`%s.c`\n" % progname)
- fhandle.write("\t* :c-better-explain:`%s.rst`\n" % progname)
diff --git a/source/cprogramming/atoiv2.rst b/source/cprogramming/atoiv2.rst
deleted file mode 100644
index 92672e75..00000000
--- a/source/cprogramming/atoiv2.rst
+++ /dev/null
@@ -1,20 +0,0 @@
-======
-atoiv2
-======
-
-*atoiv2.c*
-
-.. literalinclude:: ../../languages/cprogs/atoiv2.c
- :language: c
- :tab-width: 4
-
-
-.. raw:: html
-
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`atoiv2.c`
- * :c-better-explain:`atoiv2.rst`
diff --git a/source/cprogramming/binsearch.rst b/source/cprogramming/binsearch.rst
deleted file mode 100644
index 18e53297..00000000
--- a/source/cprogramming/binsearch.rst
+++ /dev/null
@@ -1,16 +0,0 @@
-=========
-binsearch
-=========
-
-*binsearch.c*
-
-.. literalinclude:: ../../languages/cprogs/binsearch.c
- :language: c
- :tab-width: 4
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`binsearch.c`
- * :c-better-explain:`binsearch.rst`
diff --git a/source/cprogramming/bitcount.rst b/source/cprogramming/bitcount.rst
deleted file mode 100644
index 1360df42..00000000
--- a/source/cprogramming/bitcount.rst
+++ /dev/null
@@ -1,16 +0,0 @@
-========
-bitcount
-========
-
-*bitcount.c*
-
-.. literalinclude:: ../../languages/cprogs/bitcount.c
- :language: c
- :tab-width: 4
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`bitcount.c`
- * :c-better-explain:`bitcount.rst`
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c b/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c
similarity index 98%
rename from source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c
rename to source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c
index 14d434b4..f2562e6f 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c
@@ -2,8 +2,7 @@
* Exercise 1.10 - Write a Program to copy its input to its output,
* replacing each tab by \t, each backspace by \b, and each backslash by \\.
* This makes tabs and backspaces visible in an unambiguous way.
- *
- * */
+ **/
#include
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.13.2_His_vertical.c b/source/cprogramming/chapter1/cprogs/ex_1.13.2_his_vertical.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.13.2_His_vertical.c
rename to source/cprogramming/chapter1/cprogs/ex_1.13.2_his_vertical.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.13_His_Horizontal.c b/source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.13_His_Horizontal.c
rename to source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.14_Hist_Freq.c b/source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.14_Hist_Freq.c
rename to source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c
similarity index 81%
rename from source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c
rename to source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c
index a2f85045..e3cddba6 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c
@@ -6,14 +6,15 @@
*
**/
-#include < stdio.h >
+#include
#define LOWER 0
#define UPPER 300
#define STEP 20
-void fahrtocelsius(void);
-void celsiustofahr(void);
+void fahr_to_celsius(void);
+
+void celsius_to_fahr(void);
int main(void) {
int c;
@@ -26,23 +27,23 @@ int main(void) {
c = getchar();
if (c == '1')
- fahrtocelsius();
+ fahr_to_celsius();
else if (c == '2')
- celsiustofahr();
+ celsius_to_fahr();
else
printf("Invalid Choice\n");
return 0;
}
-void fahrtocelsius() {
+void fahr_to_celsius() {
float fahr;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
printf("%3.0f%6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32.0));
}
-void celsiustofahr() {
+void celsius_to_fahr() {
float celsius;
for (celsius = LOWER; celsius <= UPPER; celsius = celsius + STEP)
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c
similarity index 84%
rename from source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c
rename to source/cprogramming/chapter1/cprogs/ex_1.16_longline.c
index 594b8073..40be31e5 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c
@@ -12,8 +12,9 @@
#define MAX 1000
/* define our functions*/
-int getNewLine(char line[], int max);
-void copy(char to[], char from[]);
+int get_line(char arr[], int lim);
+
+void copy(char to[], const char from[]);
int main() {
@@ -22,7 +23,7 @@ int main() {
char longest[MAX];
max = 0;
- while ((len = getNewLine(line, MAX)) > 0) {
+ while ((len = get_line(line, MAX)) > 0) {
if (len > max) {
@@ -40,7 +41,7 @@ int main() {
}
/* get a line in a character array */
-int getNewLine(char arr[], int lim) {
+int get_line(char arr[], int lim) {
int c, i;
@@ -53,9 +54,7 @@ int getNewLine(char arr[], int lim) {
arr[i] = c;
++i;
- }
-
- else {
+ } else {
/* Continue to count the length even if it is longer than the max */
while ((c = getchar() != EOF) && c != '\n') {
@@ -75,7 +74,7 @@ int getNewLine(char arr[], int lim) {
}
/* copy one character array to another */
-void copy(char to[], char from[]) {
+void copy(char to[], const char from[]) {
int i;
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c
similarity index 67%
rename from source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c
rename to source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c
index 16db88ae..5873a15f 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c
@@ -12,18 +12,18 @@
/***
*
- * We call it ngetline, for new getline so that it does not conflict with
+ * We call it _getline, for new getline so that it does not conflict with
* system function getline
*
***/
-int ngetline(char line[], int lim);
+int _getline(char line[], int lim);
int main(void) {
int len;
char line[MAXLINE];
- while ((len = ngetline(line, MAXLINE)) > 0) {
+ while ((len = _getline(line, MAXLINE)) > 0) {
if (len > LIMIT)
printf("%s", line);
}
@@ -31,17 +31,17 @@ int main(void) {
return 0;
}
-int ngetline(char s[], int lim) {
+int _getline(char line[], int lim) {
int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
+ line[i] = c;
if (c == '\n') {
- s[i] = c;
+ line[i] = c;
++i;
}
- s[i] = '\0';
+ line[i] = '\0';
return i;
}
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c b/source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c
similarity index 57%
rename from source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c
rename to source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c
index 76f20e98..4728c4a9 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c
@@ -9,52 +9,50 @@
#define MAXLINE 1000
-int mgetline(char line[], int lim);
-int removetrail(char rline[]);
+int _getline(char line[], int lim);
+
+int remove_trail(char rline[]);
int main(void) {
int len;
char line[MAXLINE];
- while ((len = mgetline(line, MAXLINE)) > 0)
- if (removetrail(line) > 0)
+ while ((len = _getline(line, MAXLINE)) > 0)
+ if (remove_trail(line) > 0)
printf("%s", line);
return 0;
}
-int mgetline(char s[], int lim) {
+int _getline(char line[], int lim) {
int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
+ line[i] = c;
if (c == '\n') {
- s[i] = c;
+ line[i] = c;
++i;
}
- s[i] = '\0';
+ line[i] = '\0';
return i;
}
/* To remove Trailing Blanks,tabs. Go to End and proceed backwards removing */
-
-int removetrail(char s[]) {
+int remove_trail(char rline[]) {
int i;
- for (i = 0; s[i] != '\n'; ++i)
- ;
+ for (i = 0; rline[i] != '\n'; ++i);
--i; /* To consider raw line without \n */
- for (i > 0; ((s[i] == ' ') || (s[i] == '\t')); --i)
- ; /* Removing the Trailing Blanks and Tab Spaces */
+ for (i > 0; ((rline[i] == ' ') || (rline[i] == '\t')); --i); /* Removing the Trailing Blanks and Tab Spaces */
if (i >= 0) /* Non Empty Line */
{
++i;
- s[i] = '\n';
+ rline[i] = '\n';
++i;
- s[i] = '\0';
+ rline[i] = '\0';
}
return i;
}
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c b/source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c
similarity index 77%
rename from source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c
rename to source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c
index c5ea33e9..bf9509bf 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c
@@ -8,7 +8,7 @@
#define MAXLINE 1000
-int mgetline(char line[], int lim);
+int _getline(char line[], int lim);
void reverse(char rline[]);
@@ -16,7 +16,7 @@ int main(void) {
int len;
char line[MAXLINE];
- while ((len = mgetline(line, MAXLINE)) > 0) {
+ while ((len = _getline(line, MAXLINE)) > 0) {
reverse(line);
printf("%s", line);
}
@@ -24,17 +24,17 @@ int main(void) {
return 0;
}
-int mgetline(char s[], int lim) {
+int _getline(char line[], int lim) {
int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
+ line[i] = c;
if (c == '\n') {
- s[i] = c;
+ line[i] = c;
++i;
}
- s[i] = '\0';
+ line[i] = '\0';
return i;
}
@@ -43,8 +43,7 @@ void reverse(char rline[]) {
int i, j;
char temp;
- for (i = 0; rline[i] != '\0'; ++i)
- ;
+ for (i = 0; rline[i] != '\0'; ++i);
--i;
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c
similarity index 96%
rename from source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c
rename to source/cprogramming/chapter1/cprogs/ex_1.20_detab.c
index 92331121..952abf99 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c
@@ -1,9 +1,8 @@
/**
- * Exercise 1.20 -
+ * Exercise 1.20
*
* Write a Program detab, which replaces tabs in the input with a proper
* number of blanks to spaces
- *
**/
#include
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.21_entab.c b/source/cprogramming/chapter1/cprogs/ex_1.21_entab.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.21_entab.c
rename to source/cprogramming/chapter1/cprogs/ex_1.21_entab.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c
similarity index 89%
rename from source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c
rename to source/cprogramming/chapter1/cprogs/ex_1.22_fold.c
index db7d58a1..2a558507 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c
@@ -1,7 +1,3 @@
-/* Exercise 1-22: Write a program to "fold" long input lines into two or more
- shorter lines after the last non-blank character that occurs
- before the n-th column of input. */
-
#include
#define MAXCOL 35 /* folded line length */
@@ -9,7 +5,18 @@
#define CURTAB(c) (TABVAL - ((c) % TABVAL)) /* current tab size */
#define NO_BLANK -1 /* signifies no blank found */
-int lastblank(const char arr[], int len);
+/* finds the last whitespace character in an array
+ and returns the position */
+int lastblank(const char arr[], int len) {
+ int i, lbc;
+
+ lbc = -1;
+ for (i = 0; i < len; ++i)
+ if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n')
+ lbc = i;
+
+ return lbc;
+}
/* folds long input lines into two or more shorter lines */
int main(void) {
@@ -55,17 +62,4 @@ int main(void) {
}
return 0;
-}
-
-/* finds the last whitespace character in an array
- and returns the position */
-int lastblank(const char arr[], int len) {
- int i, lbc;
-
- lbc = -1;
- for (i = 0; i < len; ++i)
- if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n')
- lbc = i;
-
- return lbc;
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c b/source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c
similarity index 99%
rename from source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c
rename to source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c
index 34956ba6..547dc0e1 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c
@@ -10,7 +10,9 @@
#include
void rcomment(int c);
+
void incomment(void);
+
void echo_quote(int c);
int main(void) {
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c
similarity index 99%
rename from source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c
rename to source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c
index dc2c52b2..f07012f7 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c
@@ -12,7 +12,9 @@
int brace, brack, paren;
void incomment();
+
void inquote(int c);
+
void search(int c);
int main(void) {
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.3_fahr2celheading.c b/source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.3_fahr2celheading.c
rename to source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.4_cel2fahr.c b/source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.4_cel2fahr.c
rename to source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c
similarity index 89%
rename from source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c
rename to source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c
index 6600ca08..1bf08ff7 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c
@@ -20,7 +20,7 @@ int main(void) {
celsius = upper;
while (celsius >= lower) {
- fahr = (float)((9.0 / 5.0) * celsius + 32.0);
+ fahr = (float) ((9.0 / 5.0) * celsius + 32.0);
printf("%3.0f %6.1f\n", celsius, fahr);
celsius = celsius - step;
}
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.6_verifyeof.c b/source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.6_verifyeof.c
rename to source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.7_eofval.c b/source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.7_eofval.c
rename to source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.8_count_blanks_etc.c b/source/cprogramming/chapter1/cprogs/ex_1.8_count_blanks_etc.c
similarity index 100%
rename from source/cprogramming/chapter1/cprogs/Ex_1.8_count_blanks_etc.c
rename to source/cprogramming/chapter1/cprogs/ex_1.8_count_blanks_etc.c
diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c
similarity index 97%
rename from source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c
rename to source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c
index 037bb705..904081c8 100644
--- a/source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c
+++ b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c
@@ -1,8 +1,7 @@
/**
* Exercise 1.9 - Write a Program to copy its input to its output, replacing
* each string of one or more blanks by a single blank.
- *
- * */
+ **/
#include
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c
index ea4eec5b..44023f89 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c
@@ -1,17 +1,42 @@
#include
+
#define MAXLINE 1000 /* maximum input line size */
+
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
-int getline(void);
-void copy(void);
+
+
+/* copy: specialized version */
+void copy(void) {
+ int i;
+ extern char line[], longest[];
+ i = 0;
+ while ((longest[i] = line[i]) != '\0')
+ ++i;
+}
+
+/* getline: specialized version */
+int mgetline(void) {
+ int c, i;
+ extern char line[];
+ for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = c;
+ if (c == '\n') {
+ line[i] = c;
+ ++i;
+ }
+ line[i] = '\0';
+ return i;
+}
+
/* print longest input line; specialized version */
-main() {
+int main() {
int len;
extern int max;
extern char longest[];
max = 0;
- while ((len = getline()) > 0)
+ while ((len = mgetline()) > 0)
if (len > max) {
max = len;
copy();
@@ -19,26 +44,4 @@ main() {
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
-}
-/* getline: specialized version */
-int getline(void) {
- int c, i;
- extern char line[];
- for (i = 0; i < MAXLINE - 1 && (c = getchar))
- != EOF &&c != '\n'; ++i)
-line[i] = c;
- if (c == '\n') {
- line[i] = c;
- ++i;
- }
- line[i] = '\0';
- return i;
-}
-/* copy: specialized version */
-void copy(void) {
- int i;
- extern char line[], longest[];
- i = 0;
- while ((longest[i] = line[i]) != '\0')
- ++i;
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c b/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c
index ae683a3f..412103bd 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c
@@ -2,4 +2,6 @@
#include
-int main() { printf("hello, world\n"); }
+int main() {
+ printf("hello, world\n");
+}
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c
index 9f65d56b..926d982b 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c
@@ -1,6 +1,7 @@
#include
+
/* print Fahrenheit-Celsius table */
-main() {
+int main() {
int fahr;
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c b/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c
index 192f6556..c188f89b 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c
@@ -1,8 +1,9 @@
#include
-#define LOWER 0 /* lower limit of table */
-#define UPPER 300 /* upper limit */
-#define STEP 20 /* step size */
-/* print Fahrenheit-Celsius table */
+
+#define LOWER 0
+#define UPPER 300
+#define STEP 20
+
int main() {
int fahr;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c b/source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c
similarity index 99%
rename from source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c
rename to source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c
index ed63fb8e..04f2e966 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c
@@ -1,4 +1,5 @@
#include
+
int main() {
int c;
c = getchar();
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c
similarity index 91%
rename from source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c
rename to source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c
index d997f4f7..87264ab9 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c
@@ -1,6 +1,7 @@
#include
+
/* count characters in input; 1st version */
-main() {
+int main() {
long nc;
nc = 0;
while (getchar() != EOF)
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c
similarity index 64%
rename from source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c
rename to source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c
index 302ab6fa..8ec8df2f 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c
@@ -1,8 +1,8 @@
#include
+
/* count characters in input; 2nd version */
-main() {
+int main() {
double nc;
- for (nc = 0; getchar() != EOF; ++nc)
- ;
+ for (nc = 0; getchar() != EOF; ++nc);
printf("%.0f\n", nc);
}
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c
index 90c1eddb..907a5084 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c
@@ -1,6 +1,7 @@
#include
+
/* count lines in input */
-main() {
+int main() {
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c
index aede6112..5bfe4801 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c
@@ -1,8 +1,10 @@
#include
+
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
+
/* count lines, words, and characters in input */
-main() {
+int main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c
index ed63fb8e..04f2e966 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c
@@ -1,4 +1,5 @@
#include
+
int main() {
int c;
c = getchar();
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c b/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c
index c26199cc..20bd0dd3 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c
@@ -1,6 +1,7 @@
#include
+
/* count digits, white space, others */
-main() {
+int main() {
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c
index 34c7a283..c8db6ff5 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c
@@ -1,12 +1,15 @@
#include
-int power(int m, int n);
+
+int power(int base, int n);
+
/* test power function */
-main() {
+int main() {
int i;
for (i = 0; i < 10; ++i)
printf("%d %d %d\n", i, power(2, i), power(-3, i));
return 0;
}
+
/* power: raise base to n-th power; n >= 0 */
int power(int base, int n) {
int i, p;
@@ -14,4 +17,4 @@ int power(int base, int n) {
for (i = 1; i <= n; ++i)
p = p * base;
return p;
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c b/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c
index 67a04bb8..70b9814a 100644
--- a/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c
+++ b/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c
@@ -1,9 +1,13 @@
#include
+
#define MAXLINE 1000 /* maximum input line length */
+
int mgetline(char line[], int maxline);
+
void copy(char to[], char from[]);
+
/* print the longest input line */
-main() {
+int main() {
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
@@ -18,18 +22,20 @@ main() {
printf("%s", longest);
return 0;
}
-/* mgetline: read a line into s, return length */
-int mgetline(char s[], int lim) {
+
+/* mgetline: read a line into line, return length */
+int mgetline(char line[], int maxline) {
int c, i;
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
+ for (i = 0; i < maxline - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = c;
if (c == '\n') {
- s[i] = c;
+ line[i] = c;
++i;
}
- s[i] = '\0';
+ line[i] = '\0';
return i;
}
+
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[]) {
int i;
diff --git a/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst
index 6eb9223b..8beeb648 100644
--- a/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst
+++ b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst
@@ -12,7 +12,7 @@ visible in an unambiguous way.
Solution
--------
-.. literalinclude:: cprogs/ex_1.10_TbsBlnkSpaces.c
+.. literalinclude:: cprogs/ex_1.10_tbsblnkspaces.c
:language: c
Explanation
diff --git a/source/cprogramming/chapter1/ex_1.11_test_word_count.rst b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst
index baf4e935..2d97340e 100644
--- a/source/cprogramming/chapter1/ex_1.11_test_word_count.rst
+++ b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst
@@ -29,5 +29,4 @@ consisting of \n, or a file entirely consisting of \t character or a empty file.
For invalid Inputs, an unclosed file which does not have EOF, which is tricky to
provide can be given to this program. A unicode character file can be given and
-see if getchar() handles it properly. We tested it and it works.
-
+see if getchar() handles it properly. We tested it and it works.
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst
index 8c215fd1..d6e122e6 100644
--- a/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst
+++ b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst
@@ -12,7 +12,7 @@ the histogram with the bars vertical.
Solution
--------
-.. literalinclude:: cprogs/ex_1.13.2_His_vertical.c
+.. literalinclude:: cprogs/ex_1.13.2_his_vertical.c
:language: c
@@ -88,4 +88,4 @@ we will have hit the bottom of the histogram::
'*''*''*''*'
-Combing them all, we would have drawn the horizontal histogram like above.
+Combing them all, we would have drawn the horizontal histogram like above.
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/ex_1.15_tempconv.rst b/source/cprogramming/chapter1/ex_1.15_tempconv.rst
index fdbf52de..19ae98e1 100644
--- a/source/cprogramming/chapter1/ex_1.15_tempconv.rst
+++ b/source/cprogramming/chapter1/ex_1.15_tempconv.rst
@@ -23,7 +23,7 @@ In this program we are going to convert a given Fahrenheit temperature to
Celsius or Celsius temperature to Fahrenheit temperature using the formula
C=(5/9)(F-32 ). We retain most of the program from section 1.4. In addition
This program contains functions such as fahrtocelsius and celsiustofhar. The
-functions fahrtocelsius and celsiustofhar are used to make the program more
+functions fahr_to_celsius and celsiustofhar are used to make the program more
dynamic by giving choices to the users for conversion between 1 - Fahrenheit to
Celsius Conversion 2 - Celsius to Fahrenheit Converion.
diff --git a/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst
index 8ab84be1..10d63943 100644
--- a/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst
+++ b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst
@@ -18,7 +18,7 @@ Solution
Explanation
===========
-In the removetrail function, we go to the very end of the line and the trace
+In the remove_trail function, we go to the very end of the line and the trace
back to the find the character which is not a space, tab and then replace it
with \0. This eliminates the trailing blanks in a line. For the empty lines
whose length is 0, we simply skip that from output and thus removing it.
diff --git a/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst
index 39bc7f81..cd641c13 100644
--- a/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst
+++ b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst
@@ -46,4 +46,3 @@ error.
::
error: expected `;` before the '}' token
-
diff --git a/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst
index 7e3a1828..2915cf1f 100644
--- a/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst
+++ b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst
@@ -8,7 +8,6 @@ Question
Modify the temperature conversion program to print a heading above the table.
-
Solution
--------
@@ -16,13 +15,13 @@ Solution
:language: c
Explanation
-===========
+-----------
In this program we are going to convert a given Fahrenheit temperature to
Celsius temperature using the formula C=(5/9)(F-32) To do this we declare some
variables in the beginning of the program so that they can be used in the later
stages of the program. The variables in this program are: lower,upper,step,
-celsius,fahr. The variable lower is assigned the value 0 similarly upper to 300,
-step to 20, and fahr to lower. So when the program enters the while loop it
-checks whether fahr <= upper is true, if it is true then it assigns the variable
-celsius 5 * (fahr - 32) / 9 and then it prints output.
+celsius,fahr. The variable lower is assigned the value 0 similarly upper to
+300, step to 20, and fahr to lower. So when the program enters the while loop
+it checks whether fahr <= upper is true, if it is true then it assigns the
+variable celsius 5 * (fahr - 32) / 9 and then it prints output.
diff --git a/source/cprogramming/chapter1/ex_1.6_verifyeof.rst b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst
index 4370f11b..81240918 100644
--- a/source/cprogramming/chapter1/ex_1.6_verifyeof.rst
+++ b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst
@@ -14,7 +14,7 @@ Solution
:language: c
Explanation
-===========
+-----------
1. This program is similar to the previous one Ex 1.5, wherein after it gets the
input, it prints the value of the expression getchar() != EOF.
diff --git a/source/cprogramming/chapter1/index.rst b/source/cprogramming/chapter1/index.rst
index c6552b4f..5a19106a 100644
--- a/source/cprogramming/chapter1/index.rst
+++ b/source/cprogramming/chapter1/index.rst
@@ -8,7 +8,6 @@ Chapter 1
sec_1.1_helloworld
ex_1.1_exp_helloworld
sec_1.2_fahr2cel
- ex_1.2_exp_printf_c
sec_1.3_for_loop
ex_1.3_fahr2celheading
sec_1.4_symbolic
@@ -30,7 +29,6 @@ Chapter 1
sec_1.10_external_variables
ex_1.10_tbsblnkspaces
ex_1.11_test_word_count
- ex_1.12_word_per_line
ex_1.13.2_his_vertical
ex_1.13_his_horizontal
ex_1.14_hist_freq
@@ -43,4 +41,4 @@ Chapter 1
ex_1.21_entab
ex_1.22_fold
ex_1.23_remcomments
- ex_1.24_synerrors
+ ex_1.24_synerrors
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/sec_1.1_helloworld.rst b/source/cprogramming/chapter1/sec_1.1_helloworld.rst
index 136f2695..462db5d7 100644
--- a/source/cprogramming/chapter1/sec_1.1_helloworld.rst
+++ b/source/cprogramming/chapter1/sec_1.1_helloworld.rst
@@ -20,11 +20,11 @@ Solution
.. literalinclude:: cprogs/sec_1.1_helloworld.c
:language: c
+Extras
+======
-Visualize It
-============
+What really happens when you run hello world program?
-.. raw:: html
-
-
+Peek into the assembly code and jmps that happen with hello world as
+demonstrated in this article https://thecoder08.github.io/hello-world.html
diff --git a/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst b/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst
index 159c24c6..6ae4202a 100644
--- a/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst
+++ b/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst
@@ -31,16 +31,3 @@ The variable lower is assigned the value 0 similarly upper to 300, step to 20,
and fahr to lower. So when the program enters the while loop it checks whether
fahr <= upper is true if it is true then it assigns the variable celsius 5 *
(fahr - 32) / 9 and then it prints out put.
-
-
-Understand
-----------
-
-.. raw:: html
-
-
-
-
-----
-
- Last Updated |today|
diff --git a/source/cprogramming/chapter1/sec_1.4_symbolic.rst b/source/cprogramming/chapter1/sec_1.4_symbolic.rst
index 778dda5e..481b9b75 100644
--- a/source/cprogramming/chapter1/sec_1.4_symbolic.rst
+++ b/source/cprogramming/chapter1/sec_1.4_symbolic.rst
@@ -20,8 +20,4 @@ to 300, STEP to 20. So when the program enters the for loop it checks whether
fahr <= UPPER, and the increments fahr using STEP in each iteration.
*symbolic constants* are substituted inline in the program during pre-processing
-phase of compilation.
-
-----
-
-This document was updated on |today|
+phase of compilation.
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst b/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst
index 0dafc13f..f0ec240f 100644
--- a/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst
+++ b/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst
@@ -7,11 +7,4 @@ Program
.. literalinclude:: cprogs/sec_1.5.1_file_copying.c
- :language: c
-
-Explanation
------------
-
-----
-
-This document was updated on |today|
+ :language: c
\ No newline at end of file
diff --git a/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst b/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst
index a1e41940..c9719190 100644
--- a/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst
+++ b/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst
@@ -7,7 +7,7 @@ Program
-------
-.. literalinclude:: cprogs/sec_1.5.2_Character_Counting.c
+.. literalinclude:: cprogs/sec_1.5.2_character_counting.c
:language: c
Explanation
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c
deleted file mode 100644
index f54afa55..00000000
--- a/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/***
- *
- * Exercise 2.1
- *
- * Program to print maximum, minimum limits of char, int, long using
- * calculation
- *
- ***/
-
-/* The logic used is
- * ~0 will give bits in 1s.
- * (unsigned ) will cast it unsigned.
- * >> 1 right shifts 1 bit to remove the sign bit.
- * () casting it the required type again
- */
-
-#include
-#include
-#include
-
-int main() {
- /* ranges of various floating-point types through calculation */
- printf("Ranges of various floating-point types through calculation:\n");
-
- printf("Minimum Signed Char %d\n", -(char)((unsigned char)~0 >> 1) - 1);
- printf("Maximum Signed Char %d\n", (char)((unsigned char)~0 >> 1));
-
- printf("Minimum Signed Short %d\n", -(short)((unsigned short)~0 >> 1) - 1);
- printf("Maximum Signed Short %d\n", (short)((unsigned short)~0 >> 1));
-
- printf("Minimum Signed Int %d\n", -(int)((unsigned int)~0 >> 1) - 1);
- printf("Maximum Signed Int %d\n", (int)((unsigned int)~0 >> 1));
-
- printf("Minimum Signed Long %ld\n", -(long)((unsigned long)~0 >> 1) - 1);
- printf("Maximum signed Long %ld\n", (long)((unsigned long)~0 >> 1));
-
- /* Unsigned Maximum Values */
-
- printf("Maximum Unsigned Char %d\n", (unsigned char)~0);
- printf("Maximum Unsigned Short %d\n", (unsigned short)~0);
- printf("Maximum Unsigned Int %u\n", (unsigned int)~0);
- printf("Maximum Unsigned Long %lu\n\n", (unsigned long)~0);
-
- /* ranges of various floating-point types from standard headers */
- printf("Ranges of various floating-point types from standard headers:\n");
- printf("Minimum Signed Char %d\n", SCHAR_MIN);
- printf("Maximum Signed Char %d\n", SCHAR_MAX);
-
- printf("Minimum Signed Short %d\n", SHRT_MIN);
- printf("Maximum Signed Short %d\n", SHRT_MAX);
-
- printf("Minimum Signed Int %d\n", INT_MIN);
- printf("Maximum Signed Int %d\n", INT_MAX);
-
- printf("Minimum Signed Long %ld\n", LONG_MIN);
- printf("Maximum signed Long %ld\n", LONG_MAX);
-
- /* Unsigned Maximum Values */
-
- printf("Maximum Unsigned Char %d\n", UCHAR_MAX);
- printf("Maximum Unsigned Short %d\n", USHRT_MAX);
- printf("Maximum Unsigned Int %u\n", UINT_MAX);
- printf("Maximum Unsigned Long %lu\n", ULONG_MAX);
-
- return 0;
-}
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c b/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c
deleted file mode 100644
index 0950c32a..00000000
--- a/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Exercise 2.3 - htoi program, character to integer program.
- *
- */
-
-#include
-#define MAXLINE 100
-
-#define YES 1
-#define NO 0
-
-int mgetline(char line[], int maxline);
-int htoi(char s[]);
-
-int main(void) {
- char line[MAXLINE];
- int value;
-
- mgetline(line, MAXLINE);
- value = htoi(line);
-
- printf("The value of %s is %d", line, value);
-
- return 0;
-}
-
-int mgetline(char s[], int lim) {
- int c, i;
-
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n') {
- s[i] = c;
- ++i;
- }
- s[i] = '\0';
-
- return i;
-}
-
-int htoi(char s[]) {
- int hexdigit, i, inhex, n;
- i = 0;
- if (s[i] == '0') {
- ++i;
- if (s[i] == 'x' || s[i] == 'X')
- ++i;
- }
-
- n = 0;
- inhex = YES;
-
- for (; inhex == YES; ++i) {
- if (s[i] >= '0' && s[i] <= '9')
- hexdigit = s[i] - '0';
- else if (s[i] >= 'a' && s[i] <= 'f')
- hexdigit = s[i] - 'a' + 10;
- else if (s[i] >= 'A' && s[i] <= 'F')
- hexdigit = s[i] - 'A' + 10;
- else
- inhex = NO;
-
- if (inhex == YES)
- n = 16 * n + hexdigit;
- }
- return n;
-}
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c
deleted file mode 100644
index 42f415f4..00000000
--- a/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Exercise 2.5
- *
- * Write the function any(s1,s2) which returns the first location in the string
- * s1 where any character from the string s2 occurs, or -1 if s1 contains
- * no characters from s2. ( The standard library function strpbrk does
- * the same job but retuns a pointer to the location
- *
- **/
-
-#include
-#define MAXLINE 1000
-
-int mgetline(char line[], int maxline);
-int any(char s1[], char s2[]);
-
-int main(void) {
- char s1[MAXLINE], s2[MAXLINE];
- int val;
-
- /* Give the first string s1 */
-
- mgetline(s1, MAXLINE);
-
- /* Give the second string s2 */
-
- mgetline(s2, MAXLINE);
-
- val = any(s1, s2);
-
- printf("%d", val);
-
- return 0;
-}
-
-int mgetline(char s[], int lim) {
- int i, c;
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n')
- s[i++] = c;
- s[i] = '\0';
-}
-
-int any(char s1[], char s2[]) {
- int i, j;
-
- for (i = 0; s1[i] != '\0'; ++i) {
- // iterate through s2 while trying to find matching character from s1
- for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j)
- ; // continue
-
- if (s2[j] != '\0' &&
- s2[j] != '\n') { // check that s2 [j]! = '\n', since s1 and s2 both
- // have the character '\n' in the penultimate
- // position of the string.
- return i;
- }
- }
-
- return -1;
-}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c
deleted file mode 100644
index f3cb0607..00000000
--- a/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- *
- * Exercise 2.6 - Write a function setbits(x,p,n,y) that returns x with the
- * n bits that begin at positionp set to the rightmost n bits of y,leaving
- * the other bits unchanged.
- **/
-
-#include
-
-unsigned setbits(unsigned x, int p, int n, unsigned y);
-
-int main(void) { printf("%u", setbits((unsigned)12, 3, 2, (unsigned)57)); }
-
-unsigned setbits(unsigned x, int p, int n, unsigned y) {
- return x & ~(~(~0 << n) << (p + 1 - n)) | (y & (~(~0 << n)) << (p + 1 - n));
-}
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.10_lowercondit.c b/source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c
similarity index 100%
rename from source/cprogramming/chapter2/cprogs/Ex_2.10_lowercondit.c
rename to source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c
diff --git a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c
new file mode 100644
index 00000000..053cbf30
--- /dev/null
+++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c
@@ -0,0 +1,93 @@
+/**
+ * Exercise 2.1
+ *
+ * Write a program to print maximum, minimum limits of char, int, long using
+ * calculation.
+ *
+ */
+
+/**
+ * Preliminary Information:
+ *
+ * ~0 will give bits in 1s.
+ * >> 1 right shift by 1 bit to remove the sign bit.
+ * -1 is added to the maximum limit to get the minimum limit.
+ *
+ * The maximum and minimum limits of various integer types can be calculated
+ * using the following logic:
+ *
+ * 1. The maximum limit of a signed integer type can be calculated by
+ * (unsigned ) ~0 >> 1
+ *
+ * 2. The minimum limit of a signed integer type can be calculated by
+ * ((unsigned ) ~0 >> 1) - 1
+ * *
+ * 3. We cast it back to the required type with sign to print the value.
+ *
+ */
+
+#include
+#include
+#include
+
+int main() {
+ /* ranges of various integer types through calculation */
+ printf("Ranges of various integer types through calculation:\n");
+
+ printf("Minimum Signed Char %d\n", -(int)((unsigned char)~0 >> 1) - 1);
+ printf("Maximum Signed Char %d\n", (int)((unsigned char)~0 >> 1));
+
+ printf("Minimum Signed Short %d\n", -(int)((unsigned short)~0 >> 1) - 1);
+ printf("Maximum Signed Short %d\n", (int)((unsigned short)~0 >> 1));
+
+ printf("Minimum Signed Int %d\n", -(int)((unsigned int)~0 >> 1) - 1);
+ printf("Maximum Signed Int %d\n", (int)((unsigned int)~0 >> 1));
+
+ printf("Minimum Signed Long %ld\n", -(long)((unsigned long)~0 >> 1) - 1);
+ printf("Maximum signed Long %ld\n", (long)((unsigned long)~0 >> 1));
+
+ /* Unsigned Maximum Values */
+
+ printf("Maximum Unsigned Char %d\n", (unsigned char)~0);
+ printf("Maximum Unsigned Short %d\n", (unsigned short)~0);
+ printf("Maximum Unsigned Int %u\n", (unsigned int)~0);
+ printf("Maximum Unsigned Long %lu\n\n", (unsigned long)~0UL);
+
+ /* Calculating max values of float types can be tricky, we can use the standard headers */
+
+ /* ranges of various floating-point types from standard headers */
+ printf("Ranges of various integer and floating-point types from standard headers:\n");
+ printf("Minimum Signed Char %d\n", SCHAR_MIN);
+ printf("Maximum Signed Char %d\n", SCHAR_MAX);
+
+ printf("Minimum Signed Short %d\n", SHRT_MIN);
+ printf("Maximum Signed Short %d\n", SHRT_MAX);
+
+ printf("Minimum Signed Int %d\n", INT_MIN);
+ printf("Maximum Signed Int %d\n", INT_MAX);
+
+ printf("Minimum Signed Long %ld\n", LONG_MIN);
+ printf("Maximum signed Long %ld\n", LONG_MAX);
+
+ printf("Minimum Signed Long Long %lld\n", LLONG_MIN);
+ printf("Maximum Signed Long Long %lld\n", LLONG_MAX);
+
+ printf("Minimum Float %E\n", FLT_MIN);
+ printf("Maximum Float %E\n", FLT_MAX);
+
+ printf("Minimum Double %E\n", DBL_MIN);
+ printf("Maximum Double %E\n", DBL_MAX);
+
+ printf("Minimum Long Double %LE\n", LDBL_MIN);
+ printf("Maximum Long Double %LE\n", LDBL_MAX);
+
+ /* Unsigned Maximum Values */
+
+ printf("Maximum Unsigned Char %d\n", UCHAR_MAX);
+ printf("Maximum Unsigned Short %d\n", USHRT_MAX);
+ printf("Maximum Unsigned Int %u\n", UINT_MAX);
+ printf("Maximum Unsigned Long %lu\n", ULONG_MAX);
+ printf("Maximum Unsigned Long Long %llu\n", ULLONG_MAX);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c b/source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c
similarity index 81%
rename from source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c
rename to source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c
index d1f24233..f0f4539f 100644
--- a/source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c
+++ b/source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c
@@ -7,10 +7,12 @@
**/
#include
+
#define MAXLINE 1000
int mgetline(char line[], int lim);
-void copy(char to[], char from[]);
+
+void copy(char to[], const char from[]);
int main(void) {
int len, max;
@@ -29,7 +31,7 @@ int main(void) {
printf("%s", maxline);
}
-int mgetline(char s[], int lim) {
+int mgetline(char line[], int lim) {
int i, c;
for (i = 0; i < lim - 1; ++i) {
@@ -38,19 +40,19 @@ int mgetline(char s[], int lim) {
break;
if (c == '\n')
break;
- s[i] = c;
+ line[i] = c;
}
if (c == '\n') {
- s[i] = c;
+ line[i] = c;
++i;
}
- s[i] = '\0';
+ line[i] = '\0';
return i;
}
-void copy(char to[], char from[]) {
+void copy(char to[], const char from[]) {
int i;
i = 0;
diff --git a/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c
new file mode 100644
index 00000000..e3c19907
--- /dev/null
+++ b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c
@@ -0,0 +1,62 @@
+/**
+ * Exercise 2.3 - htoi program, character to integer program.
+ *
+ */
+
+#include
+
+#define MAXLINE 100
+#define BASE 16
+
+int mgetline(char line[], int lim);
+
+unsigned int htoi(const char s[], int len);
+
+int main(void) {
+ char line[MAXLINE];
+ int len;
+ unsigned int value;
+
+ len = mgetline(line, MAXLINE);
+ value = htoi(line, len);
+
+ printf("The value of %s is %u \n", (char *) line, value);
+
+ return 0;
+}
+
+int mgetline(char line[], int lim) {
+ int c, i;
+
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = (char) c;
+
+ line[i] = '\0';
+
+ return i;
+}
+
+unsigned int htoi(const char s[], int len) {
+ int digit;
+ int power = 1;
+ unsigned int result = 0;
+ int end_index = 0;
+
+ if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
+ end_index = 2;
+ }
+
+ for(int i=len-1; i>=end_index; i--) {
+ if (s[i] >= '0' && s[i] <= '9') {
+ digit = (s[i] - '0');
+ } else if (s[i] >= 'a' && s[i] <= 'f') {
+ digit = (s[i] - 'a') + 10;
+ } else if (s[i] >= 'A' && s[i] <= 'F') {
+ digit = (s[i] - 'A') + 10;
+ }
+ result += digit * power;
+ power *= BASE;
+ }
+
+ return result;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c
similarity index 72%
rename from source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c
rename to source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c
index afb0dd93..3c91036f 100644
--- a/source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c
+++ b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c
@@ -2,30 +2,28 @@
* Exercise 2.4
*
* Let us write a version of squeeze(s1,s2) that deletes each
- * character in the string 1 that matches any character in the string s2
+ * character in the string 1 that matches any character in the string s2.
+ * Utilize user defined function mgetline to input the strings.
+ * Don't use any standard library string manipulation function.
*
**/
#include
+
#define MAXLINE 1000
-int mgetline(char line[], int maxline);
-void squeeze(char s1[], char s2[]);
+int mgetline(char s[], int lim);
+
+void squeeze(char s1[], const char s2[]);
int main(void) {
char s1[MAXLINE], s2[MAXLINE];
-
- putchar('s');
- putchar('1');
mgetline(s1, MAXLINE);
-
- putchar('s');
- putchar('2');
mgetline(s2, MAXLINE);
squeeze(s1, s2);
- printf("%s", s1);
+ printf("\n%s\n", s1);
return 0;
}
@@ -40,9 +38,11 @@ int mgetline(char s[], int lim) {
s[i++] = c;
s[i] = '\0';
+
+ return i;
}
-void squeeze(char s1[], char s2[]) {
+void squeeze(char s1[], const char s2[]) {
int i, j, k;
k = 0;
@@ -54,4 +54,4 @@ void squeeze(char s1[], char s2[]) {
}
s1[k] = '\0';
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c
new file mode 100644
index 00000000..072ec593
--- /dev/null
+++ b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c
@@ -0,0 +1,57 @@
+/**
+ * Exercise 2.5
+ *
+ * Write the function any(s1,s2) which returns the first location in the string
+ * s1 where any character from the string s2 occurs, or -1 if s1 contains
+ * no characters from s2. ( The standard library function strpbrk does
+ * the same job but returns a pointer to the location
+ *
+ **/
+
+#include
+
+#define MAXLINE 1000
+
+int mgetline(char line[], int lim);
+
+int any(char s1[], const char s2[]);
+
+int main(void) {
+ char s1[MAXLINE], s2[MAXLINE];
+ int val;
+
+ mgetline(s1, MAXLINE);
+ mgetline(s2, MAXLINE);
+
+ val = any(s1, s2);
+
+ printf("%d", val);
+
+ return 0;
+}
+
+int mgetline(char line[], int lim) {
+ int i, c;
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = c;
+
+ if (c == '\n')
+ line[i++] = c;
+ line[i] = '\0';
+
+ return i;
+}
+
+int any(char s1[], const char s2[]) {
+ int i, j;
+
+ for (i = 0; s1[i] != '\0'; ++i) {
+ for (j = 0; s2[j] != '\0'; ++j) {
+ if (s1[i] == s2[j] && s1[i] != '\n') {
+ return i;
+ }
+ }
+ }
+
+ return -1;
+}
diff --git a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c
new file mode 100644
index 00000000..ce639ba3
--- /dev/null
+++ b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c
@@ -0,0 +1,31 @@
+/**
+ *
+ * Exercise 2.6 - Write a function setbits(x,p,n,y) that returns x with the
+ * n bits that begin at position p set to the rightmost n bits of y,leaving
+ * the other bits unchanged.
+ **/
+
+#include
+#include
+
+unsigned setbits(unsigned x, int p, int n, unsigned y);
+
+unsigned setbits(unsigned x, int p, int n, unsigned y) {
+ return x & ((~0 << p + 1) | ~(~0 << p + 1 - n)) | ((y & ~(~0 << n)) << p + 1 - n);
+}
+
+
+int main(void) {
+
+ printf("%u", setbits((unsigned)12, 3, 2, (unsigned)57));
+
+ assert(setbits(0x2, 2, 2, 0xD) == 0x2); /* x=00000(01)0 y=000011(01) : equal to x */
+ assert(setbits(0x2, 0, 0, 0xD) == 0x2); /* x=00000010 y=00001101 : equal to x */
+ assert(setbits(0xF, 3, 1, 0xE) == 0x7); /* x=0000(1)111 y=0000111(0) : 0000(0)111 */
+ assert(setbits(0x37, 3, 2, 0x4E) == 0x3B); /* x=0011(01)11 y=010011(10) : 0011(10)11 */
+ assert(setbits(0x37, 7, 8, 0x4E) == 0x4E); /* x=(00110111) y=(01001110) : equal to y */
+ assert(setbits(0xFF, 3, 4, 0x00) == 0xF0); /* x=1111(1111) y=0000(0000) : 1111(0000) */
+ assert(setbits(0xFF, 0, 1, 0x00) == 0xFE); /* x=1111111(1) y=0000000(0) : 1111111(0) */
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c b/source/cprogramming/chapter2/cprogs/ex_2.7_invert.c
similarity index 76%
rename from source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c
rename to source/cprogramming/chapter2/cprogs/ex_2.7_invert.c
index 257635ce..5c9600b3 100644
--- a/source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c
+++ b/source/cprogramming/chapter2/cprogs/ex_2.7_invert.c
@@ -11,7 +11,7 @@
unsigned invert(unsigned x, int p, int n);
-int main(void) { printf("%u", (unsigned)invert((unsigned)8, (int)3, (int)3)); }
+int main(void) { printf("%u", (unsigned) invert((unsigned) 8, (int) 3, (int) 3)); }
unsigned invert(unsigned x, int p, int n) {
return x ^ (~(~0 << n) << (p + 1 - n));
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c b/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c
similarity index 89%
rename from source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c
rename to source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c
index 1dddb0e7..61e93a76 100644
--- a/source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c
+++ b/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c
@@ -1,4 +1,4 @@
-/* write a function rightrot(x,n) that returns the value of the integer x
+/* Write a function rightrot(x,n) that returns the value of the integer x
* rotated to rightby n bit positions */
#include
@@ -18,6 +18,7 @@ unsigned rightrot(unsigned x, int n) {
unsigned rbit; /* rightmost bit */
rbit = x << (wordlength() - n);
+
x = x >> n;
x = x | rbit;
@@ -26,9 +27,11 @@ unsigned rightrot(unsigned x, int n) {
int wordlength(void) {
int i;
+
unsigned v = (unsigned)~0;
for (i = 1; (v = v >> 1) > 0; i++)
;
+
return i;
}
diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c
similarity index 80%
rename from source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c
rename to source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c
index 64a4e1ea..485f405d 100644
--- a/source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c
+++ b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c
@@ -4,10 +4,6 @@
#include
-int bitcount(unsigned x);
-
-int main(void) { printf("%d", bitcount((unsigned)12)); }
-
int bitcount(unsigned x) {
int b;
@@ -16,3 +12,7 @@ int bitcount(unsigned x) {
return b;
}
+
+int main(void) {
+ printf("%d", bitcount((unsigned) 12));
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst
index 788cdb97..42c1dc30 100644
--- a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst
+++ b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst
@@ -20,18 +20,43 @@ Explanation
The execution of the above program will give::
- Minimum Signed Char -128
- Maximum Signed Char 127
- Minimum Signed Short -32768
- Maximum Signed Short 32767
- Minimum Signed Int -2147483648
- Maximum Signed Int 2147483647
- Minimum Signed Long -2147483648
- Maximum signed Long 2147483647
- Maximum Unsigned Char 255
- Maximum Unsigned Short 65535
- Maximum Unsigned Int 4294967295
- Maximum Unsigned Long 4294967295
+ Ranges of various floating-point types through calculation:
+ Minimum Signed Char -128
+ Maximum Signed Char 127
+ Minimum Signed Short -32768
+ Maximum Signed Short 32767
+ Minimum Signed Int -2147483648
+ Maximum Signed Int 2147483647
+ Minimum Signed Long -9223372036854775808
+ Maximum signed Long 9223372036854775807
+ Maximum Unsigned Char 255
+ Maximum Unsigned Short 65535
+ Maximum Unsigned Int 4294967295
+ Maximum Unsigned Long 18446744073709551615
+
+ Ranges of various integer and floating-point types from standard headers:
+ Minimum Signed Char -128
+ Maximum Signed Char 127
+ Minimum Signed Short -32768
+ Maximum Signed Short 32767
+ Minimum Signed Int -2147483648
+ Maximum Signed Int 2147483647
+ Minimum Signed Long -9223372036854775808
+ Maximum signed Long 9223372036854775807
+ Minimum Signed Long Long -9223372036854775808
+ Maximum signed Long Long 9223372036854775807
+ Minimum Float 1.175494E-38
+ Maximum Float 3.402823E+38
+ Minimum Double 2.225074E-308
+ Maximum Double 1.797693E+308
+ Minimum Long Double 3.362103E-4932
+ Maximum Long Double 1.189731E+4932
+ Maximum Unsigned Char 255
+ Maximum Unsigned Short 65535
+ Maximum Unsigned Int 4294967295
+ Maximum Unsigned Long 18446744073709551615
+ Maximum Unsigned Long Long 18446744073709551615
+
In order explain how we calculate the maximum values, we will have to do some
bit arthimetic. Let's start by calculating the maximum unsigned char.
diff --git a/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst b/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst
index ca8ec78d..f943bd19 100644
--- a/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst
+++ b/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst
@@ -22,7 +22,7 @@ Write a loop equivalent to the for loop above without using && or ||.
Explanation
===========
-We use mgetline instead of getline, so that our compiler does not get confused
+We use _getline instead of getline, so that our compiler does not get confused
with the builtin getline function.
The crux of the program is this.
diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst
index c14a1b82..520afa17 100644
--- a/source/cprogramming/chapter2/ex_2.3_htoi.rst
+++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst
@@ -9,7 +9,7 @@ Write a function htoi(s), which converts a string of hexadecimal digits
(including an optional 0x or 0X) into its equivalent integer value. The
allowable digits are 0 through 9, a through f,and A through F.
-.. literalinclude:: ../../languages/cprogs/Ex_2.3_htoi.c
+.. literalinclude:: cprogs/ex_2.3_htoi.c
:language: c
Explanation
@@ -67,21 +67,40 @@ find a character between a to f, we store char - `a` + 10, becase hexadecimal
Then we take each hex digit and for it's position or previous value stored in n,
we mutiply by 16 and add hexdigit.
+.. code-block:: c
+
if(inhex == YES)
n = 16 * n + hexdigit;
For example to convert **0XAF**.
-1. We strip off 0X.
-2. For A, we get the value hexdigit = 10
-3. n = 16 * 0 + 10
- = 10
-4. We gather F, we store hexdigit = 'F' - 'A' + 10;
- = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A)
- = 15
-5. n = 16 * n + hexdigit
- = 16 * 10 + 15
- = 160 + 15
- = 175
-
-**175**
+.. code::
+
+ 1. We strip off 0X.
+ 2. For A, we get the value hexdigit = 10
+ 3. n = 16 * 0 + 10
+ = 10
+ 4. We gather F, we store hexdigit = 'F' - 'A' + 10;
+ = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A)
+ = 15
+ 5. n = 16 * n + hexdigit
+ = 16 * 10 + 15
+ = 160 + 15
+ = 175
+
+ 175
+
+Visualization
+=============
+
+.. raw:: html
+
+
+
+Try It Out
+==========
+
+
+.. raw:: html
+
+
diff --git a/source/cprogramming/chapter2/ex_2.4_squeezess.rst b/source/cprogramming/chapter2/ex_2.4_squeezess.rst
index 1cfab1e5..4a402b69 100644
--- a/source/cprogramming/chapter2/ex_2.4_squeezess.rst
+++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst
@@ -8,7 +8,7 @@ Question
Write an alternative version of squeeze(s1,s2) that deletes each character in s1
that matches any character in the string s2.
-.. literalinclude:: ../../languages/cprogs/Ex_2.4_squeezess.c
+.. literalinclude:: cprogs/ex_2.4_squeezess.c
:language: c
Explanation
@@ -16,18 +16,23 @@ Explanation
Let's take the two inputs strings as:
- s1: HelloWorld
+.. code-block:: bash
- s2: ol
+ HelloWorld
+ ol
-Our desired output is::
+Our desired output is
- HeWrd
+.. code-block:: bash
+
+ HeWrd
This has removed the characters `o` and `l` from the first string. The way
squeeze works is, it take each character from the first string and if there is
no match found, stores it with a new index `k`. If there is a match found in
-**s2**, it simply skips it. The way it skips is realized by the following::
+**s2**, it simply skips it. The way it skips is realized by the following
+
+.. code-block:: c
for(j=0; (s1[i]!=s2[j]) && s2[j]!='\0' ;++j)
;
@@ -38,3 +43,18 @@ When the match is found **s1[i] == s2[j]** so our first for loop will **end**.
The second **if condtion** will fail too as s2 is not iterated till the end, so
we do not place the character in **s1[k++]** and we have successfully skipped
it.
+
+Visualization
+=============
+
+.. raw:: html
+
+
+
+
+Try It Out
+==========
+
+.. raw:: html
+
+
diff --git a/source/cprogramming/chapter2/ex_2.5_any.rst b/source/cprogramming/chapter2/ex_2.5_any.rst
index c0c9ae2d..e7f8b697 100644
--- a/source/cprogramming/chapter2/ex_2.5_any.rst
+++ b/source/cprogramming/chapter2/ex_2.5_any.rst
@@ -10,7 +10,7 @@ where any character from the string s2 occurs, or -1 if s1 contains no
characters from s2. (The standard library function strpbrk does the same job but
returns a pointer to the location.)
-.. literalinclude:: ../../languages/cprogs/Ex_2.5_any.c
+.. literalinclude:: cprogs/ex_2.5_any.c
:language: c
Explanation
@@ -29,3 +29,18 @@ check_next_char to 0. That is we found a match at **i** and we return that.
If we dont find a match in s2, we increment i and take the next character from
s1. If dont find a match at all, then we return -1.
+
+
+Visualization
+=============
+
+.. raw:: html
+
+
+
+Try It Out
+==========
+
+.. raw:: html
+
+
diff --git a/source/cprogramming/chapter2/ex_2.6_setbits.rst b/source/cprogramming/chapter2/ex_2.6_setbits.rst
index 8ea3c071..e58f0cf7 100644
--- a/source/cprogramming/chapter2/ex_2.6_setbits.rst
+++ b/source/cprogramming/chapter2/ex_2.6_setbits.rst
@@ -14,133 +14,39 @@ position p set to the rightmost n bits of y, leaving the other bits unchanged.
Explanation
===========
-The important piece of the program is this::
+The setbits function takes 4 inputs:
- (x & ~(~(~0 << n) << (p+1-n))) | ( y & (~(~0<
-Converting 1111 0000 to decimal gives us 240 and that is answer.
diff --git a/source/cprogramming/chapter2/ex_2.7_invert.rst b/source/cprogramming/chapter2/ex_2.7_invert.rst
index 6560d71a..37816dfc 100644
--- a/source/cprogramming/chapter2/ex_2.7_invert.rst
+++ b/source/cprogramming/chapter2/ex_2.7_invert.rst
@@ -46,3 +46,10 @@ position onwards by::
x ^ (~(~0 << n) << (p + 1 - n)) = 0000 1000 ^ 0000 1111
= 0000 1111
= 15
+
+Visualization
+=============
+
+.. raw:: html
+
+
diff --git a/source/cprogramming/chapter2/ex_2.8_rightrot.rst b/source/cprogramming/chapter2/ex_2.8_rightrot.rst
index dd0b24de..e0807a05 100644
--- a/source/cprogramming/chapter2/ex_2.8_rightrot.rst
+++ b/source/cprogramming/chapter2/ex_2.8_rightrot.rst
@@ -19,18 +19,19 @@ We need to get the right most bit of the number provided.
First we get the right n bits at one time.
::
+
rbit = x << (wordlength() - n);
-Once we get the right n bits, in order to rotate the value of x, we right
-shift x for n bits and then OR the result of x with the rbit determined in the previous
-step.
+Once we get the right n bits, in order to rotate the value of x, we right shift
+x for n bits and then OR the result of x with the rbit determined in the
+previous step.
::
x = x >> n;
x = x | rbit;
- For the same example.
+For the same example.
::
@@ -50,7 +51,8 @@ step.
= 0001 1001 << 5
= 0010 0000
-So we have got the right most n bits set.Now we right x by 1 and OR the rbit with x.
+So we have got the right most n bits set.Now we right x by 1 and OR the rbit
+with x.
::
@@ -66,11 +68,20 @@ Which is our expected result.
condition 3. when (n > wordlength()) like n = 12
-The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then see "n" as condition 2.
-The result should be correct too!
+The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then
+see "n" as condition 2. The result should be correct too!
::
+
condition 4. when n < 0 (which is not Often use)
-The result will mirror the function,the rightrot(x,n) function will move the left most n(n > 0)bits to the right
-side ,the function should called leftrot(x,n).
+The result will mirror the function,the rightrot(x,n) function will move the
+left most n(n > 0)bits to the right side ,the function should called
+leftrot(x,n).
+
+Visualization
+=============
+
+.. raw:: html
+
+
diff --git a/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst
index ba59110c..a556a6d6 100644
--- a/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst
+++ b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst
@@ -132,12 +132,9 @@ This gives the number of 1 bits in our program. **AND** operation is faster than
shifting, because all bits of the number are **not** moved and thereby makes our
program more efficient.
+Visualization
+=============
-References
-==========
+.. raw:: html
-* `Ones complement`_
-* `Twos complement`_
-
-.. _Ones complement: http://foldoc.org/ones+complement
-.. _Twos complement: http://foldoc.org/twos+complement
+
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c b/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c
deleted file mode 100644
index fe2b7b79..00000000
--- a/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Write a function escape(s,t) that converts characters like newline and tab
-into visible escape sequences like \n and \t as it copies the string t to s. Use
-a Switch. Write a function for the other direction as well,converting the escape
-sequences into the real characters */
-
-#include
-#define MAXLINE 1000
-int mgetline(char line[], int maxline);
-void escape(char s[], char t[]);
-
-int main(void) {
- char s[MAXLINE], t[MAXLINE];
-
- mgetline(t, MAXLINE);
-
- escape(s, t);
-
- printf("%s", s);
-
- return 0;
-}
-
-void escape(char s[], char t[]) {
- int i, j;
-
- i = j = 0;
-
- while (t[i] != '\0') {
- switch (t[i]) {
- case '\t':
- s[j] = '\\';
- ++j;
- s[j] = 't';
- break;
- case '\n':
- s[j] = '\\';
- ++j;
- s[j] = 'n';
- break;
- default:
- s[j] = t[i];
- break;
- }
- ++i;
- ++j;
- }
-
- s[j] = '\0';
-}
-
-int mgetline(char s[], int lim) {
- int i, c;
-
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF; ++i)
- s[i] = c;
-
- s[i] = '\0';
-}
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c b/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c
deleted file mode 100644
index 4079c02a..00000000
--- a/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/* itoa: convert n to characters in s */
-void itoa(int n, char s[]) {
- int i, sign;
- if ((sign = n) < 0) /*record sign */
- n = -n; /* make n positive */
- i = 0;
- do { /* generate digits in reverse order */
- s[i++] = n % 10 + '0'; /* get next digit */
- } while ((n /= 10) > 0); /* delete it */
-
- if (sign < 0)
- s[i++] = '-';
- s[i] = '\0';
- reverse(s);
-}
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c
similarity index 78%
rename from source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c
rename to source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c
index fd22711d..1655f8ae 100644
--- a/source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c
+++ b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c
@@ -1,17 +1,5 @@
-/* Binsearch function, by writing minimum tests inside the loop ( at the cost of
- * more outside)*/
-
#include
-int binsearch(int x, int v[], int n);
-
-int main(void) {
- int arr[] = {2, 4, 6, 7, 9, 29, 45, 46, 49, 50, 51};
- printf("%d", binsearch(9, arr, 10));
-
- return 0;
-}
-
int binsearch(int x, int v[], int n) {
int low, high, mid;
@@ -34,3 +22,10 @@ int binsearch(int x, int v[], int n) {
else
return -1;
}
+
+int main(void) {
+ int arr[] = {2, 4, 6, 7, 9, 29, 45, 46, 49, 50, 51};
+ printf("%d", binsearch(9, arr, 10));
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c b/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c
new file mode 100644
index 00000000..a2b482eb
--- /dev/null
+++ b/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c
@@ -0,0 +1,51 @@
+#include
+#define MAXLINE 1000
+
+void escape(char s[], char t[]) {
+ int i, j;
+
+ i = j = 0;
+
+ while (t[i] != '\0') {
+ switch (t[i]) {
+ case '\t':
+ s[j] = '\\';
+ ++j;
+ s[j] = 't';
+ break;
+ case '\n':
+ s[j] = '\\';
+ ++j;
+ s[j] = 'n';
+ break;
+ default:
+ s[j] = t[i];
+ break;
+ }
+ ++i;
+ ++j;
+ }
+
+ s[j] = '\0';
+}
+
+int mgetline(char s[], int lim) {
+ int i, c;
+
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF; ++i)
+ s[i] = c;
+
+ s[i] = '\0';
+}
+
+int main(void) {
+ char s[MAXLINE], t[MAXLINE];
+
+ mgetline(t, MAXLINE);
+
+ escape(s, t);
+
+ printf("%s", s);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c b/source/cprogramming/chapter3/cprogs/ex_3.3_expand.c
similarity index 82%
rename from source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c
rename to source/cprogramming/chapter3/cprogs/ex_3.3_expand.c
index b5021c96..d4d9bc8b 100644
--- a/source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c
+++ b/source/cprogramming/chapter3/cprogs/ex_3.3_expand.c
@@ -1,21 +1,20 @@
-/* expand: expand short hand notation in s1 into string s2. */
-
#include
#define MAXLINE 100
-int mgetline(char s[], int maxlimit);
-void expand(char s1[], char s2[]);
-
-int main(void) {
- char s1[MAXLINE], s2[MAXLINE];
-
- mgetline(s1, MAXLINE);
+void expand(char s1[], char s2[]) {
+ int i, j, c;
- expand(s1, s2);
+ i = j = 0;
- printf("%s", s2);
+ while ((c = s1[i++]) != '\0')
+ if (s1[i] == '-' && s1[i + 1] >= c) {
+ i++;
+ while (c < s1[i])
+ s2[j++] = c++;
+ } else
+ s2[j++] = c;
- return 0;
+ s2[j] = '\0';
}
int mgetline(char s[], int lim) {
@@ -30,18 +29,14 @@ int mgetline(char s[], int lim) {
s[i] = '\0';
}
-void expand(char s1[], char s2[]) {
- int i, j, c;
+int main(void) {
+ char s1[MAXLINE], s2[MAXLINE];
- i = j = 0;
+ mgetline(s1, MAXLINE);
- while ((c = s1[i++]) != '\0')
- if (s1[i] == '-' && s1[i + 1] >= c) {
- i++;
- while (c < s1[i])
- s2[j++] = c++;
- } else
- s2[j++] = c;
+ expand(s1, s2);
- s2[j] = '\0';
-}
+ printf("%s", s2);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c b/source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c
similarity index 61%
rename from source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c
rename to source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c
index 38812ff6..e0e1e2bf 100644
--- a/source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c
+++ b/source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c
@@ -1,37 +1,15 @@
-/* Modified version of itoa; to handle the situation of MIN_INT of limits.h
-in the previous number = -2147483648 would fail at n =-n,because the max value
-of integer is 2147483647
-
-modifying itoa to handle these situations.
-sign is stored as the number itself, absolute value of each digit is stored in
-the string and while loop is tested not for 0
-
-itoa: convert an integer to string */
-
#include
#include
+
#define MAXLINE 1000
#define abs(x) ((x) > 0 ? (x) : -(x))
-void itoa(int n, char s[]);
-void reverse(char s[]);
-
-int main(void) {
- int number;
- char str[MAXLINE];
-
- /* number=-2345645; */
-
- number = -2147483648;
-
- printf("Integer %d printed as\n String:", number);
-
- itoa(number, str);
-
- printf("%s", str);
+void reverse(char s[]) {
+ int c, i, j;
- return 0;
+ for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
+ c = s[i], s[i] = s[j], s[j] = c;
}
void itoa(int n, char s[]) {
@@ -54,9 +32,19 @@ void itoa(int n, char s[]) {
reverse(s);
}
-void reverse(char s[]) {
- int c, i, j;
+int main(void) {
+ int number;
+ char str[MAXLINE];
- for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
- c = s[i], s[i] = s[j], s[j] = c;
-}
+ /* number=-2345645; */
+
+ number = -2147483648;
+
+ printf("Integer %d printed as\n String:", number);
+
+ itoa(number, str);
+
+ printf("%s", str);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c b/source/cprogramming/chapter3/cprogs/ex_3.5_itob.c
similarity index 79%
rename from source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c
rename to source/cprogramming/chapter3/cprogs/ex_3.5_itob.c
index 9443046a..76a020d8 100644
--- a/source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c
+++ b/source/cprogramming/chapter3/cprogs/ex_3.5_itob.c
@@ -1,26 +1,13 @@
-/* function itob(n,s,b), that converts the integer n into a base b character
- representation in the string s.
-*/
#include
#include
#define MAXLINE 100
-void itob(int n, char s[], int b);
-void reverse(char s[]);
-
-int main(void) {
- int number, base;
- char str[MAXLINE];
-
- number = 42425;
- base = 16;
-
- itob(number, str, base);
-
- printf("%s", str);
+void reverse(char s[]) {
+ int i, j, c;
- return 0;
+ for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
+ c = s[i], s[i] = s[j], s[j] = c;
}
void itob(int n, char s[], int b) {
@@ -45,9 +32,16 @@ void itob(int n, char s[], int b) {
reverse(s);
}
-void reverse(char s[]) {
- int i, j, c;
+int main(void) {
+ int number, base;
+ char str[MAXLINE];
- for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
- c = s[i], s[i] = s[j], s[j] = c;
-}
+ number = 42425;
+ base = 16;
+
+ itob(number, str, base);
+
+ printf("%s", str);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c b/source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c
similarity index 74%
rename from source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c
rename to source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c
index 676531bb..1cb57850 100644
--- a/source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c
+++ b/source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c
@@ -1,27 +1,13 @@
-/* a function of itoa, which accepts the third argument as the width of the
-number. the string representation is padded with blanks in the left to get the
-required width */
-
#include
#include
#define MAXLIMIT 100
-void itoa(int n, char s[], int w);
-void reverse(char s[]);
-
-int main(void) {
- int number, width;
- char str[MAXLIMIT];
-
- number = -343565;
- width = 10;
-
- itoa(number, str, width);
-
- printf("%s", str);
+void reverse(char s[]) {
+ int i, j, c;
- return 0;
+ for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
+ c = s[i], s[i] = s[j], s[j] = c;
}
void itoa(int n, char s[], int w) {
@@ -47,9 +33,16 @@ void itoa(int n, char s[], int w) {
reverse(s);
}
-void reverse(char s[]) {
- int i, j, c;
+int main(void) {
+ int number, width;
+ char str[MAXLIMIT];
- for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
- c = s[i], s[i] = s[j], s[j] = c;
-}
+ number = -343565;
+ width = 10;
+
+ itoa(number, str, width);
+
+ printf("%s", str);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst b/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst
index 905c0770..912c5ebf 100644
--- a/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst
+++ b/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst
@@ -9,13 +9,10 @@ Our binary search makes two tests inside the loop, when one would suffice (at
the price of more tests outside.) Write a version with only one test inside the
loop and measure the difference in runtime.
-.. literalinclude:: cprogs/Ex_3.1_binsearch-2.c
+.. literalinclude:: cprogs/ex_3.1_binsearch-2.c
:language: c
:tab-width: 4
-.. runcode:: cprogs/Ex_3.1_binsearch-2.c
- :language: c
-
Explanation
===========
diff --git a/source/cprogramming/chapter3/ex_3.2_escape.rst b/source/cprogramming/chapter3/ex_3.2_escape.rst
index 0e61bf42..5b862de8 100644
--- a/source/cprogramming/chapter3/ex_3.2_escape.rst
+++ b/source/cprogramming/chapter3/ex_3.2_escape.rst
@@ -10,14 +10,10 @@ visible escape sequences like \n and \t as it copies the string t to s. Use a
switch. Write a function for the other direction as well, converting escape
sequences into the real characters.
-.. literalinclude:: cprogs/Ex_3.2_escape.c
+.. literalinclude:: cprogs/ex_3.2_escape.c
:language: c
:tab-width: 4
-.. runcode:: cprogs/Ex_3.2_escape.c
- :language: c
- :codesite: ideone
-
Explanation
===========
diff --git a/source/cprogramming/chapter3/ex_3.3_expand.rst b/source/cprogramming/chapter3/ex_3.3_expand.rst
index 9dcddb70..56af6625 100644
--- a/source/cprogramming/chapter3/ex_3.3_expand.rst
+++ b/source/cprogramming/chapter3/ex_3.3_expand.rst
@@ -10,14 +10,10 @@ string s1 into the equivalent complete list abc...xyz in s2. Allow for letters
of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9
and -a-z. Arrange that a leading or trailing -is taken literally.
-.. literalinclude:: cprogs/Ex_3.3_expand.c
+.. literalinclude:: cprogs/ex_3.3_expand.c
:language: c
:tab-width: 4
-.. runcode:: cprogs/Ex_3.3_expand.c
- :language: c
- :codesite: ideone
-
Explanation
===========
diff --git a/source/cprogramming/chapter3/ex_3.4_itoa-2.rst b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst
index 08b19b71..510f7fac 100644
--- a/source/cprogramming/chapter3/ex_3.4_itoa-2.rst
+++ b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst
@@ -10,20 +10,12 @@ the largest negative number, that is, the value of n equal to -(2wordsize-1).
Explain why not. Modify it to print that value correctly, regardless of the
machine on which it runs.
-The previous version of itoa was this::
+The previous version of itoa was this
-.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-previous.c
+.. literalinclude:: cprogs/ex_3.4_itoa-2.c
:language: c
:tab-width: 4
-.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-2.c
- :language: c
- :tab-width: 4
-
-.. runcode:: ../../languages/cprogs/Ex_3.4_itoa-2.c
- :language: c
- :codesite: ideone
-
Explanation
===========
@@ -37,10 +29,3 @@ Once this process is over. We check if we were converting negative number, by
checking if the sign is less than 0, if it was, we add a `-` to the string.
And then we do a simple `reverse` of the string to get our `itoa`.
-
-
-
-.. seealso::
-
- * :c-suggest-improve:`Ex_3.4_itoa-2.c`
- * :c-better-explain:`Ex_3.4_itoa-2.rst`
diff --git a/source/cprogramming/chapter3/ex_3.5_itob.rst b/source/cprogramming/chapter3/ex_3.5_itob.rst
index 36e94810..bdecec35 100644
--- a/source/cprogramming/chapter3/ex_3.5_itob.rst
+++ b/source/cprogramming/chapter3/ex_3.5_itob.rst
@@ -9,10 +9,7 @@ Write the function itob(n,s,b) that converts the integer n into a base b
character representation in the string s. In particular, itob(n,s,16) formats s
as a hexadecimal integer in s.
-.. literalinclude:: cprogs/Ex_3.5_itob.c
- :language: c
-
-.. runcode:: cprogs/Ex_3.5_itob.c
+.. literalinclude:: cprogs/ex_3.5_itob.c
:language: c
Explanation
diff --git a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst
index 6afb8969..c67fe780 100644
--- a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst
+++ b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst
@@ -9,13 +9,10 @@ Write a version of itoa that accepts three arguments instead of two. The third
argument is a minimum field width; the converted number must be padded with
blanks on the left if necessary to make it wide enough.
-.. literalinclude:: cprogs/Ex_3.6_itoa-3.c
+.. literalinclude:: cprogs/ex_3.6_itoa-3.c
:language: c
:tab-width: 4
-.. runcode:: cprogs/Ex_3.6_itoa-3.c
- :language: c
-
Explanation
===========
@@ -42,4 +39,4 @@ Run It
.. raw:: html
-
+
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c
index 71ff0b3d..482b0f4a 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c
@@ -1,145 +1,139 @@
/**
- * Exercise 4.10 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * An alternate organization uses getline to read an entire input line; this
- * makes getch and ungetch unnecessary. Revise the calculator to use this
- * approach.
- */
+ * Revise the Calculator program to use the getline instead of getch and ungetch
+ **/
-#include
-#include // for atof()
+#include
+#include /* for atof() */
-#define MAXOP 100 // max size of operand or operator
-#define NUMBER '0' // signal that a number was found
+#define MAXOP 100
+#define NUMBER '0'
+
+int getop(char []);
-int getop(char[]);
void push(double);
+
double pop(void);
-/* reverse Polish calculator */
+/* reverse polish notation calculator */
-int main(int argc, char *argv[]) {
+int main(void) {
int type;
double op2;
char s[MAXOP];
- while (--argc > 0) {
- type = getop(*++argv);
+ while ((type = getop(s)) != EOF) {
switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error: zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push((int)pop() % (int)op2);
- else
- printf("error: zero divisor\n");
- break;
- case '\0':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
+ case NUMBER:
+ push(atof(s));
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ break;
+ case '\n':
+ printf("\t%.9g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
}
}
return 0;
}
-#define MAXVAL 100 // maximum depth of val stack
+#define MAXVAL 100 /* maximum depth of the val stack */
-int sp = 0; // next free stack position
+int sp = 0;
+double val[MAXVAL];
-double val[MAXVAL]; // value stack
-
-/* push: push f onto value stack */
+/* push : push f onto value stack */
void push(double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
- printf("error: stack full, can't push %g\n", f);
+ printf("error: stack full,can't push %g\n", f);
}
-/* pop: pop and return top value from stack */
+/* pop: pop and return top values from stack */
double pop(void) {
if (sp > 0)
return val[--sp];
else {
- printf("error: stack empty\n");
+ printf("error: stack empty \n");
return 0.0;
}
}
+
/* using getline instead of getch and ungetch */
-#include
+#include
+
#define MAXLINE 100
int mgetline(char line[], int limit);
-int li = 0; // index of next char in line
-char line[MAXLINE]; // current input line
-
-int getop(char s[]) {
- int i, c;
+int li = 0; /* input line index */
+char line[MAXLINE]; /* one input line */
- if (line[li] == '\0') {
+/* getop: get next operator or numeric operand */
- if (mgetline(line, MAXLINE) == 0) {
- return '\0';
- }
+int getop(char s[]) {
+ int c, i;
- else {
+ if (line[li] == '\0')
+ if (mgetline(line, MAXLINE) == 0)
+ return EOF;
+ else
li = 0;
- }
- }
- while ((s[0] = c = line[li++]) == ' ' || c == '\t')
- ;
+ while ((s[0] = c = line[li++]) == ' ' || c == '\t');
+
s[1] = '\0';
+
if (!isdigit(c) && c != '.')
- return c; // not a number
+ return c;
+
i = 0;
- if (isdigit(c)) // collect integer part
- while (isdigit(s[++i] = c = line[li++]))
- ;
- if (c == '.') // collect fraction part
- while (isdigit(s[++i] = c = line[li++]))
- ;
+
+ if (isdigit(c))
+ while (isdigit(s[++i] = c = line[li++]));
+ if (c == '.')
+ while (isdigit(s[++i] = c = line[li++]));
+
s[i] = '\0';
+
li--;
+
return NUMBER;
}
int mgetline(char s[], int lim) {
- int c, i;
+ int i, c;
+
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ s[i] = c;
- i = 0;
- while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
- s[i++] = c;
if (c == '\n')
s[i++] = c;
+
s[i] = '\0';
+
return i;
}
+
+
+
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c
index 65327c85..5fd4166b 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c
@@ -1,82 +1,70 @@
/**
- * Exercise 4.11 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Modify getop so that it doesn't need to use ungetch. Hint: use an internal
- * static variable.
- *
- */
-
-#include
-#include
-#include // for atof()
+ * modify getop so that it does not need to use ungetch: Hint: static int lastc
+ **/
+
+#include
+#include
-#define NUMBER '0'
#define MAXOP 100
+#define NUMBER '0'
+
+int getop(char []);
-int getop(char[]);
void push(double);
+
double pop(void);
-/* reverse Polish calculator */
+/* reverse polish calculator */
-int main(int argc, char *argv[]) {
+int main(void) {
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error: zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push((int)pop() % (int)op2);
- else
- printf("error: zero divisor\n");
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
+ case NUMBER:
+ push(atof(s));
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ break;
+ case '\n':
+ printf("\t%.8g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
}
}
return 0;
}
-#define MAXVAL 100 /* maximum depth of val stack */
-int sp = 0; /* next free stack position */
-double val[MAXVAL]; /* value stack */
+#define MAXVAL 100
+
+int sp = 0;
+double val[MAXVAL];
-/* push: push f onto value stack */
+/* push : push f onto value stack */
void push(double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
- printf("error: stack full, can't push %g\n", f);
+ printf("error: stack full,can't push %g\n", f);
}
/* pop: pop and return top value from stack */
@@ -90,10 +78,12 @@ double pop(void) {
}
}
-#include
+#include
int getch(void);
+/* getop: get next operator or numeric operand */
+
int getop(char s[]) {
int c, i;
static int lastc = 0;
@@ -109,28 +99,28 @@ int getop(char s[]) {
c = getch();
s[1] = '\0';
+
if (!isdigit(c) && c != '.')
- return c; /* not a number */
+ return c;
i = 0;
- if (isdigit(c)) /* collect integer part */
- while (isdigit(s[++i] = c = getch()))
- ;
- if (c == '.') /* collect fraction part */
- while (isdigit(s[++i] = c = getch()))
- ;
+ if (isdigit(c))
+ while (isdigit(s[++i] = c = getch()));
+ if (c == '.')
+ while (isdigit(s[++i] = c = getch()));
s[i] = '\0';
+
if (c != EOF)
lastc = c;
+
return NUMBER;
}
#define BUFSIZE 100
-char buf[BUFSIZE]; /* buffer for ungetch */
-int bufp = 0; /* next free position in buf */
+char buf[BUFSIZE];
+int bufp;
-int getch(void) /* get a (possibly pushed back) character */
-{
+int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c b/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c
index dd880501..af061ab6 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c
@@ -1,34 +1,41 @@
/**
- * Exercise 4.12 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Adapt the ideas of printd to write a recursive version of itoa; that is,
- * convert an integer into a string by calling a recursive routine.
- */
-
-#include
-#include
+ * recursive version of itoa; that converts an integer string by calling a recursive routine
+ **/
+
#include
+#include
+
+#define MAXLEN 100
void itoa(int n, char s[]);
-int main(int argc, char *argv[]) {
- int n = 123456789;
- char s[100];
+
+int main(void) {
+ int n;
+ char s[MAXLEN];
+
+ n = 1723;
+
itoa(n, s);
- printf("%s\n", s);
+
+ printf("%s", s);
+
return 0;
}
void itoa(int n, char s[]) {
- static int i = 0;
- if (n / 10) {
+ static int i;
+
+ if (n / 10)
itoa(n / 10, s);
- } else {
- if (n < 0) {
+ else {
+ i = 0;
+ if (n < 0)
s[i++] = '-';
- }
}
+
s[i++] = abs(n) % 10 + '0';
+
s[i] = '\0';
-}
+
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c
index 0f21b5f7..6cb96c76 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c
@@ -1,38 +1,57 @@
/**
- * Exercise 4.13 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Write a recursive version of the function reverse(s), which reverses the
- * string s in place.
- */
+ * a recursive version of reverse(s); the string reverse function
+ **/
-#include
-#include
+#include
+#include
-#define MAXLINE 1000
+#define MAXLINE 100
-void reverse(char s[], int i, int j);
+void reverse(char s[]) {
+ static int i = 0;
+ static int len;
-int main(void) {
- char s[MAXLINE];
- int i, j;
-
- printf("Enter a string: ");
- fgets(s, MAXLINE, stdin);
- i = 0;
- j = strlen(s) - 1;
- reverse(s, i, j);
- printf("Reversed string: %s\n", s);
- return 0;
-}
+ int j;
+ char c;
+
+ if (i == 0) {
+ len = strlen(s);
+ }
-void reverse(char s[], int i, int j) {
- int c;
+ j = len - (i + 1);
if (i < j) {
c = s[i];
s[i] = s[j];
s[j] = c;
- reverse(s, ++i, --j);
+ i++;
+ reverse(s);
+ } else {
+ // the algorithm has finished so we have to set i=0 again
+ i = 0;
}
}
+
+int mgetline(char line[], int lim) {
+ int i, c;
+
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
+ line[i] = c;
+
+ if (c == '\n')
+ line[i++] = '\n';
+
+ line[i] = '\0';
+}
+
+int main(void) {
+ char s[MAXLINE];
+
+ mgetline(s, MAXLINE);
+
+ reverse(s);
+
+ printf("%s", s);
+
+ return 0;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c b/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c
index bce3aaab..d993be5b 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c
@@ -1,27 +1,17 @@
-/**
- * Exercise 4.14 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Write a macro swap(t,x,y) that interchanges two arguments of type t. (Block
- * structure will help.)
- *
- */
+/* a macro swap(t,x,y) that interchanges two arguments of type t */
-#include
+#include
-#define swap(t, x, y) \
- { \
- t temp; \
- temp = x; \
- x = y; \
- y = temp; \
- }
+#define swap(t, x, y) { t _z; \
+ _z = x; \
+ x = y; \
+ y = _z; }
-int main() {
- int x = 1;
- int y = 2;
- printf("x = %d, y = %d\n", x, y);
- swap(int, x, y);
- printf("x = %d, y = %d\n", x, y);
- return 0;
-}
+int main(void) {
+ char x, y;
+ x = 'a';
+ y = 'b';
+ printf("x= %c \t y= %c\n", x, y);
+ swap(char, x, y);
+ printf("x=%c \t y=%c\n", x, y);
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c b/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c
index dfc27313..297a4a7e 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c
@@ -1,35 +1,34 @@
-/**
- * Exercise 4.1 - The C Programming Language
- *
- * Write the function strindex(s,t) which returns the position of the rightmost
- * occurrence of t in s, or -1 if there is none.
- *
- */
+/* strindex which returns rightmost occurrence */
-#include
+#include
-int mstrindex(char s[], char t[]);
+int mstrindex(char s[],char t[])
+{
+ int i,j,k, result;
-int main(int argc, char *argv[]) {
+ result = -1;
+
+ for(i=0;s[i]!='\0';i++)
+ {
+ for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
+ ;
+ if(k>0 && t[k] == '\0')
+ result = i;
+ }
+ return result;
+}
+
+int main(void)
+{
char line[] = "abcdedfabcde";
char pattern[] = "abc";
int found;
- found = mstrindex(line, pattern);
- printf("Found: %d\n", found);
-}
+ /* It should match the a the 7th position. */
-int mstrindex(char s[], char t[]) {
- int i, j, k, result;
+ found = mstrindex(line, pattern);
- result = -1;
+ printf("Found the right index: %d\n", found);
- for (i = 0; s[i] != '\0'; i++) {
- for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
- ;
- if (k > 0 && t[k] == '\0')
- result = i;
- }
- return result;
-}
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c
index b49979be..75a8003f 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c
@@ -1,7 +1,8 @@
/**
- * Exercise 4.2 - Extend atof to handle scientific notation of the form
- * 123.45e-6 where a floating-point number may be followed by e or E and
- * an optionally signed exponent.
+ *
+ * Program demonstrating atof(char s[]).The function which converts the string
+ * to a floating point value.
+ *
*/
#include
@@ -9,30 +10,21 @@
#define MAXLINE 100
-double atof(char s[]);
-int mgetline(char s[], int lim);
-
-int main(int argc, char *argv[]) {
- char str[MAXLINE];
- double val;
-
- mgetline(str, MAXLINE);
-
- val = atof(str);
-
- printf("%f", val);
+int power(int base, int exp) {
+ int power;
+ power = 1;
+ while (exp-- > 0)
+ power *= base;
- return 0;
+ return power;
}
-double atof(char s[]) {
+double myatof(char s[]) {
double val, pow;
int sign, i, esign, exp;
-
int power(int base, int exp);
- for (i = 0; isspace(s[i]); i++)
- ;
+ for (i = 0; isspace(s[i]); i++);
sign = (s[i] == '-') ? -1 : 1;
@@ -52,48 +44,40 @@ double atof(char s[]) {
if (s[i] == 'e' || s[i] == 'E')
i++;
-
- if (s[i] == '+')
- esign = 1;
- else if (s[i] == '-')
- esign = -1;
- else
- esign = 1;
+ if (s[i] == '+' || s[i] == '-') {
+ esign = s[i];
+ i++;
+ }
for (exp = 0; isdigit(s[i]); i++)
- exp = 10 * exp + (s[i] - '0');
+ exp = 10.0 * exp + (s[i] - '0');
- if (esign == 1)
- val = (val / pow) * power(exp, 10);
+ if (esign == '-')
+ return sign * (val / pow) / power(10, exp);
else
- val = (val / pow) / power(exp, 10);
- return sign * val;
+ return sign * (val / pow) * power(10, exp);
}
-int mgetline(char s[], int lim) {
- int c, i;
+int mgetline(char line[], int lim) {
+ int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n') {
- s[i] = c;
- ++i;
- }
+ line[i] = c;
- s[i] = '\0';
+ if (c == '\n')
+ line[i++] = c;
- return i;
+ line[i] = '\0';
}
-int power(int base, int exp) {
- int i, p;
-
- p = 1;
+int main(void) {
+ char str[MAXLINE];
+ double num;
+ mgetline(str, MAXLINE);
- for (i = 1; i <= exp; ++i)
- p = p * base;
+ num = myatof(str);
+ printf("%f", num);
- return p;
+ return 0;
}
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c b/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c
index 97c59bb4..8e861943 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c
@@ -1,11 +1,11 @@
/**
- * Exercise 4.3 of The C Programming Language by Brian W. Kernighan and Dennis
- * Ritchie.
+ * Adding the Modulus operator and provision for negative numbers
+ * Program is given the input in a single and and it print the output upon
+ * getting a \n character. For e.g: 10 10 + 100 + 2 * 240
*
- * RPN modulus operator and negative numbers.
- *
- */
+ **/
+#include
#include
#include
#include
@@ -14,68 +14,78 @@
#define MAXOP 100
#define NUMBER '0'
+#define BUFSIZE 100
+
+#define MAXVAL 100
+
+int sp = 0;
+int bufp = 0;
+
+double val[MAXVAL];
+char buf[BUFSIZE];
+
+int getch(void);
+
+void ungetch(int);
+
int getop(char[]);
+
void push(double);
+
double pop(void);
-/* Reverse Polish Calculator */
+/* reverse polish calculator */
-int main(int argc, char *argv[]) {
+int main(void) {
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- push(pop() - pop());
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0) {
- push(pop() / op2);
- } else {
- printf("error: zero divisor\n");
- }
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0) {
- push(fmod(pop(), op2));
- } else {
- printf("error: zero divisor\n");
- }
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
+ case NUMBER:
+ push(atof(s));
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ else
+ printf("error:zero divisor\n");
+ break;
+ case '%':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(fmod(pop(), op2));
+ else
+ printf("erro:zero divisor\n");
+ break;
+ case '\n':
+ printf("\t%.8g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
}
}
return 0;
}
-#define MAXVAL 100
-
-int sp = 0;
-double val[MAXVAL];
-
void push(double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
- printf("error: stack full, can't push %g\n", f);
+ printf("error:stack full, cant push %g\n", f);
}
double pop(void) {
@@ -87,53 +97,30 @@ double pop(void) {
}
}
-#include
-
-int getch(void);
-void ungetch(int);
-
int getop(char s[]) {
int i, c;
-
- while ((s[0] = c = getch()) == ' ' || c == '\t')
- ;
-
+ while ((s[0] = c = getch()) == ' ' || c == '\t');
s[1] = '\0';
-
if (!isdigit(c) && c != '.' && c != '-')
- return c;
-
+ return c; // not a number
i = 0;
-
- if (c == '-' || isdigit(c))
- while (isdigit(s[++i] = c = getch()))
- ;
-
- if (c == '.')
- while (isdigit(s[++i] = c = getch()))
- ;
-
+ if (c == '-' || isdigit(c)) // collect integer part along with '-'
+ while (isdigit(s[++i] = c = getch()));
+ if (c == '.') // collect fraction part
+ while (isdigit(s[++i] = c = getch()));
s[i] = '\0';
-
if (c != EOF)
ungetch(c);
-
if (strcmp(s, "-") == 0)
- return "-";
-
+ return '-';
return NUMBER;
}
-#define BUFSIZE 100
-
-char buf[BUFSIZE];
-int bufp = 0;
-
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
-
void ungetch(int c) {
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
+
+int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c b/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c
index a5ade1c0..b0befcd5 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c
@@ -1,88 +1,149 @@
-/**
- * Exercise 4.4 - The C Programming Language by Dennis M. Ritchie and Brian W.
- * Kernighan
- *
- * Add commands to print the top elements of the stack without popping, to
- * duplicate it, and to swap the top two elements.
- * Add a command to clear the stack.
- */
-
+#include
#include
#include
#include
#define MAXOP 100
#define NUMBER '0'
+#define BUFSIZE 100
+#define MAXVAL 100
+
+int bufp = 0;
+int sp = 0;
+double val[MAXVAL];
+char buf[BUFSIZE];
+
+int getch(void);
+
+void ungetch(int);
int getop(char[]);
+
void push(double);
+
double pop(void);
-/* Reverse Polish calculator */
+/* reverse polish calculator */
-int main(int argc, char *argv[]) {
+int main(void) {
int type;
- double op2;
+ double op2, op1;
char s[MAXOP];
+ void clearsp(void);
- while (--argc > 0) {
- type = getop(*++argv);
+ while ((type = getop(s)) != EOF) {
switch (type) {
- case NUMBER:
- push(atof(*argv));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error: zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push(fmod(pop(), op2));
- else
- printf("error: zero divisor\n");
- break;
-
- case 'p':
- op2 = pop();
- printf("\t%.8g\n", op2);
- push(op2);
- break;
- case 'd':
- op2 = pop();
- push(op2);
- push(op2);
- break;
- case 's':
- op2 = pop();
- double op3 = pop();
- push(op2);
- push(op3);
- break;
- case 'c':
- while (pop() != 0.0)
- ;
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", *argv);
- break;
+ case NUMBER:
+ push(atof(s));
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ else
+ printf("error:zero divisor\n");
+ break;
+ case '%':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(fmod(pop(), op2));
+ else
+ printf("erro:zero divisor\n");
+ break;
+ case '?':
+ op2 = pop();
+ printf("\t%.8g\n", op2);
+ push(op2);
+ break;
+ case 'c':
+ clearsp();
+ break;
+ case 'd':
+ op2 = pop();
+ push(op2);
+ push(op2);
+ break;
+ case 's':
+ op1 = pop();
+ op2 = pop();
+ push(op1);
+ push(op2);
+ break;
+ case '\n':
+ printf("\t%.8g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
}
}
return 0;
}
+
+void push(double f) {
+ if (sp < MAXVAL)
+ val[sp++] = f;
+ else
+ printf("error:stack full, cant push %g\n", f);
+}
+
+double pop(void) {
+ if (sp > 0)
+ return val[--sp];
+ else {
+ printf("error: stack empty\n");
+ return 0.0;
+ }
+}
+
+void clearsp(void) { sp = 0; }
+
+int getop(char s[]) {
+ int i, c;
+
+ while ((s[0] = c = getch()) == ' ' || c == '\t');
+ s[1] = '\0';
+
+ i = 0;
+ if (!isdigit(c) && c != '.' && c != '-')
+ return c;
+
+ if (c == '-')
+ if (isdigit(c = getch()) || c == '.')
+ s[++i] = c;
+ else {
+ if (c != EOF)
+ ungetch(c);
+ return '-';
+ }
+
+ if (isdigit(c))
+ while (isdigit(s[++i] = c = getch()));
+
+ if (c == '.')
+ while (isdigit(s[++i] = c = getch()));
+
+ s[i] = '\0';
+ if (c != EOF)
+ ungetch(c);
+ return NUMBER;
+}
+
+int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
+
+void ungetch(int c) {
+ if (bufp >= BUFSIZE)
+ printf("ungetch: too many characters\n");
+ else
+ buf[bufp++] = c;
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c b/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c
index 578f6234..21c83a19 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c
@@ -1,105 +1,112 @@
/**
- * Exercise 4.5 from The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Add access to library functions like sin, exp, and pow. See in
- * Appendix B, Section 4.
- */
-
-#include /* for math functions */
+ * compile with -lm flag(the static math library)
+ **/
+
+#include
+#include
#include
-#include /* for atof() */
+#include
+#include
+
+#define MAXOP 100
+#define NUMBER '0'
+#define NAME 'n'
+#define BUFSIZE 100
+#define MAXVAL 100
-#define MAXOP 100 /* max size of operand or operator */
-#define NUMBER '0' /* signal that a number was found */
-#define NAME 'n' /* signal that a name was found */
+int sp = 0;
+double val[MAXVAL];
+char buf[BUFSIZE];
+int bufp = 0;
+
+int getch(void);
+
+void ungetch(int);
int getop(char[]);
+
void push(double);
+
double pop(void);
+
void mathfnc(char[]);
-void clearsp(void);
-int main(int argc, char *argv[]) {
+/* reverse polish calculator */
+int main(void) {
int type;
double op2, op1;
char s[MAXOP];
+ void clearsp(void);
while ((type = getop(s)) != EOF) {
switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case NAME:
- mathfnc(s);
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error: zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push(fmod(pop(), op2));
- else
- printf("error: zero divisor\n");
- break;
- case '?':
- op2 = pop();
- printf("\t%.8g\n", op2);
- push(op2);
- break;
- case 'c':
- clearsp();
- break;
- case 'd':
- op2 = pop();
- push(op2);
- push(op2);
- break;
- case 's':
- op1 = pop();
- op2 = pop();
- push(op1);
- push(op2);
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
+ case NUMBER:
+ push(atof(s));
+ break;
+ case NAME:
+ mathfnc(s);
+ break;
+ case '+':
+ push(pop() + pop());
+ break;
+ case '*':
+ push(pop() * pop());
+ break;
+ case '-':
+ op2 = pop();
+ push(pop() - op2);
+ break;
+ case '/':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(pop() / op2);
+ else
+ printf("error:zero divisor\n");
+ break;
+ case '%':
+ op2 = pop();
+ if (op2 != 0.0)
+ push(fmod(pop(), op2));
+ else
+ printf("erro:zero divisor\n");
+ break;
+ case '?':
+ op2 = pop();
+ printf("\t%.8g\n", op2);
+ push(op2);
+ break;
+ case 'c':
+ clearsp();
+ break;
+ case 'd':
+ op2 = pop();
+ push(op2);
+ push(op2);
+ break;
+ case 's':
+ op1 = pop();
+ op2 = pop();
+ push(op1);
+ push(op2);
+ break;
+ case '\n':
+ printf("\t%.8g\n", pop());
+ break;
+ default:
+ printf("error: unknown command %s\n", s);
+ break;
}
}
return 0;
}
-#define MAXVAL 100 /* maximum depth of val stack */
-int sp = 0; /* next free stack position */
-double val[MAXVAL]; /* value stack */
-
-/* push: push f onto value stack */
void push(double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
- printf("error: stack full, can't push %g\n", f);
+ printf("error:stack full, cant push %g\n", f);
}
-/* pop: pop and return top value from stack */
double pop(void) {
if (sp > 0)
return val[--sp];
@@ -111,80 +118,67 @@ double pop(void) {
void clearsp(void) { sp = 0; }
-#include
-#include
-
-int getch(void);
-void ungetch(int);
-
-/* getop: get next operator or numeric operand */
int getop(char s[]) {
int i, c;
- static int lastc = 0;
- if (lastc == 0)
- c = getch();
- else {
- c = lastc;
- lastc = 0;
- }
-
- while ((s[0] = c) == ' ' || c == '\t')
- c = getch();
+ while ((s[0] = c = getch()) == ' ' || c == '\t');
s[1] = '\0';
+
i = 0;
if (islower(c)) {
- while (islower(s[++i] = c = getch()))
- ;
+ while (islower(s[++i] = c = getch()));;
s[i] = '\0';
if (c != EOF)
- lastc = c;
+ ungetch(c);
if (strlen(s) > 1)
return NAME;
else
- return c;
+ /*return c; this line was bad since when s < 1, the array s only has
+ one character s[0], therofore, this character must be retorned in
+ order to see if it is d,?,s etc. The character c instead contain
+ whatever non-lower value wich always will result in a command
+ uknown*/
+
+ return s[0];
}
+
if (!isdigit(c) && c != '.' && c != '-')
- return c; /* not a number */
- if (c == '-') {
+ return c;
+
+ if (c == '-')
if (isdigit(c = getch()) || c == '.')
- s[++i] = c; /* negative number */
+ s[++i] = c;
else {
if (c != EOF)
- lastc = c;
- return '-'; /* minus sign */
+ ungetch(c);
+ return '-';
}
- }
- if (isdigit(c)) /* collect integer part */
- while (isdigit(s[++i] = c = getch()))
- ;
- if (c == '.') /* collect fraction part */
- while (isdigit(s[++i] = c = getch()))
- ;
+
+ if (isdigit(c))
+ while (isdigit(s[++i] = c = getch()));
+
+ if (c == '.')
+ while (isdigit(s[++i] = c = getch()));
+
s[i] = '\0';
if (c != EOF)
- lastc = c;
+ ungetch(c);
return NUMBER;
}
-#define BUFSIZE 100
-
-char buf[BUFSIZE]; /* buffer for ungetch */
-int bufp = 0; /* next free position in buf */
+int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
-int getch(void) { /* get a (possibly pushed back) character */
- return (bufp > 0) ? buf[--bufp] : getchar();
-}
-
-void ungetch(int c) { /* push character back on input */
+void ungetch(int c) {
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
+/* mathfnc: check the string s for supported math function */
void mathfnc(char s[]) {
double op2;
+
if (strcmp(s, "sin") == 0)
push(sin(pop()));
else if (strcmp(s, "cos") == 0)
@@ -195,5 +189,5 @@ void mathfnc(char s[]) {
op2 = pop();
push(pow(pop(), op2));
} else
- printf("error: %s not supported\n", s);
-}
+ printf("error: %s is not supported\n", s);
+}
\ No newline at end of file
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c b/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c
index b2b54eae..0f5e5516 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c
@@ -1,37 +1,36 @@
-/**
- *
- * Exercise 4.6 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie.
- *
- * Add commands for handling variables. (It's easy to provide twenty-six
- * variables with single-letter names.)
- *
- * Add a variable for the most recently printed value.
- */
-
+#include
#include
#include
#define MAXOP 100
#define NUMBER '0'
+#define BUFSIZE 100
+#define MAXVAL 100
+
+char buf[BUFSIZE];
+int bufp = 0;
+int sp = 0;
+double val[MAXVAL];
int getop(char[]);
void push(double);
double pop(void);
-int main(int argc, char *argv[]) {
- int type;
- int var = 0;
+int getch(void);
+void ungetch(int);
+
+/* reverse polish calculator */
- double op2;
- double v = 0.0;
+int main(void) {
+ int type, var = 0;
+ double op2, v;
+ char s[MAXOP];
double variable[26];
- while (--argc > 0) {
- type = getop(*++argv);
+ while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
- push(atof(*argv));
+ push(atof(s));
break;
case '+':
push(pop() + pop());
@@ -48,47 +47,19 @@ int main(int argc, char *argv[]) {
if (op2 != 0.0)
push(pop() / op2);
else
- printf("error: zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push((int)pop() % (int)op2);
- else
- printf("error: zero divisor\n");
+ printf("error:zero divisor\n");
break;
case '=':
pop();
if (var >= 'A' && var <= 'Z')
variable[var - 'A'] = pop();
else
- printf("error: no variable name\n");
- break;
- case 'v':
- push(v);
+ printf("error: novariablename\n");
break;
- case 'V':
+
+ case '\n':
v = pop();
- push(v);
- break;
- case 's':
- op2 = pop();
- push(pop());
- push(op2);
- break;
- case 'c':
- while (pop() != 0.0)
- ;
- break;
- case 'd':
- op2 = pop();
- push(op2);
- push(op2);
- break;
- case 'p':
- op2 = pop();
- printf("\t%.8g\n", op2);
- push(op2);
+ printf("\t%.8g\n", v);
break;
default:
if (type >= 'A' && type <= 'Z')
@@ -96,7 +67,7 @@ int main(int argc, char *argv[]) {
else if (type == 'v')
push(v);
else
- printf("error: unknown command %s\n", *argv);
+ printf("error: unknown command %s\n", s);
break;
}
var = type;
@@ -104,16 +75,11 @@ int main(int argc, char *argv[]) {
return 0;
}
-#define MAXVAL 100
-
-int sp = 0;
-double val[MAXVAL];
-
void push(double f) {
if (sp < MAXVAL)
val[sp++] = f;
else
- printf("error: stack full, can't push %g\n", f);
+ printf("error:stack full, cant push %g\n", f);
}
double pop(void) {
@@ -125,11 +91,6 @@ double pop(void) {
}
}
-#include
-
-int getch(void);
-void ungetch(int);
-
int getop(char s[]) {
int i, c;
@@ -138,24 +99,22 @@ int getop(char s[]) {
s[1] = '\0';
if (!isdigit(c) && c != '.')
return c;
+
i = 0;
if (isdigit(c))
while (isdigit(s[++i] = c = getch()))
;
+
if (c == '.')
while (isdigit(s[++i] = c = getch()))
;
+
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
-#define BUFSIZE 100
-
-char buf[BUFSIZE];
-int bufp = 0;
-
int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
void ungetch(int c) {
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c
index 03e767b7..168aac21 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c
@@ -1,66 +1,66 @@
/**
- * Exercise 4.7 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Write a routine ungets(s) that will push back an entire string onto the
- * input. Should ungets know about buf and bufp, or should it just use ungetch?
- *
- */
+ * Write a routine ungets(s) that will push back an entire string onto
+ * the input. Should ungets(s) know about buf and bufp or
+ * should it handle it to ungetch()
+ **/
#include
#include
-#define BUFSIZE 100
-#define MAXLINE 1000
+#define MAXBUF 100
+#define MAXLINE 100
-char buf[BUFSIZE];
int bufp = 0;
+int buf[MAXBUF];
int getch(void);
-void ungetch(int);
+
+void ungetch(int c);
+
void ungets(char s[]);
-int mgetline(char s[], int lim);
-int main(int argc, char *argv[]) {
+int mgetline(char line[], int maxline);
+
+int main(void) {
char line[MAXLINE];
- int len;
-
- while ((len = mgetline(line, MAXLINE)) > 0) {
- ungets(line);
- while ((len = mgetline(line, MAXLINE)) > 0) {
- printf("%s", line);
- }
- }
+ int c;
+
+ mgetline(line, MAXLINE);
+
+ ungets(line);
+
+ while ((c = getch()) != EOF)
+ putchar(c);
+
return 0;
}
int mgetline(char s[], int lim) {
- int c, i;
+ int i, c;
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
+ for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
- }
- if (c == '\n') {
- s[i] = c;
- ++i;
- }
+
+ if (c == '\n')
+ s[i++] = c;
+
s[i] = '\0';
- return i;
}
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
+void ungets(char s[]) {
+ int i;
+
+ i = strlen(s);
+
+ while (i > 0)
+ ungetch(s[--i]);
+}
void ungetch(int c) {
- if (bufp >= BUFSIZE) {
+ if (bufp >= MAXBUF)
printf("ungetch: too many characters\n");
- } else {
+ else
buf[bufp++] = c;
- }
}
-void ungets(char s[]) {
- int len = strlen(s);
- while (len > 0) {
- ungetch(s[--len]);
- }
-}
+int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c
new file mode 100644
index 00000000..00d71525
--- /dev/null
+++ b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c
@@ -0,0 +1,45 @@
+/**
+ * Suppose that there will never be more than one character
+ * for pushback. Modify getch and ungetch accordingly.
+ **/
+
+#include
+
+char buf = 0;
+
+/* getch: get a (possibly) pushed back character */
+int getch(void)
+{
+ int c;
+
+ if(buf != 0)
+ c = buf;
+ else
+ c = getchar();
+
+ buf = 0;
+ return c;
+}
+
+/* ungetch: push a character back into input */
+void ungetch(int c)
+{
+ if(buf != 0)
+ printf("ungetch: too many characters\n");
+ else
+ buf = c;
+}
+
+int main(void)
+{
+ int c;
+
+ c = '*';
+
+ ungetch(c);
+
+ while((c=getch()) != EOF)
+ putchar(c);
+
+ return 0;
+}
diff --git a/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c b/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c
index f714aeeb..d72b8e2a 100644
--- a/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c
+++ b/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c
@@ -1,40 +1,46 @@
/**
- * Exercise 4.9 of The C Programming Language by Brian Kernighan and Dennis
- * Ritchie
- *
- * Our getch and ungetch do not handle a pushed-back EOF correctly.
- *
- * Decide what their properties ought to be if an EOF is pushed back, then
- * implement your design.
- *
- */
-
-#include
-#include
+ * getch and ungetch to handle EOF Character. In all the ungetch and getch
+ * functions written so far, the buf is declared as char buf[BUFSIZ].
+ * Changing this to int buf[BUFSIZ] enable it to handle EOF. As EOF is an
+ * integer declared in stdio.h having the value -1
+ **/
-#define BUFSIZE 100
+#include
-char buf[BUFSIZE];
+#define BUFSIZE 100
-int bufp = 0;
+int getch(void);
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
+void ungetch(int c);
-void ungetch(int c) {
- if (bufp >= BUFSIZE) {
- printf("ungetch: too many characters\n");
- } else {
- buf[bufp++] = c;
- }
-}
+int buf[BUFSIZE]; /* buffer for ungetch */
+int bufp = 0; /* next free position in buf */
-int main(int argc, char *argv[]) {
+int main(void) {
int c;
+
c = '*';
- while ((c = getch()) != EOF) {
+ ungetch(c);
+
+ while ((c = getch()) != EOF)
putchar(c);
- }
return 0;
}
+
+/* getch: get a (possibly pushed back) character */
+
+int getch(void) {
+ return (bufp > 0) ? buf[--bufp] : getchar();
+}
+
+/* ungetch: push a character back onto the input */
+
+void ungetch(int c) {
+ if (bufp >= BUFSIZE)
+ printf("ungetch: too many characters \n");
+ else
+ buf[bufp++] = c;
+}
+
diff --git a/source/cprogramming/chapter4/cprogs/sec_4.2.c b/source/cprogramming/chapter4/cprogs/sec_4.2.c
deleted file mode 100644
index bf5f95cf..00000000
--- a/source/cprogramming/chapter4/cprogs/sec_4.2.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- *
- * Section 4.2 The C Programming Language
- *
- * Convert the string s to a double.
- */
-
-#include
-#include
-
-double atof(char s[]);
-
-int main(int argc, char *argv[]) {
- char s[8] = "1234.56";
- double d = atof(s);
- printf("%f\n", d);
- return 0;
-}
-
-double atof(char s[]) {
- double val, power;
- int i, sign;
-
- /** Skip white space */
- for (i = 0; isspace(s[i]); i++) {
- ;
- }
-
- sign = (s[i] == '-') ? -1 : 1;
-
- if (s[i] == '+' || s[i] == '-') {
- i++;
- }
-
- for (val = 0.0; isdigit(s[i]); i++) {
- val = 10.0 * val + (s[i] - '0');
- }
-
- if (s[i] == '.') {
- i++;
- }
-
- for (power = 1.0; isdigit(s[i]); i++) {
- val = 10.0 * val + (s[i] - '0');
- power *= 10.0;
- }
-
- return (sign * val) / power;
-}
diff --git a/source/cprogramming/chapter4/cprogs/sec_4.3.c b/source/cprogramming/chapter4/cprogs/sec_4.3.c
deleted file mode 100644
index 7bd8ad8f..00000000
--- a/source/cprogramming/chapter4/cprogs/sec_4.3.c
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Section 4.3 of the book "The C Programming Language"
- * by Brian W. Kernighan and Dennis M. Ritchie.
- *
- * Reverse Polish calculator
- *
- * Revision history:
- *
- * Senthil Kumaran - Using C99 instead of K&R C, Orgnized the code for
- * readability.
- *
- */
-
-#include
-#include
-#include /* for atof() */
-
-#define MAXOP 100 /* max size of operand or operator */
-#define NUMBER '0' /* signal that a number was found */
-
-#define BUFSIZE 100
-
-int getop(char[]);
-void push(double);
-double pop(void);
-int getch(void);
-void ungetch(int);
-
-/* reverse Polish calculator */
-
-int main(int argc, char *argv[]) {
- int type;
- double op2;
- char s[MAXOP];
-
- while ((type = getop(s)) != EOF) {
- switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error: zero divisor\n");
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
- }
- }
-}
-
-#define MAXVAL 100
-
-int sp = 0;
-double val[MAXVAL];
-
-void push(double f) {
- if (sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error: stack full, can't push %g\n", f);
-}
-
-double pop(void) {
- if (sp > 0)
- return val[--sp];
- else {
- printf("error: stack empty\n");
- return 0.0;
- }
-}
-
-int getop(char s[]) {
- int i, c;
-
- while ((s[0] = c = getch()) == ' ' || c == '\t')
- ;
- s[1] = '\0';
-
- i = 0;
-
- if (!isdigit(c) && c != '.' && c != '-')
- return c; /* not a number */
-
- if (c == '-') {
- if (isdigit(c = getch()) || c == '.')
- s[++i] = c; /* negative number */
- else {
- if (c != EOF)
- ungetch(c);
- return '-'; /* minus sign */
- }
- }
-
- if (isdigit(c)) /* collect integer part */
- while (isdigit(s[++i] = c = getch()))
- ;
-
- if (c == '.') /* collect fraction part */
- while (isdigit(s[++i] = c = getch()))
- ;
-
- s[i] = '\0';
-
- if (c != EOF)
- ungetch(c);
-
- return NUMBER;
-}
-
-char buf[BUFSIZE];
-int bufp = 0;
-
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
-
-void ungetch(int c) {
- if (bufp >= BUFSIZE)
- printf("ungetch: too many characters\n");
- else
- buf[bufp++] = c;
-}
diff --git a/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst
index afea4960..128231ff 100644
--- a/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst
+++ b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst
@@ -14,7 +14,7 @@ getch and ungetch unnecessary. Revise the calculator to use this approach.
Explanation
===========
-This program uses `mgetline` to get the characters and operands from the input
+This program uses `_getline` to get the characters and operands from the input
and and proceeds with the RPN calculator logic.
This is the main part of the program.
@@ -29,7 +29,7 @@ This is the main part of the program.
int c,i;
if(line[li] == '\0')
- if(mgetline(line,MAXLINE) == 0)
+ if(_getline(line,MAXLINE) == 0)
return EOF;
else
li =0;
@@ -59,7 +59,7 @@ This is the main part of the program.
}
-From the mgetline function, it takes the input in the line character array, and
+From the _getline function, it takes the input in the line character array, and
if if the line is `\0` only, then we define that as EOF and return `EOF`. Then
we assign to `c` the value present at `line` and look for various conditions
like, if line is a space or tab character, we simply skip it. If we encouter c
@@ -79,9 +79,6 @@ An example execution will look like this.
Visualize It
============
-.. raw:: html
-
-
* https://pythontutor.com/c.html
Try It
diff --git a/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst
index 3b4ac759..14f507ba 100644
--- a/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst
+++ b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst
@@ -15,7 +15,7 @@ design.
Explanation
===========
-The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZ]`.
+The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZE]`.
This has a limitation wherein the when an `EOF` character is encountered, it
wont be stored in the buffer. The EOF character is an integer type. This problem
can be solved by declaring our buf to be of integer type, like `int
diff --git a/source/cprogramming/chapter4/index.rst b/source/cprogramming/chapter4/index.rst
index 628efb96..9d7c2c94 100644
--- a/source/cprogramming/chapter4/index.rst
+++ b/source/cprogramming/chapter4/index.rst
@@ -5,8 +5,6 @@ Chapter 4
.. toctree::
:maxdepth: 1
- ex_4.1_strindex_rightmost
- ex_4.2_atof_scientific
ex_4.1_strindex_rightmost
ex_4.2_atof_scientific
ex_4.3_rpn_modulus_negative
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c b/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c
deleted file mode 100644
index 6ad8ec41..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c
+++ /dev/null
@@ -1,134 +0,0 @@
-/* Revise the Calculator program to use the getline instead of getch and ungetch
- */
-
-#include
-#include /* for atof() */
-
-#define MAXOP 100
-#define NUMBER '0'
-
-int getop(char[]);
-void push(double);
-double pop(void);
-
-/* reverse polish notation calculator */
-
-int main(void) {
- int type;
- double op2;
- char s[MAXOP];
-
- while ((type = getop(s)) != EOF) {
- switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- break;
- case '\n':
- printf("\t%.9g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
- }
- }
- return 0;
-}
-
-#define MAXVAL 100 /* maximum depth of the val stack */
-
-int sp = 0;
-double val[MAXVAL];
-
-/* push : push f onto value stack */
-
-void push(double f) {
- if (sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error: stack full,can't push %g\n", f);
-}
-
-/* pop: pop and return top values from stack */
-
-double pop(void) {
- if (sp > 0)
- return val[--sp];
- else {
- printf("error: stack empty \n");
- return 0.0;
- }
-}
-
-/* using getline instead of getch and ungetch */
-
-#include
-#define MAXLINE 100
-
-int mgetline(char line[], int limit);
-
-int li = 0; /* input line index */
-char line[MAXLINE]; /* one input line */
-
-/* getop: get next operator or numeric operand */
-
-int getop(char s[]) {
- int c, i;
-
- if (line[li] == '\0')
- if (mgetline(line, MAXLINE) == 0)
- return EOF;
- else
- li = 0;
-
- while ((s[0] = c = line[li++]) == ' ' || c == '\t')
- ;
-
- s[1] = '\0';
-
- if (!isdigit(c) && c != '.')
- return c;
-
- i = 0;
-
- if (isdigit(c))
- while (isdigit(s[++i] = c = line[li++]))
- ;
- if (c == '.')
- while (isdigit(s[++i] = c = line[li++]))
- ;
-
- s[i] = '\0';
-
- li--;
-
- return NUMBER;
-}
-
-int mgetline(char s[], int lim) {
- int i, c;
-
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n')
- s[i++] = c;
-
- s[i] = '\0';
-
- return i;
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c b/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c
deleted file mode 100644
index 25946373..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c
+++ /dev/null
@@ -1,122 +0,0 @@
-/* modify getop so that it does not need to use ungetch: Hint: static int lastc
- */
-
-#include
-#include
-
-#define MAXOP 100
-#define NUMBER '0'
-
-int getop(char[]);
-void push(double);
-double pop(void);
-
-/* reverse polish calculator */
-
-int main(void) {
- int type;
- double op2;
- char s[MAXOP];
-
- while ((type = getop(s)) != EOF) {
- switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
- }
- }
- return 0;
-}
-
-#define MAXVAL 100
-
-int sp = 0;
-double val[MAXVAL];
-
-/* push : push f onto value stack */
-
-void push(double f) {
- if (sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error: stack full,can't push %g\n", f);
-}
-
-/* pop: pop and return top value from stack */
-
-double pop(void) {
- if (sp > 0)
- return val[--sp];
- else {
- printf("error: stack empty\n");
- return 0.0;
- }
-}
-
-#include
-
-int getch(void);
-
-/* getop: get next operator or numeric operand */
-
-int getop(char s[]) {
- int c, i;
- static int lastc = 0;
-
- if (lastc == 0)
- c = getch();
- else {
- c = lastc;
- lastc = 0;
- }
-
- while ((s[0] = c) == ' ' || c == '\t')
- c = getch();
-
- s[1] = '\0';
-
- if (!isdigit(c) && c != '.')
- return c;
-
- i = 0;
- if (isdigit(c))
- while (isdigit(s[++i] = c = getch()))
- ;
- if (c == '.')
- while (isdigit(s[++i] = c = getch()))
- ;
- s[i] = '\0';
-
- if (c != EOF)
- lastc = c;
-
- return NUMBER;
-}
-
-#define BUFSIZE 100
-
-char buf[BUFSIZE];
-int bufp;
-
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c b/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c
deleted file mode 100644
index d34514f4..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* recursive version of itoa; that converts an integer string by calling a
- * recursive routine */
-
-#include
-#include
-
-#define MAXLEN 100
-
-void itoa(int n, char s[]);
-
-int main(void) {
- int n;
- char s[MAXLEN];
-
- n = 1723;
-
- itoa(n, s);
-
- printf("%s", s);
-
- return 0;
-}
-
-void itoa(int n, char s[]) {
- static int i;
-
- if (n / 10)
- itoa(n / 10, s);
- else {
- i = 0;
- if (n < 0)
- s[i++] = '-';
- }
-
- s[i++] = abs(n) % 10 + '0';
-
- s[i] = '\0';
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c b/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c
deleted file mode 100644
index ee9785c0..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/* a recursive version of revese(s); the string reverse function */
-
-#include
-#include
-
-#define MAXLINE 100
-
-int mgetline(char line[], int maxline);
-void reverse(char s[]);
-
-int main(void) {
- char s[MAXLINE];
-
- mgetline(s, MAXLINE);
-
- reverse(s);
-
- printf("%s", s);
-
- return 0;
-}
-
-int mgetline(char s[], int lim) {
- int i, c;
-
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n')
- s[i++] = '\n';
-
- s[i] = '\0';
-}
-
-void reverse(char s[]) {
-
- static int i = 0;
- static int len;
-
- int j;
- char c;
-
- if (i == 0) {
- len = strlen(s);
- }
-
- j = len - (i + 1);
-
- if (i < j) {
- c = s[i];
- s[i] = s[j];
- s[j] = c;
- i++;
- reverse(s);
- }
-
- // the algorithm has finished so we have to set i=0 again
- else {
- i = 0;
- }
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c b/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c
deleted file mode 100644
index 06ddf692..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c
+++ /dev/null
@@ -1,20 +0,0 @@
-/* a macro swap(t,x,y) that interchanges two arguments of type t */
-
-#include
-
-#define swap(t, x, y) \
- { \
- t _z; \
- _z = x; \
- x = y; \
- y = _z; \
- }
-
-int main(void) {
- char x, y;
- x = 'a';
- y = 'b';
- printf("x= %c \t y= %c\n", x, y);
- swap(char, x, y);
- printf("x=%c \t y=%c\n", x, y);
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c b/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c
deleted file mode 100644
index 2468b1e7..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c
+++ /dev/null
@@ -1,32 +0,0 @@
-/* strindex which returns rightmost occurance */
-
-#include
-
-int mstrindex(char source[], char searchfor[]);
-
-int main(void) {
- char line[] = "abcdedfabcde";
- char pattern[] = "abc";
-
- int found;
-
- /* It should match the a the 7th position. */
-
- found = mstrindex(line, pattern);
-
- printf("Found the right index: %d\n", found);
-}
-
-int mstrindex(char s[], char t[]) {
- int i, j, k, result;
-
- result = -1;
-
- for (i = 0; s[i] != '\0'; i++) {
- for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
- ;
- if (k > 0 && t[k] == '\0')
- result = i;
- }
- return result;
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c b/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c
deleted file mode 100644
index dfe9c2aa..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/* Program demonstrating atof(char s[]).The function which converts the string
- to a floating point value */
-#include
-#include
-#define MAXLINE 100
-
-double myatof(char s[]);
-int mgetline(char line[], int maxline);
-
-int main(void) {
- char str[MAXLINE];
- double num;
- mgetline(str, MAXLINE);
-
- num = myatof(str);
- printf("%f", num);
-
- return 0;
-}
-
-double myatof(char s[]) {
- double val, pow;
- int sign, i, esign, exp;
- int power(int base, int exp);
-
- for (i = 0; isspace(s[i]); i++)
- ;
-
- sign = (s[i] == '-') ? -1 : 1;
-
- if (s[i] == '+' || s[i] == '-')
- i++;
-
- for (val = 0.0; isdigit(s[i]); i++)
- val = 10.0 * val + (s[i] - '0');
-
- if (s[i] == '.')
- i++;
-
- for (pow = 1.0; isdigit(s[i]); i++) {
- val = 10.0 * val + (s[i] - '0');
- pow *= 10.0;
- }
-
- if (s[i] == 'e' || s[i] == 'E')
- i++;
- if (s[i] == '+' || s[i] == '-') {
- esign = s[i];
- i++;
- }
-
- for (exp = 0; isdigit(s[i]); i++)
- exp = 10.0 * exp + (s[i] - '0');
-
- if (esign == '-')
- return sign * (val / pow) / power(10, exp);
- else
-
- return sign * (val / pow) * power(10, exp);
-}
-
-int mgetline(char s[], int lim) {
- int i, c;
-
- for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
- s[i] = c;
-
- if (c == '\n')
- s[i++] = c;
-
- s[i] = '\0';
-}
-
-int power(int base, int exp) {
- int power;
- power = 1;
- while (exp-- > 0)
- power *= base;
-
- return power;
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c b/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c
deleted file mode 100644
index 496373a0..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c
+++ /dev/null
@@ -1,128 +0,0 @@
-/* Adding the Modulus operator and provision for negative numbers
- * Program is given the input in a single and and it print the output upon
- * getting a \n character.
- * For e.g:
- *
- * 10 10 + 100 + 2 *
- * 240
- */
-
-#include
-#include
-#include
-
-#define MAXOP 100
-#define NUMBER '0'
-
-int getop(char[]);
-void push(double);
-double pop(void);
-
-/* reverse polish calculator */
-
-int main(void) {
- int type;
- double op2;
- char s[MAXOP];
-
- while ((type = getop(s)) != EOF) {
- switch (type) {
- case NUMBER:
- push(atof(s));
- break;
- case '+':
- push(pop() + pop());
- break;
- case '*':
- push(pop() * pop());
- break;
- case '-':
- op2 = pop();
- push(pop() - op2);
- break;
- case '/':
- op2 = pop();
- if (op2 != 0.0)
- push(pop() / op2);
- else
- printf("error:zero divisor\n");
- break;
- case '%':
- op2 = pop();
- if (op2 != 0.0)
- push(fmod(pop(), op2));
- else
- printf("erro:zero divisor\n");
- break;
- case '\n':
- printf("\t%.8g\n", pop());
- break;
- default:
- printf("error: unknown command %s\n", s);
- break;
- }
- }
- return 0;
-}
-
-#define MAXVAL 100
-
-int sp = 0;
-double val[MAXVAL];
-
-void push(double f) {
- if (sp < MAXVAL)
- val[sp++] = f;
- else
- printf("error:stack full, cant push %g\n", f);
-}
-
-double pop(void) {
- if (sp > 0)
- return val[--sp];
- else {
- printf("error: stack empty\n");
- return 0.0;
- }
-}
-
-#include
-
-int getch(void);
-void ungetch(int);
-
-int getop(char s[]) {
- int i, c;
- while ((s[0] = c = getch()) == ' ' || c == '\t')
- ;
- s[1] = '\0';
- if (!isdigit(c) && c != '.' && c != '-')
- return c; // not a number
- i = 0;
- if (c == '-' || isdigit(c)) // collect integer part along with '-'
- while (isdigit(s[++i] = c = getch()))
- ;
- if (c == '.') // collect fraction part
- while (isdigit(s[++i] = c = getch()))
- ;
- s[i] = '\0';
- if (c != EOF)
- ungetch(c);
- if (strcmp(s, "-") == 0)
- return '-';
- return NUMBER;
-}
-
-#define BUFSIZE 100
-
-char buf[BUFSIZE];
-int bufp = 0;
-
-int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); }
-
-void ungetch(int c) {
- if (bufp >= BUFSIZE)
- printf("ungetch: too many characters\n");
- else
- buf[bufp++] = c;
-}
diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c b/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c
deleted file mode 100644
index ad91c978..00000000
--- a/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Add commands to
- - print top element of the stack,without poping
- - duplicate it
- - swap the top two elements
- - Clear the stack */
-
-#include