From fb0ca5ce7356a129fb9c1e1d0bb91f0a9eca27fc Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 20 Apr 2020 10:40:34 -0700 Subject: [PATCH 001/251] Update version and release. --- source/conf.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index f5a3a631..9035c093 100644 --- a/source/conf.py +++ b/source/conf.py @@ -68,9 +68,9 @@ # built documents. # # The short X.Y version. -version = '' +version = '0.1' # The full version, including alpha/beta/rc tags. -release = '0.1' +release = '0.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. From 5b7eb21e24d9708443f3ed2fedde56ba864cd0f5 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 20 Apr 2020 12:33:15 -0700 Subject: [PATCH 002/251] Update conf.py --- source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index de89984e..fdf223db 100644 --- a/source/conf.py +++ b/source/conf.py @@ -70,7 +70,7 @@ # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. -release = '0.2' +release = 'alpha-1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. From 15ab5b968472c40605afa4cf4bd142b7a6682c32 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 20 Apr 2020 12:53:35 -0700 Subject: [PATCH 003/251] Update atoi v2 --- languages/cprogs/atoiv2.c | 41 +++++++++++++++++----------------- source/cprogramming/atoiv2.rst | 4 ++++ 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/languages/cprogs/atoiv2.c b/languages/cprogs/atoiv2.c index 978afcdf..40868701 100644 --- a/languages/cprogs/atoiv2.c +++ b/languages/cprogs/atoiv2.c @@ -1,34 +1,33 @@ /* Ex5.6 */ -#include -#include +#include +#include + int atoiv2(char *); -int main(void) -{ - char *s="1234"; - int ret; +int main(void) { + char *s = "1234"; + int ret; - ret=atoiv2(s); + ret = atoiv2(s); - printf("%d",ret); + printf("%d", ret); - return 0; + return 0; } -int atoiv2(char *s) -{ - int n,sign; +int atoiv2(char *s) { + int n, sign; + + for (; isspace(*s); s++) /* skip white space */ + ; + sign = (*s == '-') ? -1 : 1; - 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'; - if(*s=='+' || *s=='-') - s++; - for(n=0;isdigit(*s);s++) - n = 10 *n + *s - '0'; - - return sign * n; + return sign * n; } diff --git a/source/cprogramming/atoiv2.rst b/source/cprogramming/atoiv2.rst index 978a61f1..92672e75 100644 --- a/source/cprogramming/atoiv2.rst +++ b/source/cprogramming/atoiv2.rst @@ -9,6 +9,10 @@ atoiv2 :tab-width: 4 +.. raw:: html + + + .. seealso:: From 8536e788d2db9ede0620738fa8d28b5bd523ebc0 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Thu, 23 Apr 2020 10:53:43 -0700 Subject: [PATCH 004/251] update source and layout. --- source/_templates/layout.html | 3 --- source/_templates/logo.html | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/source/_templates/layout.html b/source/_templates/layout.html index 82a3aa35..4855265a 100644 --- a/source/_templates/layout.html +++ b/source/_templates/layout.html @@ -7,9 +7,6 @@ {%- block footer %} {{ super() }} {%- endblock %} From 193de2e8b1fdcb09823d24dd53a1518834a04515 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 4 Mar 2024 04:51:28 -0800 Subject: [PATCH 119/251] RPN Calculator. Exercise 4.3 --- .../cprogs/Ex_4.3_rpn_modulus_negative.c | 225 ++++++++---------- 1 file changed, 105 insertions(+), 120 deletions(-) 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; } - From cfbcf4681917cca586d699185ed196b1c73e1354 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:00:48 -0800 Subject: [PATCH 120/251] Updated Count Ranges in C. --- .../chapter2/cprogs/ex_2.1_cal_limits.c | 54 +++++++++++-------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c index 2c32e0d3..6a3b8115 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c @@ -1,17 +1,29 @@ -/*** - * +/** * Exercise 2.1 * - * Program to print maximum, minimum limits of char, int, long using - * calculation + * Write a program to print maximum, minimum limits of char, int, long using + * calculation. * - ***/ + */ -/* The logic used is +/** + * Priminary Information: + * * ~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 + * >> 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 @@ -22,24 +34,24 @@ 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 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 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 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)); + 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); + 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"); From 5e16d4f701795afb916fdbf7f0b7284eb70850bf Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:01:39 -0800 Subject: [PATCH 121/251] Fix Typo. --- source/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/index.rst b/source/index.rst index 996c5762..ef961a19 100644 --- a/source/index.rst +++ b/source/index.rst @@ -1,7 +1,7 @@ Learn To Solve It ================= -This is a companinon website to learn C programming using K&R book. +This is a companion 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 as the platform to learn Programming and From c76a0fe735c4423a359282bf706c1ce4c0f66764 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:01:59 -0800 Subject: [PATCH 122/251] Updated Any Long Line Length. --- languages/cprogs/anylonglinelen.c | 89 +++++++++++++++---------------- 1 file changed, 42 insertions(+), 47 deletions(-) diff --git a/languages/cprogs/anylonglinelen.c b/languages/cprogs/anylonglinelen.c index d55e45e6..ce53eacb 100644 --- a/languages/cprogs/anylonglinelen.c +++ b/languages/cprogs/anylonglinelen.c @@ -1,62 +1,57 @@ -/* Program to print the longest line. - This program prints the length of any-length line with as much possible text it can hold */ +/** + * Program to print the longest line. + * This program prints the length of any-length line with as much possible + * text it can hold. + **/ -#include +#include #define MAXLINE 1000 -int getline(char line[],int lim); -void copy(char to[],char from[]); +int getline(char line[], int lim); +void copy(char to[], char from[]); -int main(void) -{ - int len,max; - char line[MAXLINE],maxline[MAXLINE]; +int main(void) { + int len, max; + char line[MAXLINE], maxline[MAXLINE]; - max = 0; + 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); + 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; + 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; +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; +void copy(char to[], char from[]) { + int i; - i=0; + i = 0; - while((to[i]=from[i]) != '\0') - ++i; + while ((to[i] = from[i]) != '\0') + ++i; } - From fb3e18db3a2a781be07a3ab391d5649f2069a403 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:15:00 -0800 Subject: [PATCH 123/251] Updated README. --- README.md | 20 ++++++++++++++++++++ README.rst | 16 ---------------- 2 files changed, 20 insertions(+), 16 deletions(-) create mode 100644 README.md delete mode 100644 README.rst diff --git a/README.md b/README.md new file mode 100644 index 00000000..4c44b9e2 --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +# 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 and practice with a dedicated community. + +### Reference Books + +* C Programming Language by Kernighan and Ritchie. + + +[![Netlify Status](https://api.netlify.com/api/v1/badges/27a766e4-762c-420f-92e2-f35441c79f63/deploy-status)](https://app.netlify.com/sites/learntosolveit/deploys) +[![Documentation Status](https://readthedocs.org/projects/learntosolveit/badge/?version=latest)](http://www.learntosolveit.com/?badge=latest) + + +## Contact + +* 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 c7de4076..00000000 --- a/README.rst +++ /dev/null @@ -1,16 +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 - - -Contact -------- - -* `Senthil Kumaran`_ - -.. _Senthil Kumaran: https://senthil.learntosolveit.com From 34c8c0d8c8b08d9769857b15b6a4af113ecef9d7 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:37:41 -0800 Subject: [PATCH 124/251] Updated README.md --- README.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4c44b9e2..3b982896 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,18 @@ [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 and practice with a dedicated community. +To practice the exercises, you can use the online compilers like + +* [https://www.tutorialspoint.com/compile_c_online.php](https://www.tutorialspoint.com/compile_c_online.php) +* [https://replit.com/](https://replit.com/) +* [https://www.jdoodle.com/c-online-compiler](https://www.jdoodle.com/c-online-compiler) +* [https://www.onlinegdb.com/online_c_compiler](https://www.onlinegdb.com/online_c_compiler) +* [https://www.codechef.com/ide](https://www.codechef.com/ide) +* [https://www.programiz.com/c-programming/online-compiler/](https://www.programiz.com/c-programming/online-compiler/). + +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. ### Reference Books @@ -17,4 +28,3 @@ I recommend [https://exercism.org](https://exercism.org) as the platform to lear * Email: [senthil@uthcode.com](mailto:senthil@uthcode.com) * Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com) - From c3a0fd12525a2a26d453e752bf40f62a23b80fd1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:43:19 -0800 Subject: [PATCH 125/251] Fix the Limits Program. --- .../chapter2/ex_2.1_cal_limits.rst | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst index 788cdb97..a81d7f72 100644 --- a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst +++ b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst @@ -20,18 +20,34 @@ 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 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 + Maximum Unsigned Char 255 + Maximum Unsigned Short 65535 + Maximum Unsigned Int 4294967295 + Maximum Unsigned 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. From f5cb7c0ea611ce97ae08f3cd42c3ceebbb78bd03 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 07:59:43 -0800 Subject: [PATCH 126/251] Added Author Information. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b982896..317ba80d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,8 @@ motivated developers. [![Documentation Status](https://readthedocs.org/projects/learntosolveit/badge/?version=latest)](http://www.learntosolveit.com/?badge=latest) -## Contact +## Author +* Senthil Kumaran * Email: [senthil@uthcode.com](mailto:senthil@uthcode.com) * Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com) From 1e8ce24d9ae088d887e58e4b6b6b61d2252f21a3 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 9 Mar 2024 09:51:48 -0800 Subject: [PATCH 127/251] Added Link to Analytics. --- utils/analytics.txt | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 utils/analytics.txt diff --git a/utils/analytics.txt b/utils/analytics.txt new file mode 100644 index 00000000..1623eecc --- /dev/null +++ b/utils/analytics.txt @@ -0,0 +1,4 @@ +# Analytics + +https://analytics.eu.umami.is/websites/2df1f153-8058-48a6-bd46-c623df582814/realtime + From dbb1d06ffafea43f61c3d38ef88800b722feca34 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 10 Mar 2024 20:11:03 -0700 Subject: [PATCH 128/251] Calculate the limits. --- .../chapter2/cprogs/ex_2.1_cal_limits.c | 21 ++++++++++++++++--- .../chapter2/ex_2.1_cal_limits.rst | 11 +++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c index 6a3b8115..a8714483 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c @@ -31,7 +31,7 @@ #include int main() { - /* ranges of various floating-point types through calculation */ + /* ranges of various integer 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); @@ -53,8 +53,10 @@ int main() { printf("Maximum Unsigned Int %u\n", (unsigned int)~0); printf("Maximum Unsigned Long %lu\n\n", (unsigned long)~0); + /* 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 floating-point types from standard headers:\n"); + 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); @@ -67,12 +69,25 @@ int main() { 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/ex_2.1_cal_limits.rst b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst index a81d7f72..42c1dc30 100644 --- a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst +++ b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst @@ -34,7 +34,7 @@ The execution of the above program will give:: Maximum Unsigned Int 4294967295 Maximum Unsigned Long 18446744073709551615 - Ranges of various floating-point types from standard headers: + Ranges of various integer and floating-point types from standard headers: Minimum Signed Char -128 Maximum Signed Char 127 Minimum Signed Short -32768 @@ -43,10 +43,19 @@ The execution of the above program will give:: 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 From 6eb76d6c9a12a6a456e19fd7c0ef81b2f9cf2848 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 11 Mar 2024 06:26:18 -0700 Subject: [PATCH 129/251] Updated to correct casting. --- .../chapter2/cprogs/ex_2.1_cal_limits.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c index a8714483..2377662e 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c @@ -32,13 +32,13 @@ int main() { /* ranges of various integer types through calculation */ - printf("Ranges of various floating-point types through calculation:\n"); + printf("Ranges of various integer 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 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", -(short)((unsigned short)~0 >> 1) - 1); - printf("Maximum Signed Short %d\n", (short)((unsigned short)~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)); @@ -51,7 +51,7 @@ int main() { 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); + 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 */ @@ -70,7 +70,7 @@ int main() { 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("Maximum Signed Long Long %lld\n", LLONG_MAX); printf("Minimum Float %E\n", FLT_MIN); printf("Maximum Float %E\n", FLT_MAX); From 50d67001bb210c65e2872bc6bcef717b6af0449e Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Tue, 12 Mar 2024 22:02:26 -0700 Subject: [PATCH 130/251] Updated htoi. --- .../chapter2/cprogs/ex_2.3_htoi.c | 66 ++++++++----------- 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c index a0ad5c44..e3c19907 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c @@ -6,22 +6,21 @@ #include #define MAXLINE 100 - -#define YES 1 -#define NO 0 +#define BASE 16 int mgetline(char line[], int lim); -int htoi(const char s[]); +unsigned int htoi(const char s[], int len); int main(void) { char line[MAXLINE]; - int value; + int len; + unsigned int value; - mgetline(line, MAXLINE); - value = htoi(line); + len = mgetline(line, MAXLINE); + value = htoi(line, len); - printf("The value of %s is %d", line, value); + printf("The value of %s is %u \n", (char *) line, value); return 0; } @@ -30,41 +29,34 @@ int mgetline(char line[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - line[i] = c; + line[i] = (char) c; - if (c == '\n') { - line[i] = c; - ++i; - } line[i] = '\0'; return i; } -int htoi(const char s[]) { - int hexdigit, i, inhex, n; - i = 0; - if (s[i] == '0') { - ++i; - if (s[i] == 'x' || s[i] == 'X') - ++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; } - 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; + 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 n; -} + + return result; +} \ No newline at end of file From 03e01dc1ad9b9f153c5f11f98a9a270f9d740e18 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 15 Mar 2024 06:45:25 -0700 Subject: [PATCH 131/251] Updated Exercise 2.4 Squeezes. --- .../chapter2/cprogs/ex_2.4_squeezess.c | 21 ++++++++-------- .../chapter2/ex_2.4_squeezess.rst | 25 +++++++++++++++++-- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c index ae6dc876..3c91036f 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c @@ -2,7 +2,9 @@ * 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. * **/ @@ -10,24 +12,18 @@ #define MAXLINE 1000 -int mgetline(char line[], int lim); +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; } @@ -42,6 +38,8 @@ int mgetline(char s[], int lim) { s[i++] = c; s[i] = '\0'; + + return i; } void squeeze(char s1[], const char s2[]) { @@ -49,10 +47,11 @@ void squeeze(char s1[], const char s2[]) { k = 0; for (i = 0; s1[i] != '\0'; ++i) { - for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j); + for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j) + ; if (s2[j] == '\0') s1[k++] = s1[i]; } s1[k] = '\0'; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/ex_2.4_squeezess.rst b/source/cprogramming/chapter2/ex_2.4_squeezess.rst index d8fffea7..613fb0da 100644 --- a/source/cprogramming/chapter2/ex_2.4_squeezess.rst +++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst @@ -16,12 +16,15 @@ Explanation Let's take the two inputs strings as: - s1: HelloWorld +.. code-block:: bash - s2: ol + HelloWorld + ol Our desired output is:: +.. code-block:: bash + HeWrd This has removed the characters `o` and `l` from the first string. The way @@ -29,6 +32,8 @@ 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:: +.. code-block:: c + for(j=0; (s1[i]!=s2[j]) && s2[j]!='\0' ;++j) ; if(s2[j]=='\0') @@ -38,3 +43,19 @@ 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 + + From 1f32ced6b641a1b7439652f882c7c7dd2ceec5e2 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 15 Mar 2024 06:51:44 -0700 Subject: [PATCH 132/251] Fixed the Code Blocks. --- source/cprogramming/chapter2/ex_2.4_squeezess.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/cprogramming/chapter2/ex_2.4_squeezess.rst b/source/cprogramming/chapter2/ex_2.4_squeezess.rst index 613fb0da..bba681bb 100644 --- a/source/cprogramming/chapter2/ex_2.4_squeezess.rst +++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst @@ -21,16 +21,16 @@ Let's take the two inputs strings as: HelloWorld ol -Our desired output is:: +Our desired output is .. code-block:: bash - HeWrd + 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 From 2ac3fd475ed75ea654a23b44442c5595da0d1bb1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Mar 2024 18:57:54 -0700 Subject: [PATCH 133/251] updated exercise htoi. --- source/cprogramming/chapter2/ex_2.3_htoi.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst index d8dd64ac..e60cfb0e 100644 --- a/source/cprogramming/chapter2/ex_2.3_htoi.rst +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -85,3 +85,15 @@ For example to convert **0XAF**. = 175 **175** + +.. raw:: html + + + +Try It Out +========== + + +.. raw:: html + + From 1641fb708446658c408c275c70a553f4af2a60cf Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Mar 2024 19:39:48 -0700 Subject: [PATCH 134/251] Added Visualization. --- source/cprogramming/chapter2/ex_2.3_htoi.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst index e60cfb0e..2823cb1d 100644 --- a/source/cprogramming/chapter2/ex_2.3_htoi.rst +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -86,6 +86,9 @@ For example to convert **0XAF**. **175** +Visualization +============= + .. raw:: html From bf6c62fdb1623f8276ddd5a61222f8dc8e75c784 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Mar 2024 22:29:24 -0700 Subject: [PATCH 135/251] formatting. --- source/cprogramming/chapter2/ex_2.3_htoi.rst | 30 +++++++++++--------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst index 2823cb1d..c3d2e7b6 100644 --- a/source/cprogramming/chapter2/ex_2.3_htoi.rst +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -67,24 +67,28 @@ 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** +.. raw:: + + 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 ============= From 429ad9385cc7b02915c963db75482855202ec1a7 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Mar 2024 22:43:16 -0700 Subject: [PATCH 136/251] Formatting. --- source/cprogramming/chapter2/ex_2.3_htoi.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst index c3d2e7b6..520afa17 100644 --- a/source/cprogramming/chapter2/ex_2.3_htoi.rst +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -74,7 +74,7 @@ we mutiply by 16 and add hexdigit. For example to convert **0XAF**. -.. raw:: +.. code:: 1. We strip off 0X. 2. For A, we get the value hexdigit = 10 From ed9ceed4dcb63d5a0a7caea48d437c31f7313744 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 07:46:00 -0700 Subject: [PATCH 137/251] Exercise 2.5; Using any function. --- source/cprogramming/chapter2/cprogs/ex_2.5_any.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c index e1e5a91f..28f583dc 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c @@ -20,12 +20,7 @@ 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); @@ -50,15 +45,14 @@ int any(char s1[], const char s2[]) { 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 + 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. + if (s2[j] != '\0' && s2[j] != '\n') { + // Due to custom getline function, we need to check for newline return i; } } return -1; -} \ No newline at end of file +} From f1b322343a737158f66114cd2f745759c26ca680 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 08:03:41 -0700 Subject: [PATCH 138/251] Updated Any Documentation. --- source/cprogramming/chapter2/ex_2.4_squeezess.rst | 1 - source/cprogramming/chapter2/ex_2.5_any.rst | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/source/cprogramming/chapter2/ex_2.4_squeezess.rst b/source/cprogramming/chapter2/ex_2.4_squeezess.rst index bba681bb..4a402b69 100644 --- a/source/cprogramming/chapter2/ex_2.4_squeezess.rst +++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst @@ -55,7 +55,6 @@ Visualization 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 e6d5fc3e..2e70015d 100644 --- a/source/cprogramming/chapter2/ex_2.5_any.rst +++ b/source/cprogramming/chapter2/ex_2.5_any.rst @@ -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 + + From c58c7f2412bd703ca0af0532ffd330d3578f0656 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 08:38:51 -0700 Subject: [PATCH 139/251] Updated any function. --- source/cprogramming/chapter2/cprogs/ex_2.5_any.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c index 28f583dc..55f13956 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c @@ -38,19 +38,18 @@ int mgetline(char line[], int lim) { 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) { - // 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') { - // Due to custom getline function, we need to check for newline - return i; + for (j = 0; s2[j] != '\0'; ++j) { + if (s1[i] == s2[j]) { + return i; + } } } From 614f7e5eb48b5787043da2e1e1fb729d5c065ca2 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 08:41:36 -0700 Subject: [PATCH 140/251] Updated Exercise 2.5 Any --- source/cprogramming/chapter2/ex_2.5_any.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter2/ex_2.5_any.rst b/source/cprogramming/chapter2/ex_2.5_any.rst index 2e70015d..e7f8b697 100644 --- a/source/cprogramming/chapter2/ex_2.5_any.rst +++ b/source/cprogramming/chapter2/ex_2.5_any.rst @@ -36,7 +36,7 @@ Visualization .. raw:: html - + Try It Out ========== From eb2d56661f01ac4e34fa10df40720bcd3e9289d3 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 08:49:43 -0700 Subject: [PATCH 141/251] Updated Exercise 2.5 --- source/cprogramming/chapter2/cprogs/ex_2.5_any.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c index 55f13956..072ec593 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c @@ -47,7 +47,7 @@ int any(char s1[], const char s2[]) { for (i = 0; s1[i] != '\0'; ++i) { for (j = 0; s2[j] != '\0'; ++j) { - if (s1[i] == s2[j]) { + if (s1[i] == s2[j] && s1[i] != '\n') { return i; } } From bdf91cfff8d720b2a70f6e7277149f1113c43b2b Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 09:54:22 -0700 Subject: [PATCH 142/251] Set Bits. --- source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c index d7f7c4bb..de98fdb9 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c @@ -1,7 +1,7 @@ /** * * 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 + * n bits that begin at position p set to the rightmost n bits of y,leaving * the other bits unchanged. **/ @@ -9,7 +9,9 @@ unsigned setbits(unsigned x, int p, int n, unsigned y); -int main(void) { printf("%u", setbits((unsigned) 12, 3, 2, (unsigned) 57)); } +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)); From 86f092f42dbcaf1c7108bae85a6b362cbe8ecefe Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 09:57:03 -0700 Subject: [PATCH 143/251] Updated Chapter1. --- source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst | 1 - source/cprogramming/chapter1/sec_1.1_helloworld.rst | 9 --------- 2 files changed, 10 deletions(-) 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/sec_1.1_helloworld.rst b/source/cprogramming/chapter1/sec_1.1_helloworld.rst index 136f2695..9fa93ea3 100644 --- a/source/cprogramming/chapter1/sec_1.1_helloworld.rst +++ b/source/cprogramming/chapter1/sec_1.1_helloworld.rst @@ -19,12 +19,3 @@ Solution .. literalinclude:: cprogs/sec_1.1_helloworld.c :language: c - - -Visualize It -============ - -.. raw:: html - - - From f5b93371a3e876ef282a29a2cc301636a022a55d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 10:16:21 -0700 Subject: [PATCH 144/251] Fix the formatting error. --- source/cprogramming/chapter1/sec_1.2_fahr2cel.rst | 13 ------------- 1 file changed, 13 deletions(-) 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| From f064512d241df9708bb782afa3433cb7b02d5dbd Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Mar 2024 19:28:42 -0700 Subject: [PATCH 145/251] Update C Programming. --- source/cprogramming/chapter1/ex_1.11_test_word_count.rst | 3 +-- source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst | 2 +- source/cprogramming/chapter1/index.rst | 2 +- source/cprogramming/chapter1/sec_1.4_symbolic.rst | 6 +----- source/cprogramming/chapter1/sec_1.5.1_file_copying.rst | 7 +------ source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c | 5 +++-- 6 files changed, 8 insertions(+), 17 deletions(-) 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 17aecd5e..d6e122e6 100644 --- a/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst +++ b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst @@ -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/index.rst b/source/cprogramming/chapter1/index.rst index f5c1d4f0..5a19106a 100644 --- a/source/cprogramming/chapter1/index.rst +++ b/source/cprogramming/chapter1/index.rst @@ -41,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.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 4f0e5938..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,9 +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/chapter5/cprogs/ex_5.8_day_date.c b/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c index eb591c40..9d784d8a 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c @@ -1,6 +1,7 @@ /* * Error check in day_of_year and month_day */ + #include static char daytab[2][13] = { @@ -35,7 +36,7 @@ int main(void) { int day_of_year(int year, int month, int day) { int i, leap; - leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; if (year < 1 || month < 1 || month > 12 || day < 1 || day > daytab[leap][month]) return -1; @@ -51,7 +52,7 @@ int day_of_year(int year, int month, int day) { void month_day(int year, int yearday, int *month, int *day) { int i, leap; - leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; + leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; if (year < 1 || yearday < 1 || yearday > (leap ? 366 : 365)) { *month = -1; From 85cc4afd17e241791d79d8b79a7b05a27f037fcd Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Mar 2024 04:29:19 -0700 Subject: [PATCH 146/251] Fix Heading. --- .../cprogramming/chapter1/ex_1.3_fahr2celheading.rst | 11 +++++------ source/cprogramming/chapter1/ex_1.6_verifyeof.rst | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) 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. From 776a9fa68b803211323e63b7628aa88921a10301 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Mar 2024 04:34:15 -0700 Subject: [PATCH 147/251] Updated Exercise 2.8 Right Rotation. --- .../chapter2/cprogs/ex_2.8_rightrot.c | 5 ++++- .../cprogramming/chapter2/ex_2.8_rightrot.rst | 22 +++++++++++-------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c b/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/ex_2.8_rightrot.rst b/source/cprogramming/chapter2/ex_2.8_rightrot.rst index dd0b24de..3c44c963 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,13 @@ 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). From e37a00548a6a507055682cf34173d50eadb439c4 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Mar 2024 04:52:51 -0700 Subject: [PATCH 148/251] Right Rotation. --- source/cprogramming/chapter2/ex_2.8_rightrot.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/source/cprogramming/chapter2/ex_2.8_rightrot.rst b/source/cprogramming/chapter2/ex_2.8_rightrot.rst index 3c44c963..e0807a05 100644 --- a/source/cprogramming/chapter2/ex_2.8_rightrot.rst +++ b/source/cprogramming/chapter2/ex_2.8_rightrot.rst @@ -78,3 +78,10 @@ see "n" as condition 2. The result should be correct too! 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 + + From 8601f4ce2630db34f4c32053c42d168d4907c485 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Mar 2024 05:20:14 -0700 Subject: [PATCH 149/251] Added Chapter 2 Visualizations. --- source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c | 7 +++---- source/cprogramming/chapter2/ex_2.6_setbits.rst | 9 +++++++++ source/cprogramming/chapter2/ex_2.7_invert.rst | 7 +++++++ source/cprogramming/chapter2/ex_2.9_bitcount2s.rst | 11 ++++------- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c index de98fdb9..a2de0ae3 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c @@ -9,10 +9,9 @@ unsigned setbits(unsigned x, int p, int n, unsigned y); -int main(void) { - printf("%u", setbits((unsigned)12, 3, 2, (unsigned)57)); -} +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)); + return (x & ~(~(~0 << n) << (p + 1 - n))) | + (y & (~(~0 << n)) << (p + 1 - n)); } diff --git a/source/cprogramming/chapter2/ex_2.6_setbits.rst b/source/cprogramming/chapter2/ex_2.6_setbits.rst index 8ea3c071..2ad369a7 100644 --- a/source/cprogramming/chapter2/ex_2.6_setbits.rst +++ b/source/cprogramming/chapter2/ex_2.6_setbits.rst @@ -144,3 +144,12 @@ We write the entire expression:: = 1111 0000 Converting 1111 0000 to decimal gives us 240 and that is answer. + + +Visualization +============= + +.. raw:: html + + + 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.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 + From 64716e001d2cecb25a699e550b5b65685646d189 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Tue, 9 Apr 2024 08:12:28 -0700 Subject: [PATCH 150/251] Updated hello world extra. --- source/cprogramming/chapter1/sec_1.1_helloworld.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/source/cprogramming/chapter1/sec_1.1_helloworld.rst b/source/cprogramming/chapter1/sec_1.1_helloworld.rst index 9fa93ea3..462db5d7 100644 --- a/source/cprogramming/chapter1/sec_1.1_helloworld.rst +++ b/source/cprogramming/chapter1/sec_1.1_helloworld.rst @@ -19,3 +19,12 @@ Solution .. literalinclude:: cprogs/sec_1.1_helloworld.c :language: c + +Extras +====== + +What really happens when you run hello world program? + +Peek into the assembly code and jmps that happen with hello world as +demonstrated in this article https://thecoder08.github.io/hello-world.html + From c09ee37878e8218f79345e3921eda8be389b9f46 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 00:28:11 +0000 Subject: [PATCH 151/251] Updated C Programs. --- languages/cprogs/alloc_afree.c | 2 + languages/cprogs/anylonglinelen.c | 20 +- languages/cprogs/test_post.py | 28 --- languages/cprogs/wumpus.c | 315 ------------------------------ 4 files changed, 17 insertions(+), 348 deletions(-) delete mode 100644 languages/cprogs/test_post.py delete mode 100644 languages/cprogs/wumpus.c diff --git a/languages/cprogs/alloc_afree.c b/languages/cprogs/alloc_afree.c index 31cf373c..4ff3022a 100644 --- a/languages/cprogs/alloc_afree.c +++ b/languages/cprogs/alloc_afree.c @@ -1,3 +1,5 @@ +#include + #define ALLOCSIZE 1000 /* size of available space */ static char allocbuf[ALLOCSIZE]; /* storage for alloc */ diff --git a/languages/cprogs/anylonglinelen.c b/languages/cprogs/anylonglinelen.c index ce53eacb..2828a240 100644 --- a/languages/cprogs/anylonglinelen.c +++ b/languages/cprogs/anylonglinelen.c @@ -8,17 +8,19 @@ #define MAXLINE 1000 -int getline(char line[], int lim); +int mgetline(char line[], int lim); void copy(char to[], char from[]); +const char* current_input = "First line of text\nSecond longer line of text\nShort line\nVery very very long line that should demonstrate the behavior of the program with a lengthy input sequence\n"; + int main(void) { int len, max; char line[MAXLINE], maxline[MAXLINE]; max = 0; + maxline[0] = '\0'; // Initialize maxline - while ((len = getline(line, MAXLINE)) > 0) { - printf("%d\t%s", len, line); + while ((len = mgetline(line, MAXLINE)) > 0) { if (len > max) { max = len; copy(maxline, line); @@ -29,10 +31,18 @@ int main(void) { return 0; } -int getline(char s[], int lim) { +// Custom getchar replacement that reads from our simulated input +int custom_getchar(void) { + if (current_input && *current_input) { + return *current_input++; + } + return EOF; +} + +int mgetline(char s[], int lim) { int i, j, c; - for (i = 0, j = 0; (c = getchar()) != EOF && c != '\n'; ++i) + for (i = 0, j = 0; (c = custom_getchar()) != EOF && c != '\n'; ++i) if (i < lim - 2) { s[i] = c; ++j; 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 ' -#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; - } -} From 4562670fc557d743fa522a3517928286e8ec935d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 00:34:14 +0000 Subject: [PATCH 152/251] Simulated input and output. --- languages/cprogs/anylonglinelen.c | 7 +++---- .../chapter8/sec_8.2_read_write.rst | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/languages/cprogs/anylonglinelen.c b/languages/cprogs/anylonglinelen.c index 2828a240..1f90b5be 100644 --- a/languages/cprogs/anylonglinelen.c +++ b/languages/cprogs/anylonglinelen.c @@ -8,8 +8,8 @@ #define MAXLINE 1000 -int mgetline(char line[], int lim); -void copy(char to[], char from[]); +int mgetline(char s[], int lim); +void copy(char to[], const char from[]); const char* current_input = "First line of text\nSecond longer line of text\nShort line\nVery very very long line that should demonstrate the behavior of the program with a lengthy input sequence\n"; @@ -18,7 +18,6 @@ int main(void) { char line[MAXLINE], maxline[MAXLINE]; max = 0; - maxline[0] = '\0'; // Initialize maxline while ((len = mgetline(line, MAXLINE)) > 0) { if (len > max) { @@ -57,7 +56,7 @@ int mgetline(char s[], int lim) { return i; } -void copy(char to[], char from[]) { +void copy(char to[], const char from[]) { int i; i = 0; diff --git a/source/cprogramming/chapter8/sec_8.2_read_write.rst b/source/cprogramming/chapter8/sec_8.2_read_write.rst index 8d8bb175..a3016bce 100644 --- a/source/cprogramming/chapter8/sec_8.2_read_write.rst +++ b/source/cprogramming/chapter8/sec_8.2_read_write.rst @@ -18,3 +18,23 @@ Explanation This uses the read and write system calls to copy input to output. + # Compile the program + + gcc copy.c -o copy + + # Test 1: Echo a simple string + + echo "Hello, World!" | ./copy + + # Test 2: Multiple lines + + cat << 'EOL' | ./copy + Line 1 + Line 2 + Line 3 + EOL + + # Test 3: Binary data (create a file with some null bytes) + + dd if=/dev/zero bs=1024 count=1 2>/dev/null | ./copy > /dev/null + From 05436e71d771b5df10aa72ef5909398bf9365e1f Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 00:42:56 +0000 Subject: [PATCH 153/251] Using raw format. --- source/cprogramming/chapter8/sec_8.2_read_write.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter8/sec_8.2_read_write.rst b/source/cprogramming/chapter8/sec_8.2_read_write.rst index a3016bce..947af916 100644 --- a/source/cprogramming/chapter8/sec_8.2_read_write.rst +++ b/source/cprogramming/chapter8/sec_8.2_read_write.rst @@ -17,6 +17,7 @@ Explanation This uses the read and write system calls to copy input to output. +.. raw:: # Compile the program @@ -37,4 +38,3 @@ This uses the read and write system calls to copy input to output. # Test 3: Binary data (create a file with some null bytes) dd if=/dev/zero bs=1024 count=1 2>/dev/null | ./copy > /dev/null - From 485de7c30b80de9ab390a7aea724b033d916b379 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 01:52:43 +0000 Subject: [PATCH 154/251] Clean up LearnToSolveIt.com --- Makefile | 7 - languages/cprogs/CMakeLists.txt | 7 - languages/cprogs/Fibonacci.c | 30 --- languages/cprogs/Nofbtn.c | 24 --- languages/cprogs/alloc_afree.c | 40 ---- languages/cprogs/anylonglinelen.c | 66 ------- languages/cprogs/atoiv2.c | 33 ---- languages/cprogs/binsearch.c | 36 ---- languages/cprogs/bitcount.c | 22 --- languages/cprogs/counts.c | 41 ----- languages/cprogs/day_datev3.c | 55 ------ languages/cprogs/dcl.c | 159 ---------------- languages/cprogs/endian.c | 11 -- languages/cprogs/eratosthenes.c | 31 ---- languages/cprogs/fork1.c | 8 - languages/cprogs/fsize.c | 133 -------------- languages/cprogs/getbits.c | 17 -- languages/cprogs/getline_woandr.c | 58 ------ languages/cprogs/getpass1.c | 68 ------- languages/cprogs/glat17.c | 40 ---- languages/cprogs/htoi.c | 70 ------- languages/cprogs/leap.c | 15 -- languages/cprogs/likefind.c | 66 ------- languages/cprogs/likegrep.c | 42 ----- languages/cprogs/long_extnal.c | 50 ----- languages/cprogs/makedir.c | 7 - languages/cprogs/mygetchar.c | 20 -- languages/cprogs/numlinesort.c | 166 ----------------- languages/cprogs/pgechov1.c | 14 -- languages/cprogs/pgechov2.c | 10 - languages/cprogs/pgechov3.c | 9 - languages/cprogs/prepro1.c | 14 -- languages/cprogs/prepro2.c | 14 -- languages/cprogs/printd.c | 30 --- languages/cprogs/quicksort.c | 64 ------- languages/cprogs/rot13.c | 38 ---- languages/cprogs/sample_template.c | 5 - languages/cprogs/shellsort.c | 39 ---- languages/cprogs/sizeof_various.c | 12 -- languages/cprogs/sort.c | 125 ------------- languages/cprogs/sortv2.c | 131 -------------- languages/cprogs/squeezesc.c | 48 ----- .../cprogs/strindex_rightmost_pointers.c | 32 ---- languages/cprogs/system-programming/prog1.c | 15 -- languages/cprogs/system-programming/prog2.c | 13 -- .../system-programming-exercises.rst | 4 - languages/cprogs/unescape.c | 60 ------ languages/cprogs/val_limits.c | 43 ----- languages/letusc/.devcontainer.json | 125 ------------- languages/python/8queens.py | 19 -- languages/python/Queue.py | 34 ---- languages/python/README | 29 --- .../python/algorithm_binary_representation.py | 117 ------------ languages/python/algorithm_binary_search.py | 19 -- languages/python/algorithm_cellauto.py | 73 -------- ...lgorithm_checking_string_text_or_binary.py | 23 --- languages/python/algorithm_eratosthenes.py | 15 -- languages/python/algorithm_fact2.py | 3 - languages/python/algorithm_fibo.py | 14 -- languages/python/algorithm_graph.py | 28 --- languages/python/algorithm_hanoi.py | 15 -- languages/python/algorithm_insertion.py | 16 -- languages/python/algorithm_int_to_roman.py | 171 ------------------ languages/python/algorithm_locate.py | 7 - languages/python/algorithm_maxsort.py | 12 -- languages/python/algorithm_mergesort.py | 40 ---- languages/python/algorithm_npuzzle.py | 138 -------------- .../python/algorithm_pyex2_multiprocessing.py | 9 - .../python/algorithm_pyex_multiprocessing.py | 29 --- languages/python/algorithm_quicksort.py | 59 ------ languages/python/algorithm_scrmable.py | 65 ------- languages/python/algorithm_spelling.py | 30 --- languages/python/algorithm_splitter.py | 20 -- languages/python/algorithm_syllablecount.py | 27 --- languages/python/algorithm_toss_coins.py | 20 -- languages/python/algorithm_traversal.py | 47 ----- languages/python/algorithm_tree2.py | 41 ----- .../python/asyncio_examples/aiohttp_client.py | 44 ----- .../asyncio_twisted_similarity.py | 41 ----- .../python/asyncio_examples/creating_task.py | 12 -- languages/python/asyncio_examples/env.sh | 2 - .../asyncio_examples/get_onepage_async.py | 100 ---------- .../python/asyncio_examples/hello_clock.py | 26 --- .../python/asyncio_examples/http_client.py | 22 --- languages/python/asyncio_examples/producer.py | 35 ---- .../producer_consumer_task_done.py | 45 ----- .../python/asyncio_examples/run_subprocess.py | 29 --- .../asyncio_examples/simple_coroutine.py | 10 - .../python/asyncio_examples/simple_server.py | 53 ------ .../python/asyncio_examples/stopping_loop.py | 19 -- .../subprocess_communicate.py | 32 ---- .../python/asyncio_examples/sync_client.py | 57 ------ .../asyncio_examples/tcp_echo_client.py | 20 -- .../asyncio_examples/tcp_echo_server.py | 31 ---- .../asyncio_examples/threads_example.py | 14 -- languages/python/bs.png | Bin 7886 -> 0 bytes .../coding_made_simple/max_rect_area.py | 52 ------ languages/python/design_args_kwargs.py | 41 ----- languages/python/design_ast_example1.py | 18 -- languages/python/design_atexit_1.py | 15 -- .../python/design_caseinsensitivedict.py | 48 ----- languages/python/design_closure1.py | 17 -- languages/python/design_closure_example1.py | 8 - languages/python/design_context_2.py | 8 - languages/python/design_contextmanager.py | 25 --- languages/python/design_contextmanager_ex.py | 13 -- languages/python/design_decorator3.py | 15 -- languages/python/design_ex_iterable27.py | 21 --- languages/python/design_func_args.py | 25 --- languages/python/design_generator.py | 12 -- .../python/design_getattribute_example1.py | 22 --- .../python/design_getattribute_example2.py | 17 -- languages/python/design_hextobin.py | 4 - languages/python/design_inheritance.py | 13 -- languages/python/design_iterator_ex2.py | 12 -- languages/python/design_object_size.py | 12 -- languages/python/design_python3_meta_ex1.py | 18 -- .../python/design_python_objects_type.py | 38 ---- languages/python/design_restricter_class.py | 20 -- languages/python/design_simple_closure.py | 13 -- languages/python/design_slice_ellipses.py | 5 - languages/python/design_sorted_loop.py | 8 - languages/python/design_stackinspection.py | 6 - languages/python/design_struct_example.py | 29 --- languages/python/design_total_ordering.py | 33 ---- languages/python/design_traceit.py | 15 -- languages/python/fbcup1.py | 34 ---- .../python/files_count_lines_large_file.py | 19 -- .../python/files_processing_every_word.py | 18 -- .../files_random_access_input_output.py | 16 -- languages/python/files_read_specific_line.py | 15 -- languages/python/files_reading_zipfile.py | 17 -- languages/python/font.ttf | Bin 53404 -> 0 bytes languages/python/index.txt | 9 - languages/python/input.txt | 4 - languages/python/input.txt~ | 1 - languages/python/min_cost_path.py | 42 ----- languages/python/networking_allifaces.py | 45 ----- languages/python/networking_allipaddress.py | 44 ----- .../python/networking_bug_gethostbyname.py | 32 ---- languages/python/networking_email1.py | 24 --- languages/python/networking_email2.py | 17 -- languages/python/networking_email3.py | 50 ----- languages/python/networking_email4.py | 56 ------ languages/python/networking_fetchrfc.py | 19 -- languages/python/networking_socket_client.py | 20 -- .../python/networking_socket_example1.py | 16 -- .../python/networking_socket_example2.py | 17 -- .../python/networking_socket_example3.py | 31 ---- .../python/networking_socket_example4.py | 22 --- languages/python/networking_twisted1.py | 11 -- languages/python/networking_twisted2.py | 18 -- languages/python/networking_twisted3.py | 24 --- languages/python/networking_twisted4.py | 9 - languages/python/networking_twisted5.py | 21 --- .../python/networking_twisted_parallel1.py | 21 --- .../python/networking_twisted_parallel2.py | 22 --- languages/python/networking_udp1.py | 20 -- languages/python/networking_udp2.py | 25 --- languages/python/networking_udp_time.py | 26 --- ...software_engineering_copy_files_unicode.py | 20 -- .../software_engineering_createtempfiles.py | 30 --- .../software_engineering_datetime_counter.py | 10 - .../software_engineering_doctest_example.py | 60 ------ ...e_engineering_encoding_unicode_xml_html.py | 53 ------ ...software_engineering_exceptions_testing.py | 12 -- .../python/software_engineering_fcntl_1.py | 21 --- .../python/software_engineering_fctrl2.py | 16 -- .../software_engineering_fortune_card.py | 21 --- .../software_engineering_htmlformatter.py | 99 ---------- .../python/software_engineering_htmlwriter.py | 97 ---------- .../software_engineering_ideone_post.py | 4 - .../python/software_engineering_logging1.py | 4 - .../python/software_engineering_logging2.py | 21 --- .../python/software_engineering_logging3.py | 20 -- .../python/software_engineering_logging4.py | 10 - .../python/software_engineering_logging5.py | 18 -- .../software_engineering_multiprocessing_1.py | 13 -- .../python/software_engineering_os_exec1.py | 3 - .../software_engineering_provide_warnings.py | 16 -- .../python/software_engineering_ptags.py | 53 ------ .../software_engineering_run_under_strace.py | 2 - .../software_engineering_runningtime.py | 15 -- ...are_engineering_runningtime_intaddition.py | 38 ---- ...ware_engineering_runningtime_intvsfloat.py | 28 --- .../software_engineering_simple_subprocess.py | 6 - .../software_engineering_simple_threading1.py | 15 -- .../python/software_engineering_sqlite3.py | 132 -------------- .../python/software_engineering_stringio.py | 6 - .../software_engineering_subprocess1.py | 6 - .../software_engineering_subprocess2.py | 13 -- .../software_engineering_subprocess3.py | 6 - .../software_engineering_subprocess4.py | 5 - .../software_engineering_subprocess5.py | 14 -- .../software_engineering_test_codec01.py | 20 -- .../software_engineering_test_codec02.py | 7 - .../software_engineering_test_codec03.py | 10 - .../software_engineering_test_dedent.py | 12 -- .../python/software_engineering_threading2.py | 16 -- .../software_engineering_time_converter.py | 3 - .../software_engineering_tkintertimer.py | 25 --- .../software_engineering_twitter_phidget.py | 164 ----------------- .../software_engineering_xmlrpcclient.py | 21 --- .../software_engineering_xmlrpcserver.py | 41 ----- .../python/text_manipulation_argparse1.py | 15 -- languages/python/trie.py | 59 ------ languages/python/web_cgi_ex.py | 30 --- languages/python/web_cookielib_example.py | 16 -- languages/python/web_crawl.py | 123 ------------- languages/python/web_crawl2.py | 23 --- languages/python/web_http_auth_header_code.py | 19 -- languages/python/web_httplib_example_1.py | 42 ----- languages/python/web_httplib_example_2.py | 9 - languages/python/web_httplib_example_3.py | 7 - languages/python/web_httplib_head.py | 6 - languages/python/web_scan_web.py | 13 -- languages/python/web_server.py | 17 -- languages/python/web_simple_http_processor.py | 56 ------ languages/python/web_urllib1.py | 2 - languages/python/web_urllib2_1.py | 4 - languages/python/web_urllib2_add_data.py | 14 -- languages/python/web_urllib2_auth_ex1.py | 6 - languages/python/web_urllib2_basic1.py | 11 -- languages/python/web_urllib2_basic2.py | 79 -------- languages/python/web_urllib2_basic3.py | 14 -- languages/python/web_urllib2_basic_digest1.py | 16 -- languages/python/web_urllib2_binary_upload.py | 93 ---------- languages/python/web_urllib2_debug_headers.py | 28 --- languages/python/web_urllib2_digest.py | 10 - languages/python/web_urllib2_digest2.py | 12 -- languages/python/web_urllib2_headers_ex1.py | 16 -- languages/python/web_urllib2_proxy_auth.py | 11 -- languages/python/web_urllib2_test.py | 25 --- .../chapter8/sec_8.2_read_write.rst | 4 +- utils/bin/__init__.py | 1 - utils/bin/add_program.py | 136 -------------- 236 files changed, 2 insertions(+), 7348 deletions(-) delete mode 100644 languages/cprogs/CMakeLists.txt delete mode 100644 languages/cprogs/Fibonacci.c delete mode 100644 languages/cprogs/Nofbtn.c delete mode 100644 languages/cprogs/alloc_afree.c delete mode 100644 languages/cprogs/anylonglinelen.c delete mode 100644 languages/cprogs/atoiv2.c delete mode 100644 languages/cprogs/binsearch.c delete mode 100644 languages/cprogs/bitcount.c delete mode 100644 languages/cprogs/counts.c delete mode 100644 languages/cprogs/day_datev3.c delete mode 100644 languages/cprogs/dcl.c delete mode 100644 languages/cprogs/endian.c delete mode 100644 languages/cprogs/eratosthenes.c delete mode 100644 languages/cprogs/fork1.c delete mode 100644 languages/cprogs/fsize.c delete mode 100644 languages/cprogs/getbits.c delete mode 100644 languages/cprogs/getline_woandr.c delete mode 100644 languages/cprogs/getpass1.c delete mode 100644 languages/cprogs/glat17.c delete mode 100644 languages/cprogs/htoi.c delete mode 100644 languages/cprogs/leap.c delete mode 100644 languages/cprogs/likefind.c delete mode 100644 languages/cprogs/likegrep.c delete mode 100644 languages/cprogs/long_extnal.c delete mode 100644 languages/cprogs/makedir.c delete mode 100644 languages/cprogs/mygetchar.c delete mode 100644 languages/cprogs/numlinesort.c delete mode 100644 languages/cprogs/pgechov1.c delete mode 100644 languages/cprogs/pgechov2.c delete mode 100644 languages/cprogs/pgechov3.c delete mode 100644 languages/cprogs/prepro1.c delete mode 100644 languages/cprogs/prepro2.c delete mode 100644 languages/cprogs/printd.c delete mode 100644 languages/cprogs/quicksort.c delete mode 100644 languages/cprogs/rot13.c delete mode 100644 languages/cprogs/sample_template.c delete mode 100644 languages/cprogs/shellsort.c delete mode 100644 languages/cprogs/sizeof_various.c delete mode 100644 languages/cprogs/sort.c delete mode 100644 languages/cprogs/sortv2.c delete mode 100644 languages/cprogs/squeezesc.c delete mode 100644 languages/cprogs/strindex_rightmost_pointers.c delete mode 100644 languages/cprogs/system-programming/prog1.c delete mode 100644 languages/cprogs/system-programming/prog2.c delete mode 100644 languages/cprogs/system-programming/system-programming-exercises.rst delete mode 100644 languages/cprogs/unescape.c delete mode 100644 languages/cprogs/val_limits.c delete mode 100644 languages/letusc/.devcontainer.json delete mode 100644 languages/python/8queens.py delete mode 100644 languages/python/Queue.py delete mode 100644 languages/python/README delete mode 100644 languages/python/algorithm_binary_representation.py delete mode 100644 languages/python/algorithm_binary_search.py delete mode 100644 languages/python/algorithm_cellauto.py delete mode 100644 languages/python/algorithm_checking_string_text_or_binary.py delete mode 100644 languages/python/algorithm_eratosthenes.py delete mode 100644 languages/python/algorithm_fact2.py delete mode 100644 languages/python/algorithm_fibo.py delete mode 100644 languages/python/algorithm_graph.py delete mode 100644 languages/python/algorithm_hanoi.py delete mode 100644 languages/python/algorithm_insertion.py delete mode 100644 languages/python/algorithm_int_to_roman.py delete mode 100644 languages/python/algorithm_locate.py delete mode 100644 languages/python/algorithm_maxsort.py delete mode 100644 languages/python/algorithm_mergesort.py delete mode 100644 languages/python/algorithm_npuzzle.py delete mode 100644 languages/python/algorithm_pyex2_multiprocessing.py delete mode 100644 languages/python/algorithm_pyex_multiprocessing.py delete mode 100644 languages/python/algorithm_quicksort.py delete mode 100644 languages/python/algorithm_scrmable.py delete mode 100644 languages/python/algorithm_spelling.py delete mode 100644 languages/python/algorithm_splitter.py delete mode 100644 languages/python/algorithm_syllablecount.py delete mode 100644 languages/python/algorithm_toss_coins.py delete mode 100644 languages/python/algorithm_traversal.py delete mode 100644 languages/python/algorithm_tree2.py delete mode 100644 languages/python/asyncio_examples/aiohttp_client.py delete mode 100644 languages/python/asyncio_examples/asyncio_twisted_similarity.py delete mode 100644 languages/python/asyncio_examples/creating_task.py delete mode 100644 languages/python/asyncio_examples/env.sh delete mode 100644 languages/python/asyncio_examples/get_onepage_async.py delete mode 100644 languages/python/asyncio_examples/hello_clock.py delete mode 100644 languages/python/asyncio_examples/http_client.py delete mode 100644 languages/python/asyncio_examples/producer.py delete mode 100644 languages/python/asyncio_examples/producer_consumer_task_done.py delete mode 100644 languages/python/asyncio_examples/run_subprocess.py delete mode 100644 languages/python/asyncio_examples/simple_coroutine.py delete mode 100644 languages/python/asyncio_examples/simple_server.py delete mode 100644 languages/python/asyncio_examples/stopping_loop.py delete mode 100644 languages/python/asyncio_examples/subprocess_communicate.py delete mode 100644 languages/python/asyncio_examples/sync_client.py delete mode 100644 languages/python/asyncio_examples/tcp_echo_client.py delete mode 100644 languages/python/asyncio_examples/tcp_echo_server.py delete mode 100644 languages/python/asyncio_examples/threads_example.py delete mode 100644 languages/python/bs.png delete mode 100644 languages/python/coding_made_simple/max_rect_area.py delete mode 100644 languages/python/design_args_kwargs.py delete mode 100644 languages/python/design_ast_example1.py delete mode 100644 languages/python/design_atexit_1.py delete mode 100644 languages/python/design_caseinsensitivedict.py delete mode 100644 languages/python/design_closure1.py delete mode 100644 languages/python/design_closure_example1.py delete mode 100644 languages/python/design_context_2.py delete mode 100644 languages/python/design_contextmanager.py delete mode 100644 languages/python/design_contextmanager_ex.py delete mode 100644 languages/python/design_decorator3.py delete mode 100644 languages/python/design_ex_iterable27.py delete mode 100644 languages/python/design_func_args.py delete mode 100644 languages/python/design_generator.py delete mode 100644 languages/python/design_getattribute_example1.py delete mode 100644 languages/python/design_getattribute_example2.py delete mode 100644 languages/python/design_hextobin.py delete mode 100644 languages/python/design_inheritance.py delete mode 100644 languages/python/design_iterator_ex2.py delete mode 100644 languages/python/design_object_size.py delete mode 100644 languages/python/design_python3_meta_ex1.py delete mode 100644 languages/python/design_python_objects_type.py delete mode 100644 languages/python/design_restricter_class.py delete mode 100644 languages/python/design_simple_closure.py delete mode 100644 languages/python/design_slice_ellipses.py delete mode 100644 languages/python/design_sorted_loop.py delete mode 100644 languages/python/design_stackinspection.py delete mode 100644 languages/python/design_struct_example.py delete mode 100644 languages/python/design_total_ordering.py delete mode 100644 languages/python/design_traceit.py delete mode 100644 languages/python/fbcup1.py delete mode 100644 languages/python/files_count_lines_large_file.py delete mode 100644 languages/python/files_processing_every_word.py delete mode 100644 languages/python/files_random_access_input_output.py delete mode 100644 languages/python/files_read_specific_line.py delete mode 100644 languages/python/files_reading_zipfile.py delete mode 100644 languages/python/font.ttf delete mode 100644 languages/python/index.txt delete mode 100644 languages/python/input.txt delete mode 100644 languages/python/input.txt~ delete mode 100644 languages/python/min_cost_path.py delete mode 100644 languages/python/networking_allifaces.py delete mode 100644 languages/python/networking_allipaddress.py delete mode 100644 languages/python/networking_bug_gethostbyname.py delete mode 100755 languages/python/networking_email1.py delete mode 100644 languages/python/networking_email2.py delete mode 100644 languages/python/networking_email3.py delete mode 100644 languages/python/networking_email4.py delete mode 100644 languages/python/networking_fetchrfc.py delete mode 100644 languages/python/networking_socket_client.py delete mode 100644 languages/python/networking_socket_example1.py delete mode 100644 languages/python/networking_socket_example2.py delete mode 100644 languages/python/networking_socket_example3.py delete mode 100644 languages/python/networking_socket_example4.py delete mode 100644 languages/python/networking_twisted1.py delete mode 100644 languages/python/networking_twisted2.py delete mode 100644 languages/python/networking_twisted3.py delete mode 100644 languages/python/networking_twisted4.py delete mode 100644 languages/python/networking_twisted5.py delete mode 100644 languages/python/networking_twisted_parallel1.py delete mode 100644 languages/python/networking_twisted_parallel2.py delete mode 100644 languages/python/networking_udp1.py delete mode 100644 languages/python/networking_udp2.py delete mode 100644 languages/python/networking_udp_time.py delete mode 100644 languages/python/software_engineering_copy_files_unicode.py delete mode 100755 languages/python/software_engineering_createtempfiles.py delete mode 100644 languages/python/software_engineering_datetime_counter.py delete mode 100644 languages/python/software_engineering_doctest_example.py delete mode 100644 languages/python/software_engineering_encoding_unicode_xml_html.py delete mode 100644 languages/python/software_engineering_exceptions_testing.py delete mode 100644 languages/python/software_engineering_fcntl_1.py delete mode 100644 languages/python/software_engineering_fctrl2.py delete mode 100644 languages/python/software_engineering_fortune_card.py delete mode 100644 languages/python/software_engineering_htmlformatter.py delete mode 100644 languages/python/software_engineering_htmlwriter.py delete mode 100644 languages/python/software_engineering_ideone_post.py delete mode 100644 languages/python/software_engineering_logging1.py delete mode 100644 languages/python/software_engineering_logging2.py delete mode 100644 languages/python/software_engineering_logging3.py delete mode 100644 languages/python/software_engineering_logging4.py delete mode 100644 languages/python/software_engineering_logging5.py delete mode 100644 languages/python/software_engineering_multiprocessing_1.py delete mode 100644 languages/python/software_engineering_os_exec1.py delete mode 100644 languages/python/software_engineering_provide_warnings.py delete mode 100644 languages/python/software_engineering_ptags.py delete mode 100644 languages/python/software_engineering_run_under_strace.py delete mode 100644 languages/python/software_engineering_runningtime.py delete mode 100644 languages/python/software_engineering_runningtime_intaddition.py delete mode 100644 languages/python/software_engineering_runningtime_intvsfloat.py delete mode 100644 languages/python/software_engineering_simple_subprocess.py delete mode 100644 languages/python/software_engineering_simple_threading1.py delete mode 100755 languages/python/software_engineering_sqlite3.py delete mode 100644 languages/python/software_engineering_stringio.py delete mode 100644 languages/python/software_engineering_subprocess1.py delete mode 100644 languages/python/software_engineering_subprocess2.py delete mode 100644 languages/python/software_engineering_subprocess3.py delete mode 100644 languages/python/software_engineering_subprocess4.py delete mode 100644 languages/python/software_engineering_subprocess5.py delete mode 100644 languages/python/software_engineering_test_codec01.py delete mode 100644 languages/python/software_engineering_test_codec02.py delete mode 100644 languages/python/software_engineering_test_codec03.py delete mode 100644 languages/python/software_engineering_test_dedent.py delete mode 100644 languages/python/software_engineering_threading2.py delete mode 100644 languages/python/software_engineering_time_converter.py delete mode 100644 languages/python/software_engineering_tkintertimer.py delete mode 100644 languages/python/software_engineering_twitter_phidget.py delete mode 100644 languages/python/software_engineering_xmlrpcclient.py delete mode 100644 languages/python/software_engineering_xmlrpcserver.py delete mode 100755 languages/python/text_manipulation_argparse1.py delete mode 100644 languages/python/trie.py delete mode 100755 languages/python/web_cgi_ex.py delete mode 100644 languages/python/web_cookielib_example.py delete mode 100644 languages/python/web_crawl.py delete mode 100644 languages/python/web_crawl2.py delete mode 100644 languages/python/web_http_auth_header_code.py delete mode 100644 languages/python/web_httplib_example_1.py delete mode 100644 languages/python/web_httplib_example_2.py delete mode 100644 languages/python/web_httplib_example_3.py delete mode 100644 languages/python/web_httplib_head.py delete mode 100644 languages/python/web_scan_web.py delete mode 100644 languages/python/web_server.py delete mode 100644 languages/python/web_simple_http_processor.py delete mode 100644 languages/python/web_urllib1.py delete mode 100644 languages/python/web_urllib2_1.py delete mode 100644 languages/python/web_urllib2_add_data.py delete mode 100644 languages/python/web_urllib2_auth_ex1.py delete mode 100644 languages/python/web_urllib2_basic1.py delete mode 100644 languages/python/web_urllib2_basic2.py delete mode 100644 languages/python/web_urllib2_basic3.py delete mode 100644 languages/python/web_urllib2_basic_digest1.py delete mode 100644 languages/python/web_urllib2_binary_upload.py delete mode 100644 languages/python/web_urllib2_debug_headers.py delete mode 100644 languages/python/web_urllib2_digest.py delete mode 100644 languages/python/web_urllib2_digest2.py delete mode 100644 languages/python/web_urllib2_headers_ex1.py delete mode 100644 languages/python/web_urllib2_proxy_auth.py delete mode 100644 languages/python/web_urllib2_test.py delete mode 100644 utils/bin/__init__.py delete mode 100755 utils/bin/add_program.py 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/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/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 4ff3022a..00000000 --- a/languages/cprogs/alloc_afree.c +++ /dev/null @@ -1,40 +0,0 @@ -#include - -#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 1f90b5be..00000000 --- a/languages/cprogs/anylonglinelen.c +++ /dev/null @@ -1,66 +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 mgetline(char s[], int lim); -void copy(char to[], const char from[]); - -const char* current_input = "First line of text\nSecond longer line of text\nShort line\nVery very very long line that should demonstrate the behavior of the program with a lengthy input sequence\n"; - -int main(void) { - int len, max; - char line[MAXLINE], maxline[MAXLINE]; - - max = 0; - - while ((len = mgetline(line, MAXLINE)) > 0) { - if (len > max) { - max = len; - copy(maxline, line); - } - } - printf("%s", maxline); - - return 0; -} - -// Custom getchar replacement that reads from our simulated input -int custom_getchar(void) { - if (current_input && *current_input) { - return *current_input++; - } - return EOF; -} - -int mgetline(char s[], int lim) { - int i, j, c; - - for (i = 0, j = 0; (c = custom_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[], const 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/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/unescape.c b/languages/cprogs/unescape.c deleted file mode 100644 index 900c41c5..00000000 --- a/languages/cprogs/unescape.c +++ /dev/null @@ -1,60 +0,0 @@ -/* function unescape */ -#include -#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/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 b5645343cb6645009edae5c120f0733fb65d15c7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7886 zcmZu$30P8T)TW%KrlxGSGPSa@a?B~SR76@_S~WE_w`fr@%@#2!QExR%nJME;n zWol-nXkLh|DCe~dtwI+c{-1q71BYrW`4{kA;T#bowmd~q|47iCk z2059p?iWFv;hU`22Zo%mupaYFavM>CU}tQhOgz%0wbf$d`K;GIvCtlLMr5t%&}xbk z0Fw5IK3V9$8Q)oPKD}T48Q_?L#pUWm2Uz@MdYJTaS^}P?mVNkvhII@PdjQCd+l(g~ zG(mJ48%@>Lv$h2fi-{5$`^c_Z(NZh5tWW_2Egi@`)rh)Zqa`1^A~0Y)MV%H3?wAb&XCFW)&IFY;QxKbEq@`{2K-BGsSOwU28I1 zBoRvGNANMy2NEZCEY&QK@n-WnSls~@fm1hhX3t*Mnyh{*sp&Ti$|7;%n-rnLlgk;QFGHH((k8Q>Et1sqr!sOOzCI}(d;e{@ zxDMHjcOciMC9rR6&(CcBZuiWAP5yW??h8=l>Z0Bw-~}7TgP7RHP#o5MFREvCl=r;2 zsU!&vjKZg%^v)~jRNa!iv~?hh_`Q~A%e(Er%(Ef?%Iy9po}e(%DZD8Ny2-PpZ?arlHUE_oh*LqWf2I!qnN zL7$M*V7UdbCaHx$$Q77iBP9rzp$nXwIFtE_e;}vU4pL9WNY5AzO#W;pS%%)ckd8%W z(mm z6?uYLp|xv*vsh3dqOa(dtTj))e83^|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)^^ncU_XHyiAGIZ?66wcBqCA>9a!=3a1cvQ@AS|RPKE=8&_|if4 SJn%a;W`~Qr^P{Z?FZ>V1ryU&t 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("" % 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 9c691234af0ef89190a772a082d564fc18bf9d15..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 53404 zcmbrm2Vh&(**AXAUFT}c+8(m@ur1rNBugH$Ezfw5cqC5j#4~XcJ9~#f5;Dmk34}n{ zqfj=KJqwh#rIfae($c=H7D{Pf=%nSPVEKE_mEsQWP9(<___Fsp6-OA}5D@+3?v=qhOLQ%IrFf}o=edadh^%V7j zKvAm0QEt#8 z$G=H#v#|ZsUr-_kzg|YoRsZ_xr6|CpT_dwQjA?x^30wDeIBS5MBYwFaBAnt#EWBwTW6qt)tdbJ~+1xwl`B#u(b(}&A@pp z1q_Biay)U}C^Zd7$Kk3`^6gsd;Fg)09oE|Q>!#PO+(FgC$w6uhe0hf20o%3Idiben zc&(&%ESy}qWqNcYwGe)JC0sO3e&he@7yhpJ)jJH;N%=1rq{uwWL!UdBv zP3zWf-eh%Ko3>0(TglE2k$y8&lSrq{KpQLNhF6m~0z!?{nH|9N7@~Yz8?6s9u13e` zl*utQ(oi^i&D=-yt?XJZ2QKwfrSSC_wFm7$FVea6HhLDlk9z5Q83XeSeFd9CJC=+s z8KY>5jpZ4Q27_L&(`mIDO-6=Vtx_qK3WZ!QlS!o#3Cl7JO(O(ieEdl?cc5{q;s5#n zBRtnc6+9wfcz>AV;CCLz7~bJIt_0owjNc8ijH!W`6$wI2LSvRg6wh%C&9RumJVrDE zAw^Wv*5ZhXs)-gy)wAS3Dvr*=&TNz_@uQZhr+`L6%hc#Yv4xAvG9ph=!rTjGgTV}2 zhRc>=yOJ564bs)KFY&v-y8KFRIo$n+FuMO>@1Ueq7F8S5q3rBfPKGfH_}(I&r*6SpX!fU zP(eY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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('') - - 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 + '' % 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/source/cprogramming/chapter8/sec_8.2_read_write.rst b/source/cprogramming/chapter8/sec_8.2_read_write.rst index 947af916..343429cd 100644 --- a/source/cprogramming/chapter8/sec_8.2_read_write.rst +++ b/source/cprogramming/chapter8/sec_8.2_read_write.rst @@ -17,7 +17,7 @@ Explanation This uses the read and write system calls to copy input to output. -.. raw:: +:: # Compile the program @@ -37,4 +37,4 @@ This uses the read and write system calls to copy input to output. # Test 3: Binary data (create a file with some null bytes) - dd if=/dev/zero bs=1024 count=1 2>/dev/null | ./copy > /dev/null + dd if=/dev/zero bs=1024 count=1 2>/dev/null | ./copy > /dev/null \ No newline at end of file diff --git a/utils/bin/__init__.py b/utils/bin/__init__.py deleted file mode 100644 index 838a3f27..00000000 --- a/utils/bin/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'skumaran' diff --git a/utils/bin/add_program.py b/utils/bin/add_program.py deleted file mode 100755 index 70425b48..00000000 --- a/utils/bin/add_program.py +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/python - -""" -BUGS: - 1. make cprogramming and cprogs dir into a single dir name. - -""" - -import os -import sys -import time - -LANGUAGE_PATH = '../../languages/' -NOW_FORMAT = '%d-%m-%Y %H:%M' -PROGRAM_NAME_TEMPLATE = 'PROGRAMNAME' -SOURCE_PATH = '../../source/' -TEMPLATE_FORMAT = '../{0}_template.rst' -INVALID_EXIT = -1 -PROGRAM_DIR = os.path.abspath(os.path.dirname(__file__)) - -USAGE = """ -add_program.py program_name - -program_name should follow pattern generic_specific.extension -""" - -def _now(): - return time.strftime(NOW_FORMAT, time.localtime(time.time())) - -def _comment_type(ext): - return { - 'c': '//', - 'py': '#', - 'rb': '#', - 'java': '//', - 'scala': '//'}.get(ext, '#') - -def _source_folder_name(language): - return { - 'c': 'cprogramming', - 'py': 'python', - 'rb': 'ruby', - 'scala': 'scala', - 'java': 'java'}.get(language, '') - -def _program_folder_name(language): - return { - 'c': 'cprogs', - 'py': 'python', - 'rb': 'ruby', - 'scala': 'scala', - 'java': 'java'}.get(language, '') - -def get_language_dir(language): - return os.path.abspath( - os.path.join( - PROGRAM_DIR, - LANGUAGE_PATH, - _program_folder_name(language))) - -def get_source_dir(language): - return os.path.abspath( - os.path.join( - PROGRAM_DIR, - SOURCE_PATH, - _source_folder_name(language))) - -def get_template_file(language): - template_path = TEMPLATE_FORMAT.format(_source_folder_name(language)) - return os.path.abspath(os.path.join(PROGRAM_DIR, template_path)) - -def create_program(filename): - ext = filename.split('.')[1] - with open(filename, 'w') as fh: - fh.write('{0} {1} - {2}'.format( - _comment_type(ext), - os.path.basename(filename), - _now())) - -def _program_name(program): - return program.split('.')[0] - -def _rst_filename(program): - return _program_name(program) + '.rst' - -def create_source(template, filename, program): - with open(template) as template_file: - with open(filename, 'w') as source_file: - for line in template_file: - source_file.write( - line.replace(PROGRAM_NAME_TEMPLATE, program)) - -def update_index_file(filename, program): - with open(filename, 'a') as f: - f.write(' %s\n\n' % program) - -def get_index_file(language): - return os.path.abspath(os.path.join(get_source_dir(language), 'index.rst')) - -def exit_if_not_exists(path): - if not os.path.exists(path): - print("{0} does not exists".format(path)) - sys.exit(-1) - -def main(args): - try: - program, = args - except ValueError: - print(USAGE) - sys.exit(-1) - - program_name, language = program.split('.') - - path = get_language_dir(language) - exit_if_not_exists(path) - program_file = os.path.abspath(os.path.join(path, program)) - create_program(program_file) - print('Created {0}'.format(program_file)) - - path = get_source_dir(language) - exit_if_not_exists(path) - source_file = os.path.abspath(os.path.join(path, _rst_filename(program))) - create_source( - get_template_file(language), - source_file, - _program_name(program)) - - print('Created {0}'.format(source_file)) - - filename = get_index_file(language) - exit_if_not_exists(filename) - update_index_file(filename, _program_name(program)) - print('Updated {0}'.format(filename)) - -if __name__ == '__main__': - main(sys.argv[1:]) From 901c376e3c3f16fb980a887e71e83c72ddf4a40a Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:16:30 +0000 Subject: [PATCH 155/251] Trying out a new theme. --- languages/cprogs/Ex_1.8_count_blanks_etc.c | 12 +++++++++++- requirements.txt | 2 +- source/conf.py | 16 +++++++++++++--- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/languages/cprogs/Ex_1.8_count_blanks_etc.c b/languages/cprogs/Ex_1.8_count_blanks_etc.c index 5f59bd67..5d862063 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 custom_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 = custom_getchar()) != EOF) { if (c == ' ') ++blanks; if (c == '\t') diff --git a/requirements.txt b/requirements.txt index 32c9a15e..267d0db7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ sphinx +sphinx-wagtail-theme pydata-sphinx-theme sphinx_bootstrap_theme sphinx-autobuild breathe -piccolo_theme sphinx-pdj-theme diff --git a/source/conf.py b/source/conf.py index f4660497..7ab144ba 100644 --- a/source/conf.py +++ b/source/conf.py @@ -22,9 +22,11 @@ # Activate the theme. -import sphinx_pdj_theme -html_theme = 'sphinx_pdj_theme' -html_theme_path = [sphinx_pdj_theme.get_html_theme_path()] +#import sphinx_pdj_theme +# html_theme = 'sphinx_pdj_theme' +#html_theme_path = [sphinx_pdj_theme.get_html_theme_path()] +#extensions.append("sphinx_wagtail_theme") +#html_theme = 'sphinx_wagtail_theme' #html_theme = 'piccolo_theme' @@ -223,3 +225,11 @@ # 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' \ No newline at end of file From f0551d97548bccc882994dc4e7c484da13aaf0b0 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:40:39 +0000 Subject: [PATCH 156/251] Updating Learn To Solve It. --- source/conf.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index 7ab144ba..91a38385 100644 --- a/source/conf.py +++ b/source/conf.py @@ -232,4 +232,14 @@ extensions = [] extensions.append('sphinx_wagtail_theme') -html_theme = 'sphinx_wagtail_theme' \ No newline at end of file +html_theme = 'sphinx_wagtail_theme' + +# This is used by Sphinx in many places, such as page title tags. +project = "Learn To Solve It" + +# These are options specifically for the Wagtail Theme. +html_theme_options = dict( + project_name = "Learn To Solve It", + logo = "_static/learntosolveit.png", + logo_alt = "Learn To Solve It", +) \ No newline at end of file From aade3290e3bc6ac1a8ecb4555a911906535ddb39 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:46:31 +0000 Subject: [PATCH 157/251] updated project title. --- source/conf.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/source/conf.py b/source/conf.py index 91a38385..d16b519a 100644 --- a/source/conf.py +++ b/source/conf.py @@ -234,12 +234,9 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' -# This is used by Sphinx in many places, such as page title tags. -project = "Learn To Solve It" - # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name = "Learn To Solve It", - logo = "_static/learntosolveit.png", - logo_alt = "Learn To Solve It", + logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", + github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" ) \ No newline at end of file From b0acde63c6b61d35aa65d4b4dc2c988907f23385 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:49:03 +0000 Subject: [PATCH 158/251] updated source configuration. --- source/conf.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index d16b519a..edbc48f7 100644 --- a/source/conf.py +++ b/source/conf.py @@ -234,9 +234,10 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' +project = "Learn to Solve It" # These are options specifically for the Wagtail Theme. html_theme_options = dict( - project_name = "Learn To Solve It", logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", + logo_alt = "Learn To Solve It", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" ) \ No newline at end of file From a3e814e824a50abbfe0b69307a50c6b28fadb891 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:51:54 +0000 Subject: [PATCH 159/251] Setting the Correct Options. --- source/conf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/source/conf.py b/source/conf.py index edbc48f7..5de424a7 100644 --- a/source/conf.py +++ b/source/conf.py @@ -237,6 +237,7 @@ project = "Learn to Solve It" # These are options specifically for the Wagtail Theme. html_theme_options = dict( + project_name ="", logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", logo_alt = "Learn To Solve It", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" From ad8f19d31ccabc28827ac9a79fd838a42fb616a9 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 02:59:36 +0000 Subject: [PATCH 160/251] Fixing the correct link name. --- source/conf.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index 5de424a7..d84a668d 100644 --- a/source/conf.py +++ b/source/conf.py @@ -234,10 +234,10 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' -project = "Learn to Solve It" +project = "" # These are options specifically for the Wagtail Theme. html_theme_options = dict( - project_name ="", + project_name ="Learn To Solve It", logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", logo_alt = "Learn To Solve It", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" From 98e1ef3e77ee266b4095073090034a3c1c81b008 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:02:22 +0000 Subject: [PATCH 161/251] Fixing customization --- source/conf.py | 1 - 1 file changed, 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index d84a668d..1ba6a64c 100644 --- a/source/conf.py +++ b/source/conf.py @@ -239,6 +239,5 @@ html_theme_options = dict( project_name ="Learn To Solve It", logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", - logo_alt = "Learn To Solve It", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" ) \ No newline at end of file From 63c51eb27b5817ca888bc5bf19cb39495b585634 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:09:25 +0000 Subject: [PATCH 162/251] give a comment. --- source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index 1ba6a64c..fce3aacc 100644 --- a/source/conf.py +++ b/source/conf.py @@ -234,7 +234,7 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' -project = "" +project = "//" # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", From f90883179798e461850a9d2548b71edf29be1dc2 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:21:02 +0000 Subject: [PATCH 163/251] fix the logo. --- source/conf.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index fce3aacc..cfafacef 100644 --- a/source/conf.py +++ b/source/conf.py @@ -234,10 +234,9 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' -project = "//" +project = "" # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", - logo = "https://dl.dropbox.com/s/fgkfrmbgo7ogjgq/learntosolveit.png", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" ) \ No newline at end of file From f584b5975fe01ca1328be0b7ad383385867bff9e Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:29:36 +0000 Subject: [PATCH 164/251] updated learn to solve it. --- source/conf.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/conf.py b/source/conf.py index cfafacef..3b6a53c0 100644 --- a/source/conf.py +++ b/source/conf.py @@ -238,5 +238,7 @@ # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", + logo = "_static/learntosolveit2.png", + logo_alt = "", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" ) \ No newline at end of file From 10cab8a850122eaa2a5a268b649353e852a4fbe7 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:36:28 +0000 Subject: [PATCH 165/251] Updated C programming files. --- languages/cprogs/Ex_1.10_TbsBlnkSpaces.c | 13 ++++++++++++- languages/cprogs/Ex_1.8_count_blanks_etc.c | 4 ++-- languages/cprogs/Ex_1.9_SinBlank.c | 15 ++++++++++++++- languages/cprogs/Ex_6.4.c | 4 ++-- 4 files changed, 30 insertions(+), 6 deletions(-) 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 5d862063..4ca14c52 100644 --- a/languages/cprogs/Ex_1.8_count_blanks_etc.c +++ b/languages/cprogs/Ex_1.8_count_blanks_etc.c @@ -9,7 +9,7 @@ const char *input = "This\tis\ta\ttest\\string\bwith\ttabs\\and\\backspaces.\n\nnewline"; int input_index = 0; -int custom_getchar(void) { +int _getchar(void) { if (input[input_index] == '\0') { return EOF; } else { @@ -23,7 +23,7 @@ int main() blanks = tabs = newlines = 0; - while ((c = custom_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_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; } From f7ac5b62d96bbb8e776dcf5f32ba72bfe4b52768 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 03:39:07 +0000 Subject: [PATCH 166/251] updated config. --- source/conf.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index 3b6a53c0..4466fcfd 100644 --- a/source/conf.py +++ b/source/conf.py @@ -238,7 +238,10 @@ # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", - logo = "_static/learntosolveit2.png", + logo = "uthcode.png", logo_alt = "", - github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/" + github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/", + logo_height = 59, + logo_url = "/", + logo_width = 45, ) \ No newline at end of file From e75e1c5644443fbd9ccb584292cbeadf90d24355 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 04:03:55 +0000 Subject: [PATCH 167/251] Visualizing Program 7.1 --- languages/cprogs/Ex_7.1_lower-upper.c | 41 ++++++++++++------- .../chapter7/ex_7.1_lower-upper.rst | 5 +++ 2 files changed, 31 insertions(+), 15 deletions(-) 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/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index 89672862..3ea0025c 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -16,5 +16,10 @@ Explanation =========== +Visualize +========= +.. raw:: html + + From b0a1293abc9953bea2993537b8c89d30b9b64a95 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 04:58:09 +0000 Subject: [PATCH 168/251] Customize Visualization. --- source/cprogramming/chapter7/ex_7.1_lower-upper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index 3ea0025c..e07259c4 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -21,5 +21,5 @@ Visualize .. raw:: html - + From 5e8a339665f3769c7cf970dad8724f1a39c24250 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 05:05:21 +0000 Subject: [PATCH 169/251] Customizing Width and height --- source/cprogramming/chapter7/ex_7.1_lower-upper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index e07259c4..829a9406 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -21,5 +21,5 @@ Visualize .. raw:: html - + From 444d279506b875eb5ca0214729056d414981e20a Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 05:08:45 +0000 Subject: [PATCH 170/251] Updated Exercise 7.1 with lower to upper. --- .../chapter7/cprogs/ex_7.1_lower-upper.c | 17 +++++++++++++++-- .../chapter7/ex_7.1_lower-upper.rst | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c b/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c index cec9d0ff..847780de 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c @@ -8,14 +8,27 @@ upper case depending on the name it is involved with as found in argv[0] */ /* lower: converts upper case to lower case */ /* upper: converts lower case to upper case */ +const char *input = "This\tis\ta\ttest"; +int input_index = 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) + while ((c = _getchar()) != EOF) putchar(tolower(c)); else - while ((c = getchar()) != EOF) + while ((c = _getchar()) != EOF) putchar(toupper(c)); return 0; diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index 829a9406..1a016704 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -8,7 +8,7 @@ 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:: cprogs/ex_7.1_lower-upper.c +.. literalinclude:: cprogs/Ex_7.1_lower-upper.c :language: c :tab-width: 4 From 0cf9d8a896eb6e7f3ebe2d57bea8866557c7eb1f Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 05:11:28 +0000 Subject: [PATCH 171/251] Fixing the correct link. --- source/cprogramming/chapter7/ex_7.1_lower-upper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index 1a016704..829a9406 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -8,7 +8,7 @@ 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:: cprogs/Ex_7.1_lower-upper.c +.. literalinclude:: cprogs/ex_7.1_lower-upper.c :language: c :tab-width: 4 From 824c14ca7e794d17a4ade4c38dff9a2f88a6a780 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 05:17:30 +0000 Subject: [PATCH 172/251] Updated with correct imports. --- source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c | 1 + source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c | 1 + source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c | 1 + 3 files changed, 3 insertions(+) diff --git a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c index fb473009..52273865 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c @@ -6,6 +6,7 @@ the relative speeds of the two versions */ #include #include #include +#include #define STDIN 0 #define STDOUT 1 diff --git a/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c index d978e8c4..82a6e237 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c @@ -5,6 +5,7 @@ #include #include #include +#include #define NAME_MAX 14 diff --git a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c index a8bff8e8..5001e581 100644 --- a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c +++ b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c @@ -3,6 +3,7 @@ #include #include #include +#include #define PERMS 0666 /* RW for owner, group and others */ From db9e3dffe98d971aa4940f43e4cc748eb80ef27a Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 14:22:52 +0000 Subject: [PATCH 173/251] updated visualization of chapter 7 programs. --- .../chapter7/cprogs/ex_7.2_nongraphic.c | 14 +++++++++++++- source/cprogramming/chapter7/ex_7.2_nongraphic.rst | 6 ++++++ source/cprogramming/chapter7/ex_7.3_minprintf.rst | 6 ++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c b/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c index a315014d..b81c952f 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c @@ -10,6 +10,18 @@ #define MAXLINE 100 /* maximum number of chars in one line */ #define OCTLEN 6 /* length of an octal value */ +const char *input = "This\tis\ta\ttest. With a very long line."; +int input_index = 0; + +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + + /* inc : increment position counter for output */ int inc(int pos, int n) { if (pos + n < MAXLINE) @@ -26,7 +38,7 @@ int main(void) { pos = 0; /* position in the line */ - while ((c = getchar()) != EOF) + while ((c = _getchar()) != EOF) if (iscntrl(c) || c == ' ') { /* non-graphic or blank character */ pos = inc(pos, OCTLEN); diff --git a/source/cprogramming/chapter7/ex_7.2_nongraphic.rst b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst index 1497a8b4..b05c5af4 100644 --- a/source/cprogramming/chapter7/ex_7.2_nongraphic.rst +++ b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst @@ -22,3 +22,9 @@ If there is special character, we allocate 6 characters to it and print the char character. +Visualize +========= + +.. raw:: html + + diff --git a/source/cprogramming/chapter7/ex_7.3_minprintf.rst b/source/cprogramming/chapter7/ex_7.3_minprintf.rst index bac80a8b..56c363dd 100644 --- a/source/cprogramming/chapter7/ex_7.3_minprintf.rst +++ b/source/cprogramming/chapter7/ex_7.3_minprintf.rst @@ -15,5 +15,11 @@ Explanation =========== +Visualize +========= + +.. raw:: html + + From bc77481b42a8f5a133ba5c125a597f453dc3b1ca Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 14:33:43 +0000 Subject: [PATCH 174/251] Updated programs and visualization code. --- source/cprogramming/chapter7/cprogs/ex_7.4.c | 2 +- source/cprogramming/chapter7/cprogs/ex_7.9.c | 14 +++++++++++++- source/cprogramming/chapter7/ex_7.4.rst | 5 +++++ source/cprogramming/chapter7/ex_7.9.rst | 6 ++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.4.c b/source/cprogramming/chapter7/cprogs/ex_7.4.c index 04fc08fd..a0aa4a27 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.4.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.4.c @@ -10,7 +10,7 @@ int main(void) { minscanf("%d", &i); printf("minscanf input: %d\n", i); - char *a; + char *a = NULL; minscanf("%s", a); printf("minscanf input: %s\n", a); diff --git a/source/cprogramming/chapter7/cprogs/ex_7.9.c b/source/cprogramming/chapter7/cprogs/ex_7.9.c index 0247d85d..20f4c524 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.9.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.9.c @@ -8,10 +8,22 @@ int myisupper(int); +const char *input = "AbCdEfx"; +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()) != 'x') { + while ((c = _getchar()) != 'x') { if (c == '\n') continue; diff --git a/source/cprogramming/chapter7/ex_7.4.rst b/source/cprogramming/chapter7/ex_7.4.rst index 598071be..1e89eb32 100644 --- a/source/cprogramming/chapter7/ex_7.4.rst +++ b/source/cprogramming/chapter7/ex_7.4.rst @@ -16,6 +16,11 @@ section. Explanation =========== +Visualize +========= +.. raw:: html + + diff --git a/source/cprogramming/chapter7/ex_7.9.rst b/source/cprogramming/chapter7/ex_7.9.rst index a409f313..40b6c98d 100644 --- a/source/cprogramming/chapter7/ex_7.9.rst +++ b/source/cprogramming/chapter7/ex_7.9.rst @@ -17,5 +17,11 @@ Explanation =========== +Visualize +========= + +.. raw:: html + + From e6dc455657cdd77995e9698c4647cdde82a33b28 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 17:54:40 +0000 Subject: [PATCH 175/251] Added Explaination for Ex 7.1 --- source/cprogramming/chapter7/cprogs/ex_7.9.c | 4 ++-- source/cprogramming/chapter7/ex_7.1_lower-upper.rst | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.9.c b/source/cprogramming/chapter7/cprogs/ex_7.9.c index 20f4c524..acd7a805 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.9.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.9.c @@ -11,7 +11,7 @@ int myisupper(int); const char *input = "AbCdEfx"; int input_index = 0; -int _getchar(void) { +int custom_getchar(void) { if (input[input_index] == '\0') { return EOF; } else { @@ -23,7 +23,7 @@ int _getchar(void) { int main(void) { int c; - while ((c = _getchar()) != 'x') { + while ((c = custom_getchar()) != 'x') { if (c == '\n') continue; diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index 829a9406..57861866 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -15,6 +15,16 @@ depending on the name it is invoked with, as found in argv[0] Explanation =========== +This program converts the input string to either lower case or upper case depending on the program. +This takes help of the various header files like. + +:: + + #include // Provides character handling functions like tolower() and toupper() + #include // Provides input/output functions like putchar() + #include // Provides string handling functions like strcmp() + + Visualize ========= From 6610d62d95a282d1b7953952a69f98f7f5fb97c1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 18:56:41 +0000 Subject: [PATCH 176/251] Added explaination for Ex 7.4 --- source/cprogramming/chapter7/cprogs/ex_7.4.c | 3 +- source/cprogramming/chapter7/ex_7.4.rst | 30 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.4.c b/source/cprogramming/chapter7/cprogs/ex_7.4.c index a0aa4a27..bd45a41c 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.4.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.4.c @@ -1,5 +1,6 @@ /* minscanf: minimalistic scanf function */ #include +#include #include void minscanf(char *fmt, ...); @@ -10,7 +11,7 @@ int main(void) { minscanf("%d", &i); printf("minscanf input: %d\n", i); - char *a = NULL; + char *a = malloc(100); // Allocate 100 bytes, enough for "test char" minscanf("%s", a); printf("minscanf input: %s\n", a); diff --git a/source/cprogramming/chapter7/ex_7.4.rst b/source/cprogramming/chapter7/ex_7.4.rst index 1e89eb32..d65cdcd7 100644 --- a/source/cprogramming/chapter7/ex_7.4.rst +++ b/source/cprogramming/chapter7/ex_7.4.rst @@ -16,6 +16,36 @@ section. Explanation =========== +The Headers + +`#include ` + +This header provides functionality for functions with variable arguments (variadic functions) +It defines va_list, va_start, va_arg, and va_end macros which are used to handle variable arguments +Essential for implementing functions like scanf/printf that can take varying numbers of arguments + + +`#include ` + +This is the standard input/output header +Provides functions like printf, sscanf, putchar used in the program +Necessary for basic input/output operations + +This program implements a functionality similar to scanf, by taking a variable number of args and prints them to output. + +`#include ` for the malloc macro. + +The key components are + +:: + + va_list ap; // Declares a variable to hold the argument list + va_start(ap, fmt); // Initializes ap to point to first unnamed argument + va_arg(ap, type); // Returns next argument of specified type + va_end(ap); // Cleanup of argument list + + + Visualize ========= From 564236cb5d051c1702f01f70f869fbeed726dbc8 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 3 Nov 2024 19:46:56 +0000 Subject: [PATCH 177/251] Updated exercise 7.4 --- source/cprogramming/chapter7/cprogs/ex_7.4.c | 1 + 1 file changed, 1 insertion(+) diff --git a/source/cprogramming/chapter7/cprogs/ex_7.4.c b/source/cprogramming/chapter7/cprogs/ex_7.4.c index bd45a41c..c411de31 100644 --- a/source/cprogramming/chapter7/cprogs/ex_7.4.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.4.c @@ -14,6 +14,7 @@ int main(void) { char *a = malloc(100); // Allocate 100 bytes, enough for "test char" minscanf("%s", a); printf("minscanf input: %s\n", a); + free(a); // free the allocated memory float f; minscanf("%f", &f); From ae7c73a2031a05270d6bd5d346cfae4f13768acb Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Thu, 14 Nov 2024 02:30:55 +0000 Subject: [PATCH 178/251] updated explainations. --- source/cprogramming/chapter7/ex_7.3_minprintf.rst | 3 +++ source/cprogramming/chapter8/ex_8.8_bfree.rst | 2 ++ 2 files changed, 5 insertions(+) diff --git a/source/cprogramming/chapter7/ex_7.3_minprintf.rst b/source/cprogramming/chapter7/ex_7.3_minprintf.rst index 56c363dd..7deafb80 100644 --- a/source/cprogramming/chapter7/ex_7.3_minprintf.rst +++ b/source/cprogramming/chapter7/ex_7.3_minprintf.rst @@ -14,6 +14,9 @@ Revise minprintf to handle more of the other facilities of printf. Explanation =========== +The header `#include ` provides functionality for functions with variable arguments (variadic functions) It defines va_list, va_start, va_arg, and va_end macros which are used to handle variable arguments. +Essential for implementing functions like scanf/printf that can take varying numbers of arguments + Visualize ========= diff --git a/source/cprogramming/chapter8/ex_8.8_bfree.rst b/source/cprogramming/chapter8/ex_8.8_bfree.rst index 9228cee2..90587c41 100644 --- a/source/cprogramming/chapter8/ex_8.8_bfree.rst +++ b/source/cprogramming/chapter8/ex_8.8_bfree.rst @@ -16,3 +16,5 @@ a static or external array to the free list at any time. Explanation =========== +This program manages the memory blocks, takes care of the alignment, and for the smaller memory blocks it maintains a wtbfree method +that helps align smaller memory blocks. From bb2788480487794e52de15e8af9df6f4e59c2b01 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Thu, 14 Nov 2024 15:02:30 +0000 Subject: [PATCH 179/251] fixing exercise. --- source/cprogramming/chapter6/cprogs/ex_6.5.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/cprogramming/chapter6/cprogs/ex_6.5.c b/source/cprogramming/chapter6/cprogs/ex_6.5.c index 435c268e..74d33599 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.5.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.5.c @@ -4,6 +4,7 @@ #include #include +#include /*undef will be if it is just hashtable. Remove it. * If it is in linked list, delete from linked list. @@ -44,7 +45,7 @@ struct nlist *lookup(char *s) { struct nlist *lookup(char *); -char *strdup(char *); +// char *strdup(char *); /* install: put (name, defn) in hashtab */ struct nlist *install(char *name, char *defn) { From f0be7677083388b425d683dd0bb62796c8de9808 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 15:23:26 +0000 Subject: [PATCH 180/251] Updated Program 5.20 --- .../chapter5/cprogs/ex_5.20_dcl-funcargs.c | 100 +++++++++--------- .../chapter5/ex_5.20_dcl-funcargs.rst | 2 + 2 files changed, 51 insertions(+), 51 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c index d26c7322..6fe46c5d 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c @@ -4,8 +4,8 @@ #include #include -enum { NAME,PARENS,BRACKETS}; -enum { NO,YES }; +enum { NAME, PARENS, BRACKETS}; +enum { NO, YES }; void dcl(void); void dirdcl(void); @@ -26,7 +26,7 @@ void dcl(void) { int ns; - for(ns = 0; gettoken() = '*'; ) /* count *'s */ + for(ns = 0; gettoken() == '*'; ) /* count *'s */ ns++; dirdcl(); while(ns-- > 0) @@ -87,14 +87,9 @@ void errmsg(char *msg) #define MAXTOKEN 100 -enum { NAME,PARENS,BRACKETS}; -enum { NO, YES}; - void dcl(void); void errmsg(char *); void dclspec(void); -void typespec(void); -void typequal(void); int compare(char **,char **); int gettoken(void); extern int tokentype; /* type of last token */ @@ -117,6 +112,52 @@ void parmdcl(void) errmsg("missing ) in parameter declaration \n"); } +/* compare: compare two strings for bsearch */ + +int compare(char **s,char **t) +{ + return strcmp(*s,*t); +} + + + +/* typequal: return YES if token is a type-qualifier */ +int typequal(void) +{ + static char *typeq[] = + { + "const", + "volatile" + }; + + char *pt = token; + + if(bsearch(&pt,typeq,sizeof(typeq)/sizeof(char *),sizeof(char *),(int *) compare) == NULL) + return NO; + else + return YES; +} + + + +/* typespec: return YES if token is a type-specifier */ +int typespec(void) +{ + static char *types[] = + { + "char", + "int", + "void" + }; + + char *pt = token; + + if(bsearch(&pt,types,sizeof(types)/sizeof(char *),sizeof(char *), (int *) compare) == NULL) + return NO; + else + return YES; +} + /* dclspec: declaration specification */ @@ -156,46 +197,3 @@ void dclspec(void) } - -/* typespec: return YES if token is a type-specifier */ -int typespec(void) -{ - static char *type[] = - { - "char", - "int", - "void" - }; - - char *pt = token; - - if(bsearch(&pt,types,sizeof(types)/sizeof(char *),sizeof(char *)compare) == NULL) - return NO; - else - return YES; -} - -/* typequal: return YES if token is a type-qualifier */ -int typequal(void) -{ - static char *typeq[] = - { - "const", - "volatile" - }; - - char *pt = token; - - if(bsearch(&pt,typeq,sizeof(typeq)/sizeof(char *),sizeof(char *),compare) == NULL) - return NO; - else - return YES; -} - -/* compare: compare two strings for bsearch */ - -int compare(char **s,char **t) -{ - return strcmp(*s,*t); -} - diff --git a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst index d0919b77..f3f730a9 100644 --- a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst +++ b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst @@ -16,6 +16,8 @@ const, and so on. Explanation =========== +This program is a simple parser that reads a C declaration, breaks down the C declaration into constituent parts and provides +a human readable representation of the declaration. It handles basic declaration syntax including pointers, functions, arrays and parameter declarations. From 08f1e2526e0f1d973c13d11a3c0adee94a62b74c Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 16:22:23 +0000 Subject: [PATCH 181/251] Added Explaination for Sort fnr. --- source/cprogramming/chapter5/ex_5.15_sortfnr.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst index ab49056c..115a63e8 100644 --- a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst +++ b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst @@ -17,6 +17,20 @@ Explanation =========== +This is a sort function, which sorts the given input lines. But this function adds a flag `-f` which introduces case insensitive folding. + +.. raw:: + + ./ex_5.15_sortfnr -f + hello + Hello + Apple + Apple + Hello + hello + + + From a38509bf94e4e70d8a6786ea328d34643919a58f Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 17:01:54 +0000 Subject: [PATCH 182/251] updated readline using array. --- .../chapter5/ex_5.7_readlines_using_array.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst index 146a4800..e3a299da 100644 --- a/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst +++ b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst @@ -20,6 +20,24 @@ 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. +It's a line sorting program written in C that reads input lines, sorts them alphabetically, and prints them out. + +:: + + $ ./ex_5.7_readlines_using_array + this is a line. + Another line. + Good Line. + Abacus + Backgammon. + ^D + Abacus + Another line. + Backgammon. + Good Line. + this is a line. + + From 559ff94704dc6d6c2fd32b0e9431b668d59af162 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 17:05:55 +0000 Subject: [PATCH 183/251] updated sort fnr. --- source/cprogramming/chapter5/ex_5.15_sortfnr.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst index 115a63e8..368b5a4c 100644 --- a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst +++ b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst @@ -19,7 +19,7 @@ Explanation This is a sort function, which sorts the given input lines. But this function adds a flag `-f` which introduces case insensitive folding. -.. raw:: +:: ./ex_5.15_sortfnr -f hello From 0dee803ee05fabf89e7adede92c40fd7d7fc9a84 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 18:57:22 +0000 Subject: [PATCH 184/251] Adopted the contribution on setbits. --- .../chapter2/cprogs/ex_2.6_setbits.c | 22 ++- .../cprogramming/chapter2/ex_2.6_setbits.rst | 137 +++--------------- 2 files changed, 35 insertions(+), 124 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c index a2de0ae3..ce639ba3 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c @@ -5,13 +5,27 @@ * the other bits unchanged. **/ +#include #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)); + 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/ex_2.6_setbits.rst b/source/cprogramming/chapter2/ex_2.6_setbits.rst index 2ad369a7..e58f0cf7 100644 --- a/source/cprogramming/chapter2/ex_2.6_setbits.rst +++ b/source/cprogramming/chapter2/ex_2.6_setbits.rst @@ -14,137 +14,34 @@ 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< Date: Sat, 16 Nov 2024 20:32:31 +0000 Subject: [PATCH 185/251] Added Explaination for Sorting the program with -d and -f --- .../chapter5/ex_5.16_sort_dfnr.rst | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst index 9012c8f5..0918ede2 100644 --- a/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst +++ b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst @@ -16,6 +16,40 @@ letters, numbers and blanks. Make sure it works in conjunction with -f. Explanation =========== +This is a command-line sorting program that can sort text lines in different ways based on various options. +The `-d` flag sorts the lines of input in the directory order, that is ignoring punctuation marks. +The `-f` folds the input, that is, it does a case insensitive comparison of lower case and upper case lines. + + +:: + + ./ex_5.16_sort_dfnr -d + something-anotherthing + some-thing + another-thing + one! + once + ^D + another-thing + once + one! + some-thing + something-anotherthing + + +:: + + ./ex_5.16_sort_dfnr -df + Apple + apple + apple-pie + Carrot-Cake + + + apple + Apple + apple-pie + Carrot-Cake From 37a1ca800d79257fd9e3d342580f652fd93d3286 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 16 Nov 2024 20:43:56 +0000 Subject: [PATCH 186/251] Sort dfnr with options. --- .../chapter5/ex_5.17_sortdfnr-withoption.rst | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst index 65d6262c..67c15c01 100644 --- a/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst +++ b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst @@ -17,6 +17,53 @@ numbers.) Explanation =========== +This program is an enhanced version of the previous sort program. +The main difference is that it can sort text based on specific fields (portions) within each line, rather than just sorting entire lines. This is particularly useful for sorting structured data like tables or indexes. +Key differences from the previous version: +Added field handling with two new parameters: ++pos1: Specifies where to start looking in each line (starting position) +-pos2: Specifies where to stop looking in each line (ending position) + + +Example usage: + +# Original data (index with page numbers): +Arrays, dynamic 125 +Arrays, initialization 89 +Arrays, multidimensional 110 + +:: + + sort -df +0 -2 -n +2 + + # Using an example line: "Arrays, dynamic 125" + + +Let's separate each part: + +* -df: These are sorting options +* -d: Directory order (only considers letters, numbers, and spaces) +* -f: Fold case (treats uppercase and lowercase as the same) + + +:: + + +0 -2: This specifies the first field to sort by + + +* +0: Start from position 0 (beginning of line) +* -2: Stop before position 2 (in this case, the text portion) + +So this would look at "Arrays, dynamic" + + +:: + + -n +2: This specifies the second field to sort by + +* -n: Use numeric sorting +* +2: Start from position 2 (where the numbers are) +* So this would look at "125" From 84d6f70937fb036013cf201393b2a74594fc4109 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 03:09:05 +0000 Subject: [PATCH 187/251] Added explaination for 5.18 --- source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst index 9b49f335..9a1866cc 100644 --- a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst +++ b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst @@ -14,3 +14,6 @@ Make dcl recover from input errors. Explanation =========== +The program has an errmsg function that is called whenever an error is detected during parsing. +The dcl and dirdcl functions, which are responsible for parsing the declarator, continue parsing even if an error is encountered. + From 15a74613899f3bc3e5cb5ec520925e3052e1d2ba Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 15:05:08 +0000 Subject: [PATCH 188/251] Updated exercise 5.19 undcl. --- .../cprogramming/chapter5/ex_5.19_undcl.rst | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/source/cprogramming/chapter5/ex_5.19_undcl.rst b/source/cprogramming/chapter5/ex_5.19_undcl.rst index f2cfbf7b..45d6e29f 100644 --- a/source/cprogramming/chapter5/ex_5.19_undcl.rst +++ b/source/cprogramming/chapter5/ex_5.19_undcl.rst @@ -15,6 +15,43 @@ Modify undcl so that it does not add redundant parentheses to declarations. Explanation =========== - +The book provides this undcl implementation + +:: + /* undcl: convert word descriptions to declarations */ + main() { + int type; + char temp[MAXTOKEN]; + while (gettoken() != EOF) { + strcpy(out, token); + while ((type = gettoken()) != '\n') + } + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + sprintf(temp, "(*%s)", out); + strcpy(out, temp); + } else if (type == NAME) { + sprintf(temp, "%s %s", token, out); + strcpy(out, temp); + } else + printf("invalid input at %s\n", token); + } + +The important change in our implementation from the book program is, if the nexttoken is a PARENS or BRACKETS then we +print them out. + +:: + + + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + + if ((type = nexttoken()) == PARENS || type == BRACKETS) + sprintf(temp, "(*%s)", out); + + else + + sprintf(temp, "*%s", out); + strcpy(out, temp); + } else if (type == NAME) { From 502fcc11adc9d8ca7ee1017f317fc6249cb67b2d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 15:13:16 +0000 Subject: [PATCH 189/251] Updated Exercise 5.19 --- source/cprogramming/chapter5/ex_5.19_undcl.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/source/cprogramming/chapter5/ex_5.19_undcl.rst b/source/cprogramming/chapter5/ex_5.19_undcl.rst index 45d6e29f..ba9f9e94 100644 --- a/source/cprogramming/chapter5/ex_5.19_undcl.rst +++ b/source/cprogramming/chapter5/ex_5.19_undcl.rst @@ -18,6 +18,7 @@ Explanation The book provides this undcl implementation :: + /* undcl: convert word descriptions to declarations */ main() { int type; From a76c3ba0b673ac229113ee7030e3af46e9dcd799 Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 15:37:27 +0000 Subject: [PATCH 190/251] Update Ex_5.17_sortdfnr-withoption.c (#151) Fixed typos that caused errors --- languages/cprogs/Ex_5.17_sortdfnr-withoption.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 Date: Sun, 17 Nov 2024 15:37:49 +0000 Subject: [PATCH 191/251] Also fixed here. --- .../chapter5/cprogs/ex_5.17_sortdfnr-withoption.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c index 1da0692f..f1b60cf8 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c @@ -20,7 +20,7 @@ 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); @@ -98,6 +98,7 @@ void readargs(int argc, char *argv[]) { #include #include #include +#include #define MAXSTR 100 @@ -173,7 +174,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; @@ -250,7 +251,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; for (i = 0; i < nlines; i++) @@ -284,8 +285,7 @@ void afree(char *p) /* free storage pointed to by p */ int mgetline(char s[], int lim) { int c, i; - 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; From 21b9feca1cd47560f761d19a52cca840b893d401 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 15:40:57 +0000 Subject: [PATCH 192/251] Updated Exercise 5.1 --- source/cprogramming/chapter5/cprogs/ex_5.1_getint.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c b/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c index c50b1b68..43a5062c 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c @@ -52,19 +52,18 @@ int getint(int *pn) { return c; } -int main(void) { - int n, s, array[SIZE], getint(int *); +int main(void) +{ + int n,s,array[SIZE]; - for (n = 0; n < SIZE && getint(&array[n]) != EOF) { - /* For debug purposes */ - /* ( (res!=0) ? n++:0 ) will add only valid values to the array */ + for(n=0;n Date: Sun, 17 Nov 2024 15:41:12 +0000 Subject: [PATCH 193/251] Update Ex_5.1_getint.c (#146) 1. Removed the "debugging purposes" part on line 64 due to having no purpose excepting making program not run, cause "res" is not defined in any shape or form. 2. Removed "getint(int *) from line 62, due to it already being a function, this resulted in host of problems when trying to initialize it inside main. As a result of these changes, the program is functional --- languages/cprogs/Ex_5.1_getint.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 Date: Sun, 17 Nov 2024 15:45:47 +0000 Subject: [PATCH 194/251] updated exercise 5.2 for get float. --- .../cprogramming/chapter5/cprogs/ex_5.2_getfloat.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c b/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c index 246bdbf3..284fe109 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c @@ -11,14 +11,16 @@ void ungetch(int); int getfloat(float *); -int main(void) { +int main(void) +{ int n; float array[SIZE]; - for (n = 0; n < SIZE && getfloat(&array[n]) != EOF; n++); - for (; n >= 0; n--) - printf("%f", array[n]); - + for(n=0;n=0;n--) + printf("%f\n",array[n]); + } return 0; } From 31a522d09aca9856c91eb751610b26d23c60a003 Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 15:46:17 +0000 Subject: [PATCH 195/251] Update Ex_5.2_getfloat.c (#147) Program was stuck in the empty loop at for loop execution at line 18. As result it did not print the conversion. This was solved by nesting the for loop with the the for loop that was supposed to be followed by it. Program runs correctly now. --- languages/cprogs/Ex_5.2_getfloat.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/languages/cprogs/Ex_5.2_getfloat.c b/languages/cprogs/Ex_5.2_getfloat.c index f0fc6464..3d0a75ee 100644 --- a/languages/cprogs/Ex_5.2_getfloat.c +++ b/languages/cprogs/Ex_5.2_getfloat.c @@ -16,10 +16,10 @@ int main(void) float array[SIZE]; for(n=0;n=0;n--) - printf("%f",array[n]); - + { + for(;n>=0;n--) + printf("%f\n",array[n]); + } return 0; } From 82a3079ade777cf203eca22396ddd19ae3db9764 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 16:08:36 +0000 Subject: [PATCH 196/251] Fix strncpy --- source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c b/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c index c928672d..b939c589 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c @@ -20,7 +20,7 @@ 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'; From b4d20786ce0e24c5ac44c704bb4dea8b97e581ee Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:09:02 +0000 Subject: [PATCH 197/251] Update Ex_5.5_strncpy.c (#148) 2 minor fixes: first function call of mystrnlen had a typo and as such produced wimplicit warning, and *dest++ is not doing anything except pointing, its supposed to rather increment, so changed it to dest++. --- languages/cprogs/Ex_5.5_strncpy.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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'; From 81b912cccf147b101708ef1a2b69e0496321a9ff Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 16:28:06 +0000 Subject: [PATCH 198/251] fix readlines. --- .../cprogs/ex_5.7_readlines_using_array.c | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c b/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c index 809d5970..a3dd17c7 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c @@ -35,26 +35,36 @@ int mgetline(char *, int); char *alloc(int); /* readlines: read input lines */ -int readlines(char *lineptr[], char *linestor, int maxlines) { - int len, nlines; +int readlines(char *lineptr[],char *linestor,int maxlines) +{ + int len,nlines; char line[MAXLEN]; char *p = linestor; char *linestop = linestor + MAXSTOR; + char c; - nlines = 0; - - while ((len = mgetline(line, MAXLEN)) > 0) - if (nlines >= maxlines || p + len > linestop) + nlines=0; + loop: + while((len=mgetline(line,MAXLEN)) > 0) + if(nlines >= maxlines || p+len > linestop) return -1; - else { - line[len - 1] = '\0'; - strcpy(p, line); - lineptr[nlines++] = p; - p += len; + else + { + line[len-1] = '\0'; + 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 */ void writelines(char *lineptr[], int nlines) { int i; From 2cbe94ecf5acf147210db4113140fe43c7a33b38 Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:28:34 +0000 Subject: [PATCH 199/251] Update Ex_5.7_readlines_using_array.c (#149) Added a sort of checking at line 60, in order to make program functional, otherwise its stuck at the while loop forever and program wont do anything besides take input. --- languages/cprogs/Ex_5.7_readlines_using_array.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) 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; } - From 593c15eceba8adef228684d3c00c4ad5dcde170b Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:37:31 +0000 Subject: [PATCH 200/251] Update Ex_5.14_sortrevnum.c (#150) fixed line 50 else statement, where it had no purpose due to both function pointers having a same expression. --- languages/cprogs/Ex_5.14_sortrevnum.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From cf863c7c479a56797fb4f6c2defbbb6a4d6fcd35 Mon Sep 17 00:00:00 2001 From: Milan <68999758+Oroweln@users.noreply.github.com> Date: Sun, 17 Nov 2024 18:02:35 +0000 Subject: [PATCH 201/251] Update Ex_5.18_dcl-errorec.c (#152) An addition to make program clear the arrays of strings after printing out, as to make it usable without restarting the program. --- languages/cprogs/Ex_5.18_dcl-errorec.c | 254 +++++++++++++------------ 1 file changed, 134 insertions(+), 120 deletions(-) diff --git a/languages/cprogs/Ex_5.18_dcl-errorec.c b/languages/cprogs/Ex_5.18_dcl-errorec.c index 64e3c738..86f68385 100644 --- a/languages/cprogs/Ex_5.18_dcl-errorec.c +++ b/languages/cprogs/Ex_5.18_dcl-errorec.c @@ -1,156 +1,170 @@ -/* Make dcl recover from input errors */ +/* DCL: A Recursive Descent Parser */ + +/* dcl: parse a declarator */ #include #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; } - From c2a10ad8974283e0d018436f111f41975aaebcec Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:05:53 +0000 Subject: [PATCH 202/251] Recursive Descent Parser. --- .../chapter5/cprogs/ex_5.18_dcl-errorec.c | 255 +++++++++--------- .../chapter5/ex_5.18_dcl-errorec.rst | 10 + 2 files changed, 143 insertions(+), 122 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c b/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c index 64e3c738..222a8af0 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c @@ -1,156 +1,167 @@ -/* Make dcl recover from input errors */ +/* DCL: A Recursive Descent Parser */ + +/* dcl: parse a declarator */ #include #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 main(void) { - int ns; - - for(ns = 0; gettoken() == '*';) /* count *'s */ - ns++; - - dirdcl(); - - while(ns-- > 0) - strcat(out,"pointer to"); + 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 - -/* enum { NAME,PARENS,BRACKETS}; */ -/* enum { NO,YES }; */ - -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -int prevtoken = NO; + dirdcl(); + while(ns-- > 0) + strcat(out," pointer to"); +} -/* gettoken : return next token */ +/* dirdcl: parse a direct declarator */ -int gettoken(void) +void dirdcl(void) { - int c,getch(void); - void ungetch(int); - - char *p = token; - - if(prevtoken == YES) - { - prevtoken = NO; - - return tokentype; - } - - 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; + 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; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst index 9a1866cc..ac8273d0 100644 --- a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst +++ b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst @@ -14,6 +14,16 @@ Make dcl recover from input errors. Explanation =========== +This program is a recursive descent parser that converts C-style declarations into English descriptions. +The program takes a C declaration as input and converts it into a more readable English description. For example: + +:: + + ./ex_5.18_dcl-errorec + char *str[] + str arg[] of pointer to char + + The program has an errmsg function that is called whenever an error is detected during parsing. The dcl and dirdcl functions, which are responsible for parsing the declarator, continue parsing even if an error is encountered. From a7a2c67703fe6ed91dd0d2b370603d4484175628 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:31:29 +0000 Subject: [PATCH 203/251] Fix exercise 6.3 --- source/cprogramming/chapter6/cprogs/ex_6.3.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/source/cprogramming/chapter6/cprogs/ex_6.3.c b/source/cprogramming/chapter6/cprogs/ex_6.3.c index 7cfa93fc..9fad63ab 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.3.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.3.c @@ -250,6 +250,14 @@ struct linenumber *lnumberalloc(void) { return (struct linenumber *) malloc(sizeof(struct linenumber)); } +void printnumbers(const struct linenumber *p) { + if (p != NULL) { + printf("%d,", p->number); + printnumbers(p->nextnumber); + } +} + + /* treeprint: From K&R2 page 142. Prints tree p in-order. */ void treeprint(const struct tnode *p) { if (p != NULL) { @@ -260,12 +268,6 @@ void treeprint(const struct tnode *p) { } } -void printnumbers(const struct linenumber *p) { - if (p != NULL) { - printf("%d,", p->number); - printnumbers(p->nextnumber); - } -} /* talloc: From K&R2 page 142. Makes a tnode. */ struct tnode *talloc(void) { From f5e68d28b58395cacc54c8251dcc16f16c8a1e5a Mon Sep 17 00:00:00 2001 From: Ivan Shafran <68784245+ShafranIvan@users.noreply.github.com> Date: Sun, 17 Nov 2024 20:46:15 +0200 Subject: [PATCH 204/251] Update Ex_6.3.c (#130) Original code was a mess. There were argc/argv thingy from previous exercise. Line "Remove noise words like "the" and "and" so on." was ignored. Co-authored-by: Shafran-Ivan <68784245+Shafran-Ivan@users.noreply.github.com> --- languages/cprogs/Ex_6.3.c | 393 ++++++++++++++++---------------------- 1 file changed, 163 insertions(+), 230 deletions(-) diff --git a/languages/cprogs/Ex_6.3.c b/languages/cprogs/Ex_6.3.c index 6d648b6d..fae8635c 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 */ - -/* - * 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; -}; - -/* - * 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 */ -}; -/* - * 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 */ -}; +#define MAXWORD 500 -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 binarySearch(const char *arr[], int l, int r, char *x); -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; - } +void treeprint(const struct tnode *p); +char *mstrdup(char *s); - printf("Words with line numbers\n"); +int getWord(char *word, int lim); - treeprint(root); /* prints all the words */ +void ungetch(char c); +int getch(void); - return 0; -} /* end of main() */ +char buf; /* buffer for getch/ungetch */ struct tnode *talloc(void); -char *mstrdup(char *); - -/* mgetword from Ex6.1 */ - -#define IN 1 -#define OUT 0 +struct tnode *addtree(struct tnode *p, char *w, unsigned int l); -int mgetword(char *word, int lim, int *lineno_addr) -{ - int c, d, getch(void), comment, string, directive; - void ungetch(int); - char *w = word; +void printline(const struct ocurLine *p); - comment = string = directive = OUT; +struct ocurLine *linealloc(void); +struct ocurLine *addLine(struct ocurLine *p, unsigned int l); - while (isspace(c = getch())) { - if (c == '\n') { +struct tnode{ + char *word; + unsigned int count; + struct ocurLine *lineOfOccurence; - *lineno_addr = *lineno_addr +1; + struct tnode *left; + struct tnode *right; +}; - } - } +struct ocurLine{ + unsigned int line; + struct ocurLine *next; +}; - /* Check if inside a comment */ - 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; +} From f397cc3d53c9086ac13e88550db9033ce2e972c3 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:53:25 +0000 Subject: [PATCH 205/251] Updated Exercise 6.3 --- languages/cprogs/Ex_6.3.c | 30 +- source/cprogramming/chapter6/cprogs/ex_6.3.c | 391 ++++++++----------- source/cprogramming/chapter6/ex_6.3.rst | 54 ++- 3 files changed, 205 insertions(+), 270 deletions(-) diff --git a/languages/cprogs/Ex_6.3.c b/languages/cprogs/Ex_6.3.c index fae8635c..ee0dd3e1 100644 --- a/languages/cprogs/Ex_6.3.c +++ b/languages/cprogs/Ex_6.3.c @@ -36,6 +36,21 @@ const char *noiseWords[N_OF_NOISEWORDS]={"a", "about", "after", "all", #define MAXWORD 500 + struct tnode{ + char *word; + unsigned int count; + struct ocurLine *lineOfOccurence; + + struct tnode *left; + struct tnode *right; + }; + + + struct ocurLine{ + unsigned int line; + struct ocurLine *next; + }; + int binarySearch(const char *arr[], int l, int r, char *x); void treeprint(const struct tnode *p); @@ -56,21 +71,6 @@ void printline(const struct ocurLine *p); struct ocurLine *linealloc(void); struct ocurLine *addLine(struct ocurLine *p, unsigned int l); -struct tnode{ - char *word; - unsigned int count; - struct ocurLine *lineOfOccurence; - - struct tnode *left; - struct tnode *right; -}; - -struct ocurLine{ - unsigned int line; - struct ocurLine *next; -}; - - int main() { int l=1; diff --git a/source/cprogramming/chapter6/cprogs/ex_6.3.c b/source/cprogramming/chapter6/cprogs/ex_6.3.c index 9fad63ab..a2c3b391 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.3.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.3.c @@ -1,304 +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. * */ -#include -#include +#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 -#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 { +struct tnode{ char *word; - int count; - struct linenumber *linenumbers; + unsigned int count; + struct ocurLine *lineOfOccurence; + struct tnode *left; struct tnode *right; }; -struct linenumber { - int *number; - struct linenumber *nextnumber; -}; -/* - * 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 */ -}; - -/* - * 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 ocurLine{ + unsigned int line; + struct ocurLine *next; }; -struct tnode *addtree(struct tnode *, char *, int); +int binarySearch(const char *arr[], int l, int r, char *x); -void treeprint(const struct tnode *); +void treeprint(const struct tnode *p); +char *mstrdup(char *s); -int mgetword(char *, int, int *); +int getWord(char *word, int lim); -struct linenumber *lnumberalloc(void); +void ungetch(char c); +int getch(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 */ - - return 0; -} /* end of main() */ +char buf; /* buffer for getch/ungetch */ struct tnode *talloc(void); +struct tnode *addtree(struct tnode *p, char *w, unsigned int l); -char *mstrdup(char *); - -/* mgetword from Ex6.1 */ +void printline(const struct ocurLine *p); -#define IN 1 -#define OUT 0 +struct ocurLine *linealloc(void); +struct ocurLine *addLine(struct ocurLine *p, unsigned int l); -int mgetword(char *word, int lim, int *lineno_addr) { - int c, d, getch(void), comment, string, directive; - void ungetch(int); - char *w = word; +int main() +{ + int l=1; + struct tnode *root; + char word[MAXWORD]; - comment = string = directive = OUT; + root = NULL; - while (isspace(c = getch())) { - if (c == '\n') { + 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); +} - *lineno_addr = *lineno_addr + 1; - } - } - /* Check if inside a comment */ +/* 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); - if (c == '/') { - if ((d = getch()) == '*') { - comment = IN; - } else { - comment = OUT; - ungetch(d); - } - } + if (cmp == 0) + return mid; - /* Check if inside a quote */ + if (cmp > 0) + return binarySearch(arr, l, mid - 1, x); - if (c == '\"') { - string = IN; + return binarySearch(arr, mid + 1, r, x); } - /* Check if inside a directive */ - - if (c == '#') { - directive = IN; - } + 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; + } -/*************************************************************************** - * All code below here is from K&R2. * - ***************************************************************************/ + *w = '\0'; + return word[0]; +} -/* - * 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 */ + 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) { + } + else if((cond = strcmp(w, p->word)) == 0){ p->count++; - p->linenumbers = addlinenumber(p->linenumbers, linenumber); - } else if (cond < 0) - p->left = addtree(p->left, w, linenumber); + p->lineOfOccurence = addLine(p->lineOfOccurence, l); + } + else if(cond < 0) + 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); -struct linenumber *lnumberalloc(void) { - return (struct linenumber *) malloc(sizeof(struct linenumber)); -} + printf("%s: [", p->word); -void printnumbers(const struct linenumber *p) { - if (p != NULL) { - printf("%d,", p->number); - printnumbers(p->nextnumber); - } -} + printline(p->lineOfOccurence); + printf("]\n"); -/* treeprint: From K&R2 page 142. Prints tree p in-order. */ -void treeprint(const struct tnode *p) { - if (p != NULL) { - treeprint(p->left); - printf("\n%s :", p->word); - printnumbers(p->linenumbers); treeprint(p->right); } } - /* talloc: From K&R2 page 142. Makes a tnode. */ -struct tnode *talloc(void) { +struct tnode *talloc(void) +{ return (struct tnode *) malloc(sizeof(struct tnode)); } + +/* printline: Prints all lines.*/ +void printline(const struct ocurLine *p) +{ + if (p->next == NULL) + printf("%i", p->line); + else{ + printf("%i, ", p->line); + printline(p->next); + } +} + +/* 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; +} + +/* linealloc: Makes ocurLine*/ +struct ocurLine *linealloc(void) +{ + return (struct ocurLine *) malloc(sizeof(struct ocurLine)); +} + /* strdup: From K&R2 page 143. Makes a duplicate of s. */ -char *mstrdup(char *s) { +char *mstrdup(char *s) +{ char *p; + p = (char *) malloc(strlen(s) + 1); - if (p != NULL) + + 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 */ - -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); +/************************************************************* + * Getch/Ungetch functions from previous exercises * + *************************************************************/ + +/* 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; +/* ungetch: pushes character back on input */ +void ungetch(char c) +{ + buf = c; } \ No newline at end of file diff --git a/source/cprogramming/chapter6/ex_6.3.rst b/source/cprogramming/chapter6/ex_6.3.rst index 6d46538a..d6ff7f13 100644 --- a/source/cprogramming/chapter6/ex_6.3.rst +++ b/source/cprogramming/chapter6/ex_6.3.rst @@ -20,35 +20,25 @@ 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, - - - - + [ec2-user@ip-172-32-32-162 learntosolveit]$ ./ex_6.3 + This is a + cross reference + word + document + creator + lists words and their line numbers. + Gets the word and puts their line numbers. + + Gets: [7] + This: [1] + and: [6, 7] + creator: [5] + cross: [2] + document: [4] + line: [6, 7] + lists: [6] + numbers: [6, 7] + puts: [7] + reference: [2] + word: [3, 7] + words: [6] From a3ce54a7cd01ee027ae14359306262e2794142e4 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 21:00:54 +0000 Subject: [PATCH 206/251] HTML Additional Pages. --- source/conf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/source/conf.py b/source/conf.py index 4466fcfd..d0331fd3 100644 --- a/source/conf.py +++ b/source/conf.py @@ -200,6 +200,7 @@ # 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_additional_pages = {"Courses": "https://courses.learntosolveit.com/"} html_sidebars = {'**': ['logo.html', 'globaltoc.html']} From 958e5cee4769cfe2513c714bfdaac4cc5bbbe0a1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 21:03:46 +0000 Subject: [PATCH 207/251] Updated Using Scanf. --- source/cprogramming/chapter7/ex_7.5.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/source/cprogramming/chapter7/ex_7.5.rst b/source/cprogramming/chapter7/ex_7.5.rst index 4797f5ab..fc6ba70e 100644 --- a/source/cprogramming/chapter7/ex_7.5.rst +++ b/source/cprogramming/chapter7/ex_7.5.rst @@ -15,6 +15,26 @@ input and number conversion. Explanation =========== +In this Reverse Polish Notation Calculator, we use scanf in the getch function. Instead of getchar this uses the function +scanf from the input output library introduced in this chapter. + + +:: + + #define BUFSIZE 100 + char buf[BUFSIZE]; + int bufp = 0; + + int getch(void) { + char c; + if (bufp > 0) { + return buf[--bufp]; + } else { + scanf("%c", &c); + return c; + } + } + From 22c74bcb1eb22d4e3eb923b609e4045c70f40170 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 21:14:32 +0000 Subject: [PATCH 208/251] Fix the source configuration. --- source/conf.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index d0331fd3..c5ed6ea7 100644 --- a/source/conf.py +++ b/source/conf.py @@ -200,8 +200,6 @@ # 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_additional_pages = {"Courses": "https://courses.learntosolveit.com/"} - html_sidebars = {'**': ['logo.html', 'globaltoc.html']} From 043680e9fdf7534b84d81d7d78f9504932f04fce Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 22:01:57 +0000 Subject: [PATCH 209/251] Finished Chapter 7 Explainations. --- source/cprogramming/chapter7/ex_7.6.rst | 10 +++++ source/cprogramming/chapter7/ex_7.7.rst | 3 ++ source/cprogramming/chapter7/ex_7.8.rst | 50 +++++++++++++++++++++++++ source/cprogramming/chapter7/ex_7.9.rst | 11 ++++++ 4 files changed, 74 insertions(+) diff --git a/source/cprogramming/chapter7/ex_7.6.rst b/source/cprogramming/chapter7/ex_7.6.rst index 1f2fa7c4..20ef0199 100644 --- a/source/cprogramming/chapter7/ex_7.6.rst +++ b/source/cprogramming/chapter7/ex_7.6.rst @@ -15,5 +15,15 @@ Explanation =========== +This program reads two files using two file pointers, get one character at a time from each file and compares them, +and if they are not same, prints their differences. + +:: + + if (f1 != f2) { + putchar(f1); + putchar(f2); + break; + } diff --git a/source/cprogramming/chapter7/ex_7.7.rst b/source/cprogramming/chapter7/ex_7.7.rst index 715ec92f..1d97af41 100644 --- a/source/cprogramming/chapter7/ex_7.7.rst +++ b/source/cprogramming/chapter7/ex_7.7.rst @@ -16,6 +16,9 @@ Should the file name be printed when a matching line is found? Explanation =========== +This program searches for a pattern `char pattern[] = "ould";`` in the given input line. +The idea of this program is to take the input from a file. + diff --git a/source/cprogramming/chapter7/ex_7.8.rst b/source/cprogramming/chapter7/ex_7.8.rst index 37ca83e6..d32c2722 100644 --- a/source/cprogramming/chapter7/ex_7.8.rst +++ b/source/cprogramming/chapter7/ex_7.8.rst @@ -16,6 +16,56 @@ with a title and a running page count for each file. Explanation =========== +This takes a file as argument, and prints the file into number of pages, with Page # End as a de-mark at the end of the page. + +:: + + $ ./ex_7.8 README.md + + + File: README.md + + # 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. + + To practice the exercises, you can use the online compilers like + + * [https://www.tutorialspoint.com/compile_c_online.php](https://www.tutorialspoint.com/compile_c_online.php) + * [https://replit.com/](https://replit.com/) + * [https://www.jdoodle.com/c-online-compiler](https://www.jdoodle.com/c-online-compiler) + * [https://www.onlinegdb.com/online_c_compiler](https://www.onlinegdb.com/online_c_compiler) + + Page 1 End. + + * [https://www.codechef.com/ide](https://www.codechef.com/ide) + * [https://www.programiz.com/c-programming/online-compiler/](https://www.programiz.com/c-programming/online-compiler/). + + 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. + + ### Reference Books + + * C Programming Language by Kernighan and Ritchie. + + Page 2 End. + + + + [![Netlify Status](https://api.netlify.com/api/v1/badges/27a766e4-762c-420f-92e2-f35441c79f63/deploy-status)](https://app.netlify.com/sites/learntosolveit/deploys) + [![Documentation Status](https://readthedocs.org/projects/learntosolveit/badge/?version=latest)](http://www.learntosolveit.com/?badge=latest) + + + ## Author + + * Senthil Kumaran + * Email: [senthil@uthcode.com](mailto:senthil@uthcode.com) + + Page 3 End. + + * Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com) + diff --git a/source/cprogramming/chapter7/ex_7.9.rst b/source/cprogramming/chapter7/ex_7.9.rst index 40b6c98d..6f98e1b4 100644 --- a/source/cprogramming/chapter7/ex_7.9.rst +++ b/source/cprogramming/chapter7/ex_7.9.rst @@ -16,6 +16,17 @@ both possibilities. Explanation =========== +This is custom implementation of isupper function instead of the standard library one. + +:: + + int myisupper(int c) { + if (c >= 'A' && c <= 'Z') + return 1; + else + return 0; + } + Visualize ========= From d739d59750f9737775f5acb936576aad05c04f63 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 23:08:30 +0000 Subject: [PATCH 210/251] Updated source for chapter 8. --- .../chapter8/cprogs/ex_8.5_fsize.c | 176 +++++------------- .../chapter8/cprogs/sec_8.3_open_creat.c | 28 ++- source/cprogramming/chapter8/ex_8.1_mycat.rst | 3 + source/cprogramming/chapter8/ex_8.2.rst | 4 + source/cprogramming/chapter8/ex_8.3.rst | 3 + source/cprogramming/chapter8/ex_8.4.rst | 9 + source/cprogramming/chapter8/ex_8.5_fsize.rst | 16 ++ .../cprogramming/chapter8/ex_8.6_calloc.rst | 5 + .../cprogramming/chapter8/ex_8.7_malloc.rst | 9 + source/cprogramming/chapter8/ex_8.8_bfree.rst | 3 + .../chapter8/sec_8.3_open_creat.rst | 6 + 11 files changed, 123 insertions(+), 139 deletions(-) diff --git a/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c index 82a6e237..ce59bcc0 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c @@ -1,162 +1,80 @@ -#include +/* + Modify the fsize program to print the other information contained in the inode entry. + + Solution by Akil Adeshwar + https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_5 +*/ + #include -#include #include -#include -#include +#include #include -#include - -#define NAME_MAX 14 - -typedef struct { - long ino; - char name[NAME_MAX + 1]; -} Dirent; - -typedef struct { - int fd; - Dirent d; -} MYDIR; - -MYDIR *myopendir(char *dirname); - -Dirent *myreaddir(MYDIR *dfd); - -void myclosedir(MYDIR *dfd); - -void fsize(char *); - -void dirwalk(char *, void (*fcn)(char *)); - -/* stat from sys.stat.h has the following structure and these fields can be -accessed. - * -struct stat { - dev_t st_dev; [XSI] ID of device containing file - ino_t st_ino; [XSI] File serial number - mode_t st_mode; [XSI] Mode of file (see below) - nlink_t st_nlink; [XSI] Number of hard links - uid_t st_uid; [XSI] User ID of the file - gid_t st_gid; [XSI] Group ID of the file - dev_t st_rdev; [XSI] Device ID -#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) - struct timespec st_atimespec; time of last access - struct timespec st_mtimespec; time of last data modification - struct timespec st_ctimespec; time of last status change -#else - time_t st_atime; [XSI] Time of last access - long st_atimensec; nsec of last access - time_t st_mtime; [XSI] Last data modification time - long st_mtimensec; last data modification nsec - time_t st_ctime; [XSI] Time of last status change - long st_ctimensec; nsec of last status change -#endif - off_t st_size; [XSI] file size, in bytes - blkcnt_t st_blocks; [XSI] blocks allocated for file - blksize_t st_blksize; [XSI] optimal blocksize for I/O - __uint32_t st_flags; user defined flags for file - __uint32_t st_gen; file generation number - __int32_t st_lspare; RESERVED: DO NOT USE! - __int64_t st_qspare[2]; RESERVED: DO NOT USE! -}; -*/ +#include +#include +#include +#include -/*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; - } +#define MAX_PATH 1024 - if ((stbuf.st_mode & S_IFMT) == S_IFDIR) - dirwalk(name, fsize); +#ifndef DIRSIZ +#define DIRSIZ 14 +#endif - printf("%8ld - %8ld - %8ld - %8ld - %8ld - %8ld %s\n", stbuf.st_size, - stbuf.st_blocks, stbuf.st_blksize, stbuf.st_flags, stbuf.st_gen, - stbuf.st_nlink, name); -} -#define MAX_PATH 1024 +void dirwalk( char *dir,void (*fcn)(char *)){ -void dirwalk(char *dir, void (*fcn)(char *)) { char name[MAX_PATH]; - Dirent *dp; - MYDIR *dfd; + struct dirent *dp; + DIR *dfd; - if ((dfd = myopendir(dir)) == NULL) { - fprintf(stderr, "dirwalk: cant open %s\n", dir); + if((dfd = opendir(dir))==NULL){ + puts("Error: Cannot open Directory"); return; } - - while ((dp = myreaddir(dfd)) != NULL) { - if (strcmp(dp->name, ".") == 0 || strcmp(dp->name, "..") == 0) + puts(dir); + // Get each dir entry + while((dp=readdir(dfd)) != NULL){ + // Skip . and .. is redundant. + if(strcmp(dp->d_name,".") == 0 + || strcmp(dp->d_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); + if(strlen(dir)+strlen(dp->d_name)+2 > sizeof(name)) + puts("Error: Name too long!"); + else{ + sprintf(name,"%s/%s",dir,dp->d_name); + // Call fsize (*fcn)(name); } } - myclosedir(dfd); + closedir(dfd); } -#ifndef DIRSIZ -#define DIRSIZE 14 -#endif - -struct direct { /* directory entry */ - ino_t d_ino; - char d_name[DIRSIZE]; -}; - -MYDIR *myopendir(char *dirname) { - int fd; +void fsize(char *name){ struct stat stbuf; - MYDIR *dp; - - if ((fd = open(dirname, O_RDONLY, 0)) == -1 || fstat(fd, &stbuf) == -1 || - (stbuf.st_mode & S_IFMT) != S_IFDIR || - (dp = (MYDIR *) malloc(sizeof(MYDIR))) == NULL) - return NULL; - dp->fd = fd; - return dp; -} -void myclosedir(MYDIR *dp) { - if (dp) { - close(dp->fd); - free(dp); + if(stat(name,&stbuf) == -1){ + puts("Error: Cannot get file stats!"); + return; + } + + if((stbuf.st_mode & S_IFMT) == S_IFDIR){ + dirwalk(name,fsize); } + struct passwd *pwd = getpwuid(stbuf.st_uid); + //print file name,size and owner + printf("%81d %s Owner: %s\n",(int)stbuf.st_size,name,pwd->pw_name); } -#include -#define DIRSIZE 14 -Dirent *myreaddir(MYDIR *dp) { - struct direct dirbuf; - static Dirent d; - 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, DIRSIZE); - d.name[DIRSIZE] = '\0'; - return &d; - } - return NULL; -} +int main(int argc,char *argv[]){ -int main(int argc, char *argv[]) { - if (argc == 1) + if(argc==1) fsize("."); else - while (--argc > 0) + while(--argc>0) fsize(*++argv); return 0; } diff --git a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c index 5001e581..49618bcf 100644 --- a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c +++ b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c @@ -1,9 +1,12 @@ -#include -#include -#include -#include -#include -#include +#include // For file control options like O_RDONLY +#include // For variable argument functions +#include // For standard I/O +#include // For system calls +#include // For UNIX standard functions like read/write +#include // For exit() + +#define PERMS 0666 // File permissions: read/write for all users +#define BUFSIZ 1024 // Buffer size for reading/writing #define PERMS 0666 /* RW for owner, group and others */ @@ -30,12 +33,17 @@ int main(int argc, char *argv[]) { return 0; } +/** +fmt is the format string parameter +... (ellipsis) indicates variable number of arguments can follow + +*/ void merror(char *fmt, ...) { - va_list args; - va_start(args, fmt); + va_list args; // Declares a variable to hold the argument list + va_start(args, fmt); // Initialize 'args' to start after 'fmt' fprintf(stderr, "error: "); - vfprintf(stderr, fmt, args); + vfprintf(stderr, fmt, args); // Print formatted output using args list fprintf(stderr, "\n"); - va_end(args); + va_end(args); // cleans up variable arguments. exit(1); } diff --git a/source/cprogramming/chapter8/ex_8.1_mycat.rst b/source/cprogramming/chapter8/ex_8.1_mycat.rst index 1edd1584..a4eac327 100644 --- a/source/cprogramming/chapter8/ex_8.1_mycat.rst +++ b/source/cprogramming/chapter8/ex_8.1_mycat.rst @@ -16,4 +16,7 @@ the relative speeds of the two versions. Explanation =========== +This is custom implementation of `cat` program using read/write/open/close function calls instead of the standard library ones. + + diff --git a/source/cprogramming/chapter8/ex_8.2.rst b/source/cprogramming/chapter8/ex_8.2.rst index 1c6f5bfb..d3a6d0cf 100644 --- a/source/cprogramming/chapter8/ex_8.2.rst +++ b/source/cprogramming/chapter8/ex_8.2.rst @@ -16,4 +16,8 @@ Compare code size and execution speed. Explanation =========== +This is a low level implementation of fopen and _fillbuf with enums and fields. + + + diff --git a/source/cprogramming/chapter8/ex_8.3.rst b/source/cprogramming/chapter8/ex_8.3.rst index 046e71a0..4454a521 100644 --- a/source/cprogramming/chapter8/ex_8.3.rst +++ b/source/cprogramming/chapter8/ex_8.3.rst @@ -15,3 +15,6 @@ Design and write _flushbuf, fflush, and fclose. Explanation =========== +This is an internal implementation of `_flushbuf`, `fflush`, and `fclose`. This is implemented by defining a structure called +`_iobuf`, making it point to a file pointer, and reading the contents as a linked list implementation, each time allocating a memory to `base` in the iobuf. + diff --git a/source/cprogramming/chapter8/ex_8.4.rst b/source/cprogramming/chapter8/ex_8.4.rst index 92c982e4..e8174471 100644 --- a/source/cprogramming/chapter8/ex_8.4.rst +++ b/source/cprogramming/chapter8/ex_8.4.rst @@ -19,4 +19,13 @@ The standard library function: Explanation =========== +This uses three fields + +:: + + #define SEEK_SET 0 + #define SEEK_CUR 1 + #define SEEK_END 2 + +and determines where we are in the file using the file seek operations. diff --git a/source/cprogramming/chapter8/ex_8.5_fsize.rst b/source/cprogramming/chapter8/ex_8.5_fsize.rst index 7de7d3ef..b316f08e 100644 --- a/source/cprogramming/chapter8/ex_8.5_fsize.rst +++ b/source/cprogramming/chapter8/ex_8.5_fsize.rst @@ -16,4 +16,20 @@ entry. Explanation =========== +The main purpose of this program information about files and directories, similar to the ls command in Unix-like systems, +but with more detailed information. It prints various file attributes like size, block information, and other metadata. + +If a file argument is provided, it gets file statistics using stat to get the file inode and other information. +If the program encounters a directory, it uses dirwalk to recursively traverse through it and on each file, it does +a stat on the file. + +:: + + $ ./ex_8.5_fsize source/_templates + + source/_templates + 101 source/_templates/index.html Owner: ec2-user + 902 source/_templates/layout.html Owner: ec2-user + 275 source/_templates/logo.html Owner: ec2-user + 60 source/_templates Owner: ec2-user \ No newline at end of file diff --git a/source/cprogramming/chapter8/ex_8.6_calloc.rst b/source/cprogramming/chapter8/ex_8.6_calloc.rst index 2c12fd34..03598c58 100644 --- a/source/cprogramming/chapter8/ex_8.6_calloc.rst +++ b/source/cprogramming/chapter8/ex_8.6_calloc.rst @@ -16,3 +16,8 @@ or by modifying it. Explanation =========== +This is a custom implmentation of calloc. The standard library function calloc(n,size) returns a pointer to n objects +of `size`, with the storage intialized to zero. + +This program writes calloc,by utilizing malloc. + diff --git a/source/cprogramming/chapter8/ex_8.7_malloc.rst b/source/cprogramming/chapter8/ex_8.7_malloc.rst index 2e81b33e..26622729 100644 --- a/source/cprogramming/chapter8/ex_8.7_malloc.rst +++ b/source/cprogramming/chapter8/ex_8.7_malloc.rst @@ -15,3 +15,12 @@ routines so they make more pains with error checking. Explanation =========== +This is an error checking implementation of malloc. If it cannot allocate more bytes, it will throw an error + +:: + + if (nbytes > MAXBYTES) { + fprintf(stderr, "alloc: can't allocate more than %u bytes\n", MAXBYTES); + return NULL; + } + diff --git a/source/cprogramming/chapter8/ex_8.8_bfree.rst b/source/cprogramming/chapter8/ex_8.8_bfree.rst index 90587c41..3613c191 100644 --- a/source/cprogramming/chapter8/ex_8.8_bfree.rst +++ b/source/cprogramming/chapter8/ex_8.8_bfree.rst @@ -18,3 +18,6 @@ Explanation This program manages the memory blocks, takes care of the alignment, and for the smaller memory blocks it maintains a wtbfree method that helps align smaller memory blocks. + +This memory allocation program is simliar how to parking lot orchestrator can allocate park spots for regular sized cars +and smaller vehicles like bikes, and it will squeeze the spots together to make room for bigger car or additional small sized bikes. \ No newline at end of file diff --git a/source/cprogramming/chapter8/sec_8.3_open_creat.rst b/source/cprogramming/chapter8/sec_8.3_open_creat.rst index 9dc4fd08..9f8cb4a9 100644 --- a/source/cprogramming/chapter8/sec_8.3_open_creat.rst +++ b/source/cprogramming/chapter8/sec_8.3_open_creat.rst @@ -15,4 +15,10 @@ Demonstrate the ``cp`` like program which copies the contents of one file to ano Explanation =========== +:: + while ((n = read(f1, buf, BUFSIZ)) > 0) + if (write(f2, buf, n) != n) + +Reads up to BUFSIZ bytes from source file into buffer. Writes the same number of bytes to destination file. continues +until entire file is copied From 96f370a52a44dc31f4d3ee8eda5f236428de1ff8 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 23:20:54 +0000 Subject: [PATCH 211/251] using html theme options. --- source/conf.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source/conf.py b/source/conf.py index c5ed6ea7..e824bb8f 100644 --- a/source/conf.py +++ b/source/conf.py @@ -233,6 +233,14 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' + +html_theme_options = dict( + header_links = "Computer Science Courses|https://courses.learntosolveit.com/", + footer_links = ",".join([ + "Senthil Kumaran|https://senthil.learntosolveit.com/", + ]), +) + project = "" # These are options specifically for the Wagtail Theme. html_theme_options = dict( From f772a5058b5c40e8133935a20854835c2a409696 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 18 Nov 2024 00:24:03 +0000 Subject: [PATCH 212/251] updated chapter 4 file --- .../cprogs/ex_4.8_getch_ungetch_pushback.c | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c 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..cc650c12 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c @@ -0,0 +1,46 @@ +/** + * Description: 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; +} From 68fcd76be6e0033db11ea1273c867ee1917b7101 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:00:06 -0800 Subject: [PATCH 213/251] Updated With Links Removed References to WagTail --- source/conf.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index e824bb8f..1ada1845 100644 --- a/source/conf.py +++ b/source/conf.py @@ -235,7 +235,7 @@ html_theme_options = dict( - header_links = "Computer Science Courses|https://courses.learntosolveit.com/", + header_links = "Computer Science Courses|https://courses.learntosolveit.com/", "Projects|https://projects.learntosolveit.com/", "Just Do Beaver|https://www.justdobeaver.com/", footer_links = ",".join([ "Senthil Kumaran|https://senthil.learntosolveit.com/", ]), @@ -251,4 +251,8 @@ logo_height = 59, logo_url = "/", logo_width = 45, -) \ No newline at end of file + header_links = "Computer Science Courses|https://courses.learntosolveit.com/", + footer_links = ",".join([ + "Senthil Kumaran|https://senthil.learntosolveit.com/", + ]), +) From c260464b61478ba5328815f2c4524eb5760ccf2f Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:07:10 -0800 Subject: [PATCH 214/251] Update conf.py Updated conf changes. --- source/conf.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/source/conf.py b/source/conf.py index 1ada1845..3563bef6 100644 --- a/source/conf.py +++ b/source/conf.py @@ -233,14 +233,6 @@ extensions.append('sphinx_wagtail_theme') html_theme = 'sphinx_wagtail_theme' - -html_theme_options = dict( - header_links = "Computer Science Courses|https://courses.learntosolveit.com/", "Projects|https://projects.learntosolveit.com/", "Just Do Beaver|https://www.justdobeaver.com/", - footer_links = ",".join([ - "Senthil Kumaran|https://senthil.learntosolveit.com/", - ]), -) - project = "" # These are options specifically for the Wagtail Theme. html_theme_options = dict( @@ -251,7 +243,7 @@ logo_height = 59, logo_url = "/", logo_width = 45, - header_links = "Computer Science Courses|https://courses.learntosolveit.com/", + header_links = "Computer Science Courses|https://courses.learntosolveit.com/", "Projects|https://projects.learntosolveit.com/", "Just Do Beaver|https://www.justdobeaver.com/", footer_links = ",".join([ "Senthil Kumaran|https://senthil.learntosolveit.com/", ]), From 42d75fa3b64e12b3aa75560c41529682c85c2016 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:14:49 -0800 Subject: [PATCH 215/251] Update requirements.txt --- requirements.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/requirements.txt b/requirements.txt index 267d0db7..af80e1a8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,4 @@ sphinx sphinx-wagtail-theme -pydata-sphinx-theme -sphinx_bootstrap_theme sphinx-autobuild breathe -sphinx-pdj-theme From 08bb0856c53680eb3a74af13323f252b8e36e186 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:26:35 -0800 Subject: [PATCH 216/251] Update conf.py Fix the syntax error. --- source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index 3563bef6..76e70efb 100644 --- a/source/conf.py +++ b/source/conf.py @@ -243,7 +243,7 @@ logo_height = 59, logo_url = "/", logo_width = 45, - header_links = "Computer Science Courses|https://courses.learntosolveit.com/", "Projects|https://projects.learntosolveit.com/", "Just Do Beaver|https://www.justdobeaver.com/", + header_links = "Computer Science Courses|https://courses.learntosolveit.com/, Projects|https://projects.learntosolveit.com/, Just Do Beaver|https://www.justdobeaver.com/", footer_links = ",".join([ "Senthil Kumaran|https://senthil.learntosolveit.com/", ]), From 03d3d64d43da4baf78ea8c06b7697ee651774501 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 17 Nov 2024 18:28:41 -0800 Subject: [PATCH 217/251] Update conf.py Fix the theme import. --- source/conf.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/source/conf.py b/source/conf.py index 76e70efb..f9bfd7bc 100644 --- a/source/conf.py +++ b/source/conf.py @@ -15,11 +15,6 @@ import os from datetime import date -# At the top. -import sphinx_bootstrap_theme - -# ... - # Activate the theme. #import sphinx_pdj_theme From b3c6870b1ba6ffd9e01482f5848b1a7d96853277 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 23 Nov 2024 15:22:06 +0000 Subject: [PATCH 218/251] Updated Configuration. --- source/conf.py | 145 +------------------------------------------------ 1 file changed, 1 insertion(+), 144 deletions(-) diff --git a/source/conf.py b/source/conf.py index f9bfd7bc..7ee9982e 100644 --- a/source/conf.py +++ b/source/conf.py @@ -11,45 +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 -# Activate the theme. - -#import sphinx_pdj_theme -# html_theme = 'sphinx_pdj_theme' -#html_theme_path = [sphinx_pdj_theme.get_html_theme_path()] -#extensions.append("sphinx_wagtail_theme") -#html_theme = 'sphinx_wagtail_theme' - - -#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', - -#extensions = ['sphinx.ext.extlinks'] - # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -59,122 +22,32 @@ # 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'] # These paths are either relative to html_static_path @@ -187,30 +60,14 @@ # 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 From 586e82828bcd0878ded543886fd954cabe861dfe Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 23 Nov 2024 16:09:11 +0000 Subject: [PATCH 219/251] Project Clean Up. --- .readthedocs.yml | 24 ------------------------ LICENSE | 2 +- pyproject.toml | 14 -------------- utils/cprogramming_template.rst | 26 -------------------------- utils/requirements.txt | 1 - 5 files changed, 1 insertion(+), 66 deletions(-) delete mode 100644 .readthedocs.yml delete mode 100644 pyproject.toml delete mode 100644 utils/cprogramming_template.rst delete mode 100644 utils/requirements.txt 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/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/utils/cprogramming_template.rst b/utils/cprogramming_template.rst deleted file mode 100644 index 45f14b87..00000000 --- a/utils/cprogramming_template.rst +++ /dev/null @@ -1,26 +0,0 @@ -======================= -Exercise NUMBER - TITLE -======================= - -Question -======== - -ADDQUESTION - - -.. literalinclude:: ../../languages/cprogs/PROGRAMNAME.c - :language: c - :tab-width: 4 - - :language: c - -Explanation -=========== - -.. git_changelog:: - - -.. seealso:: - - * :c-suggest-improve:`PROGRAMNAME.c` - * :c-better-explain:`PROGRAMNAME.rst` diff --git a/utils/requirements.txt b/utils/requirements.txt deleted file mode 100644 index db4f14a5..00000000 --- a/utils/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -https://dl.dropbox.com/s/81rheg9ba3w55cx/sphinx-bootstrap-theme-0.4.2.tar.gz From 16d5bff50fe5fb59f71ca7fbf5537dc207db50ab Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Nov 2024 17:07:00 +0000 Subject: [PATCH 220/251] Added Explaination for Exercise 8.2 --- .../chapter4/ex_4.9_getch_ungetch_eof.rst | 2 +- source/cprogramming/chapter8/cprogs/ex_8.2.c | 62 ++----------------- .../cprogramming/chapter8/sec_8.2_getchar.rst | 2 +- .../chapter8/sec_8.3_open_creat.rst | 4 +- 4 files changed, 10 insertions(+), 60 deletions(-) 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/chapter8/cprogs/ex_8.2.c b/source/cprogramming/chapter8/cprogs/ex_8.2.c index 3a5b6cb1..12206523 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.2.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.2.c @@ -1,9 +1,4 @@ -#include -#include -// The functions available from stdio.h are implemented here. -//#include #include -#include #include #ifdef NULL @@ -12,7 +7,7 @@ #define NULL 0 #define EOF (-1) -#define BUFSIZ 1024 +#define BUFSIZE 1024 #define OPEN_MAX 20 /* max # files open at once */ typedef struct _iobuf { @@ -46,56 +41,11 @@ int _fillbuf(FILE *); int _flushbuf(int, FILE *); -#define feof(p) (((p)->flag & _EOF) != 0) -#define ferror(p) (((p)->flag & _ERR) != 0) -#define fileno(p) ((p)->fd) - #define getc(p) (--(p)->cnt >= 0 ? (unsigned char)*(p)->ptr++ : _fillbuf(p)) - #define putc(x, p) (--(p)->cnt >= 0 ? *(p)->ptr++ = (x) : _flushbuf((x), p)) - #define getchar() getc(stdin) #define putchar(x) putc((x), stdout) -#define PERMS 0666 /* RW for owner, group and others */ - -/* fopen: open file, return file ptr */ - -FILE *fopen(char *name, char *mode) { - int fd; - FILE *fp; - - if (*mode != 'r' && *mode != 'w' && *mode != 'a') - return NULL; - - /* Bit operation */ - - for (fp = _iob; fp < _iob + OPEN_MAX; fp++) - if ((fp->flag & (_READ | _WRITE)) == 0) - break; /* found free slot */ - - if (fp >= _iob + OPEN_MAX) /* no free slots */ - return NULL; - - if (*mode == 'w') - fd = creat(name, PERMS); - else if (*mode == 'a') { - if ((fd = open(name, O_WRONLY, 0)) == -1) - fd = creat(name, PERMS); - lseek(fd, 0L, 2); - } else - fd = open(name, O_RDONLY, 0); - - if (fd == -1) /* couldn't access name */ - return NULL; - - fp->fd = fd; - fp->cnt = 0; - fp->base = NULL; - fp->flag = (*mode == 'r') ? _READ : _WRITE; - return fp; -} - /* _fillbuf: allocate and fill input buffer */ int _fillbuf(FILE *fp) { @@ -108,7 +58,7 @@ int _fillbuf(FILE *fp) { /* this is a bit operation */ - bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; + bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZE; if (fp->base == NULL) /* no buffer yet */ if ((fp->base = (char *) malloc(bufsize)) == NULL) @@ -144,12 +94,12 @@ int _flushbuf(int c, FILE *f) { if (f->base == NULL && ((f->flag & _UNBUF) == 0)) { /* no buffer yet */ - if ((f->base = malloc(BUFSIZ)) == NULL) + if ((f->base = malloc(BUFSIZE)) == NULL) /* could not allocate a buffer, so try unbuffered */ f->flag |= _UNBUF; else { f->ptr = f->base; - f->cnt = BUFSIZ - 1; + f->cnt = BUFSIZE - 1; } } @@ -170,7 +120,7 @@ int _flushbuf(int c, FILE *f) { bufsize = (int) (f->ptr - f->base); num_written = write(f->fd, f->base, bufsize); f->ptr = f->base; - f->cnt = BUFSIZ - 1; + f->cnt = BUFSIZE - 1; } if (num_written == bufsize) @@ -191,4 +141,4 @@ int main(int argc, char *argv[]) { while ((c = getchar()) != 'x') { putchar(c); } -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter8/sec_8.2_getchar.rst b/source/cprogramming/chapter8/sec_8.2_getchar.rst index 2a3cdcd5..95417c1f 100644 --- a/source/cprogramming/chapter8/sec_8.2_getchar.rst +++ b/source/cprogramming/chapter8/sec_8.2_getchar.rst @@ -22,7 +22,7 @@ The buffered version of getchar, sets aside a buffer for reading the characters. :: - static char buf[BUFSIZ]; + static char buf[BUFSIZE]; static char *bufp = buf; And reads each of the characters into the buffer, `read(0, buf, sizeof buf)` and then returns one character at a diff --git a/source/cprogramming/chapter8/sec_8.3_open_creat.rst b/source/cprogramming/chapter8/sec_8.3_open_creat.rst index 9f8cb4a9..bf6a0d22 100644 --- a/source/cprogramming/chapter8/sec_8.3_open_creat.rst +++ b/source/cprogramming/chapter8/sec_8.3_open_creat.rst @@ -17,8 +17,8 @@ Explanation :: - while ((n = read(f1, buf, BUFSIZ)) > 0) + while ((n = read(f1, buf, BUFSIZE)) > 0) if (write(f2, buf, n) != n) -Reads up to BUFSIZ bytes from source file into buffer. Writes the same number of bytes to destination file. continues +Reads up to BUFSIZE bytes from source file into buffer. Writes the same number of bytes to destination file. continues until entire file is copied From 4fff08ae3485120723429a56d4bbe4621359fcab Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Nov 2024 19:29:34 +0000 Subject: [PATCH 221/251] updated mycat program. --- source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c | 6 +----- source/cprogramming/concepts/concepts.rst | 0 2 files changed, 1 insertion(+), 5 deletions(-) create mode 100644 source/cprogramming/concepts/concepts.rst diff --git a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c index 52273865..c2dc1b46 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c @@ -1,7 +1,3 @@ -/* 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 */ - #include #include #include @@ -57,4 +53,4 @@ int main(int argc, char *argv[]) { close(fd); } return 0; -} +} \ No newline at end of file diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst new file mode 100644 index 00000000..e69de29b From 6ce885768176bd3968b4cdddb4ebbc4cda4daab1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 24 Nov 2024 20:09:15 +0000 Subject: [PATCH 222/251] Updated exercise 8.3 --- source/cprogramming/chapter8/cprogs/ex_8.3.c | 4 ---- source/cprogramming/concepts/concepts.rst | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/source/cprogramming/chapter8/cprogs/ex_8.3.c b/source/cprogramming/chapter8/cprogs/ex_8.3.c index 5a83067f..755e7019 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.3.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.3.c @@ -1,9 +1,5 @@ #include -#include -// The functions available from stdio.h are implemented here. -//#include #include -#include #include #ifdef NULL diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst index e69de29b..d814c826 100644 --- a/source/cprogramming/concepts/concepts.rst +++ b/source/cprogramming/concepts/concepts.rst @@ -0,0 +1,15 @@ +C Programming Concepts +====================== + +1. Integer and float data types. +2. Character Datatype. +3. Character Array and String. +4. Pointers. +5. Structures. +6. Pointer to Structures. +7. TypeDefs +8. DEFS and IFDEFS Macros +9. Union and Pointer to Unions +10. Bitwise manipulation +11. Using extern +12. Using enums \ No newline at end of file From b93f8f602a660065bc22932c8e98c91c85de6add Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Nov 2024 04:54:48 +0000 Subject: [PATCH 223/251] updated section 6.3 getword. --- languages/cprogs/Ex_5.4_strend.c | 1 + .../chapter6/cprogs/sec_6.3_getword.c | 82 ++++++++++--------- source/cprogramming/concepts/concepts.rst | 8 +- 3 files changed, 51 insertions(+), 40 deletions(-) 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/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c b/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c index f53a17ce..f601a78d 100644 --- a/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c +++ b/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c @@ -2,36 +2,48 @@ #include #include +#define BUFSIZE 100 #define MAXWORD 100 +#define NKEYS (sizeof keytab / sizeof(struct key)) +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + +/* Figure out why printf is a special case */ struct key { char *word; int count; } keytab[] = { - "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, - "continue", 0, "default", 0, "unsigned", 0, "void", 0, "volatile", 0, - "while", 0, "printf", 0, /* Figure out why printf is a special case */ + "auto", 0, + "break", 0, + "case", 0, + "char", 0, + "const", 0, + "continue", 0, + "default", 0, + "unsigned", 0, + "void", 0, + "volatile", 0, + "while", 0, + "printf", 0, }; -#define NKEYS (sizeof keytab / sizeof(struct key)) - -int mgetword(char *, int); - int binsearch(char *, struct key *, int); +int getch(void); +int mgetword(char *, int); +void ungetch(int c); -/* count C keywords */ -int main(int argc, char *argv[]) { - int n; - char word[MAXWORD]; +int getch(void) /* get a (possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} - while (mgetword(word, MAXWORD) != EOF) - if (isalpha(word[0])) - if ((n = binsearch(word, keytab, NKEYS)) >= 0) - keytab[n].count++; - for (n = 0; n < NKEYS; n++) - if (keytab[n].count > 0) - printf("%4d %s\n", keytab[n].count, keytab[n].word); - return 0; +void ungetch(int c) /* push a character back on input */ +{ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; } /* binsearch: find word in tab[0]...tab[n-1] */ @@ -54,8 +66,7 @@ int binsearch(char *word, struct key tab[], int n) { /* getword: get next word or character from input */ int mgetword(char *word, int lim) { - int c, getch(void); - void ungetch(int); + int c; char *w = word; while (isspace(c = getch())); if (c != EOF) @@ -73,20 +84,17 @@ int mgetword(char *word, int lim) { return word[0]; } -#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(); -} +/* count C keywords */ +int main(int argc, char *argv[]) { + int n; + char word[MAXWORD]; -void ungetch(int c) /* push a character back on input */ -{ - if (bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; -} + while (mgetword(word, MAXWORD) != EOF) + if (isalpha(word[0])) + if ((n = binsearch(word, keytab, NKEYS)) >= 0) + keytab[n].count++; + for (n = 0; n < NKEYS; n++) + if (keytab[n].count > 0) + printf("%4d %s\n", keytab[n].count, keytab[n].word); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst index d814c826..a47c0d39 100644 --- a/source/cprogramming/concepts/concepts.rst +++ b/source/cprogramming/concepts/concepts.rst @@ -1,5 +1,5 @@ -C Programming Concepts -====================== +C Programming Building Blocks +============================= 1. Integer and float data types. 2. Character Datatype. @@ -12,4 +12,6 @@ C Programming Concepts 9. Union and Pointer to Unions 10. Bitwise manipulation 11. Using extern -12. Using enums \ No newline at end of file +12. Using enums +13. Important C headers. +14. Program Structure \ No newline at end of file From 709b8759c8f5df33f69435e0728d9c45ed5aafd5 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 25 Nov 2024 05:04:00 +0000 Subject: [PATCH 224/251] Section 6.3 Getword. --- source/cprogramming/chapter6/ex_6.1_getword.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/cprogramming/chapter6/ex_6.1_getword.rst b/source/cprogramming/chapter6/ex_6.1_getword.rst index 4130ca26..2e7b28c0 100644 --- a/source/cprogramming/chapter6/ex_6.1_getword.rst +++ b/source/cprogramming/chapter6/ex_6.1_getword.rst @@ -12,6 +12,12 @@ comments, or preprocessor control lines. Write a better version. :language: c :tab-width: 4 +This is program from Section 6.3 implementing getword. + +.. literalinclude:: cprogs/sec_6.3_getword.c + :language: c + :tab-width: 4 + Explanation =========== From 3b49ca932c067451df1ed7a75486603da3ee76cc Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Tue, 26 Nov 2024 05:33:27 +0000 Subject: [PATCH 225/251] updated source. --- source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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) From f94ac86331d620c67ff0ca81065033fd5277af15 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 15:54:48 +0000 Subject: [PATCH 226/251] updated source and pick random. --- .../chapter2/cprogs/ex_2.9_bitcount2s.c | 8 +-- .../chapter4/cprogs/ex_4.13_reverse_string.c | 62 +++++++++---------- source/cprogramming/pick_random.sh | 2 +- 3 files changed, 34 insertions(+), 38 deletions(-) diff --git a/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c index 5dbdb1dd..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/chapter4/cprogs/ex_4.13_reverse_string.c b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c index b3a0bf54..5c9ec5a4 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c @@ -1,24 +1,32 @@ -/* a recursive version of revese(s); the string reverse function */ - +/* a recursive version of reverse(s); the string reverse function */ #include #include #define MAXLINE 100 -int mgetline(char line[], int lim); - -void reverse(char s[]); - -int main(void) { - char s[MAXLINE]; +void reverse(char s[]) { + static int i = 0; + static int len; - mgetline(s, MAXLINE); + int j; + char c; - reverse(s); + if (i == 0) { + len = strlen(s); + } - printf("%s", s); + j = len - (i + 1); - return 0; + if (i < j) { + c = s[i]; + s[i] = s[j]; + s[j] = c; + i++; + reverse(s); + } else { + // the algorithm has finished so we have to set i=0 again + i = 0; + } } int mgetline(char line[], int lim) { @@ -33,33 +41,21 @@ int mgetline(char line[], int lim) { line[i] = '\0'; } -void reverse(char s[]) { +int main(void) { + char s[MAXLINE]; - static int i = 0; - static int len; + mgetline(s, MAXLINE); - int j; - char c; + reverse(s); + + printf("%s", s); + + return 0; +} - 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/pick_random.sh b/source/cprogramming/pick_random.sh index 893223ec..02355d6f 100755 --- a/source/cprogramming/pick_random.sh +++ b/source/cprogramming/pick_random.sh @@ -1,2 +1,2 @@ #!/bin/sh -find . -type f -name *.c | xargs shuf -n1 -e +find . -type f -print0 -name "*.c" | xargs --null shuf -n1 -e From 1255fae76bffc9844a478e2d42f3e4ffc4c4deec Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 18:11:41 +0000 Subject: [PATCH 227/251] updated source programs. --- .../cprogs/ex_4.1_strindex_rightmost.c | 34 +++++++++---------- .../chapter4/cprogs/ex_4.2_atof_scientific.c | 32 ++++++++--------- .../chapter8/cprogs/ex_8.1_mycat.c | 1 - source/cprogramming/chapter8/cprogs/ex_8.2.c | 16 +++------ source/cprogramming/chapter8/cprogs/ex_8.3.c | 5 --- 5 files changed, 35 insertions(+), 53 deletions(-) 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 38c4d357..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,24 +1,7 @@ -/* strindex which returns rightmost occurance */ +/* strindex which returns rightmost occurrence */ #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; @@ -34,3 +17,18 @@ int mstrindex(char s[],char t[]) } return result; } + +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); + +} \ 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 0bc41cb2..75a8003f 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c @@ -10,19 +10,13 @@ #define MAXLINE 100 -double myatof(char s[]); - -int mgetline(char line[], int lim); - -int main(void) { - char str[MAXLINE]; - double num; - mgetline(str, MAXLINE); - - num = myatof(str); - printf("%f", num); +int power(int base, int exp) { + int power; + power = 1; + while (exp-- > 0) + power *= base; - return 0; + return power; } double myatof(char s[]) { @@ -77,11 +71,13 @@ int mgetline(char line[], int lim) { line[i] = '\0'; } -int power(int base, int exp) { - int power; - power = 1; - while (exp-- > 0) - power *= base; +int main(void) { + char str[MAXLINE]; + double num; + mgetline(str, MAXLINE); - return power; + num = myatof(str); + printf("%f", num); + + return 0; } diff --git a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c index c2dc1b46..164b937f 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c @@ -36,7 +36,6 @@ void filecopy(int ifd, int ofd) { } /* cat: concatenate files - read/write/open/close */ - int main(int argc, char *argv[]) { int fd; diff --git a/source/cprogramming/chapter8/cprogs/ex_8.2.c b/source/cprogramming/chapter8/cprogs/ex_8.2.c index 12206523..df888546 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.2.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.2.c @@ -22,19 +22,13 @@ extern FILE _iob[OPEN_MAX]; #define stdin (&_iob[0]) #define stdout (&_iob[1]) -#define stderr (&_iob[2]) enum _flags { - _READ = 01, - /* file open for reading */ /* binary 1 */ - _WRITE = 02, - /* file open for writing */ /* binary 10 */ - _UNBUF = 03, - /* file is unbuffered */ /* binary 11 */ - _EOF = 010, - /* EOF has occurred on this file */ /* binary 1000 */ - _ERR = 020, - /* error occurred on this file */ /* binary 10000*/ + _READ = 01, /* file open for reading */ /* binary 1 */ + _WRITE = 02, /* file open for writing */ /* binary 10 */ + _UNBUF = 03, /* file is unbuffered */ /* binary 11 */ + _EOF = 010, /* EOF has occurred on this file */ /* binary 1000 */ + _ERR = 020, /* error occurred on this file */ /* binary 10000*/ }; int _fillbuf(FILE *); diff --git a/source/cprogramming/chapter8/cprogs/ex_8.3.c b/source/cprogramming/chapter8/cprogs/ex_8.3.c index 755e7019..945b99c5 100644 --- a/source/cprogramming/chapter8/cprogs/ex_8.3.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.3.c @@ -23,7 +23,6 @@ extern FILE _iob[OPEN_MAX]; #define stdin (&_iob[0]) #define stdout (&_iob[1]) -#define stderr (&_iob[2]) enum _flags { _READ = 01, /* file open for reading */ @@ -37,10 +36,6 @@ int _fillbuf(FILE *); int _flushbuf(int, FILE *); -#define feof(p) (((p)->flag & _EOF) != 0) -#define ferror(p) (((p)->flag & _ERR) != 0) -#define fileno(p) ((p)->fd) - #define getc(p) (--(p)->cnt >= 0 ? (unsigned char)*(p)->ptr++ : _fillbuf(p)) #define putc(x, p) (--(p)->cnt >= 0 ? *(p)->ptr++ = (x) : _flushbuf((x), p)) From 74fb343cde3d095826689a38f947e3c8f33bfa4e Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 19:28:32 +0000 Subject: [PATCH 228/251] Updated Chapter 6 Programs. --- .../cprogs/ex_6.2_identical_variables.c | 1 - source/cprogramming/chapter6/cprogs/ex_6.4.c | 1 - source/cprogramming/chapter6/cprogs/ex_6.5.c | 26 ++--- source/cprogramming/chapter6/cprogs/ex_6.6.c | 107 +++++++----------- .../cprogramming/chapter6/ex_6.1_getword.rst | 8 ++ .../chapter6/ex_6.2_identical_variables.rst | 4 +- source/cprogramming/chapter6/ex_6.3.rst | 8 ++ source/cprogramming/chapter6/ex_6.4.rst | 6 + source/cprogramming/chapter6/ex_6.5.rst | 12 ++ source/cprogramming/chapter6/ex_6.6.rst | 5 + 10 files changed, 91 insertions(+), 87 deletions(-) diff --git a/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c index 923ecb7e..f9c15f40 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c @@ -8,7 +8,6 @@ */ #include -#include #include #include #include diff --git a/source/cprogramming/chapter6/cprogs/ex_6.4.c b/source/cprogramming/chapter6/cprogs/ex_6.4.c index 88fafbff..af21156b 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.4.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.4.c @@ -10,7 +10,6 @@ */ #include -#include #include #include #include diff --git a/source/cprogramming/chapter6/cprogs/ex_6.5.c b/source/cprogramming/chapter6/cprogs/ex_6.5.c index 74d33599..7dc6eec4 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.5.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.5.c @@ -6,22 +6,17 @@ #include #include -/*undef will be if it is just hashtable. Remove it. - * If it is in linked list, delete from linked list. - */ +#define HASHSIZE 101 -/* nlist from K&R Page 144 */ +static struct nlist *hashtab[HASHSIZE]; /* pointer table */ +/* linked List of words. nlist from K&R Page 144 */ struct nlist { /* table entry: */ struct nlist *next; /* next entry in chain */ char *name; /* defined name */ char *defn; /* replacement text */ }; -#define HASHSIZE 101 - -static struct nlist *hashtab[HASHSIZE]; /* pointer table */ - /* hash: form hash value for string s */ unsigned hash(char *s) { unsigned hashval; @@ -33,7 +28,6 @@ unsigned hash(char *s) { } /* lookup: look for s in hashtab */ - struct nlist *lookup(char *s) { struct nlist *np; @@ -43,10 +37,6 @@ struct nlist *lookup(char *s) { return NULL; /* not found */ } -struct nlist *lookup(char *); - -// char *strdup(char *); - /* install: put (name, defn) in hashtab */ struct nlist *install(char *name, char *defn) { struct nlist *np; @@ -69,6 +59,10 @@ struct nlist *install(char *name, char *defn) { return np; } +/** + * undef will be if it is just hashtable. Remove it. + * If it is in linked list, delete from linked list. + **/ struct nlist *undef(char *name) { struct nlist *found; @@ -90,8 +84,10 @@ struct nlist *undef(char *name) { int main(int argc, char *argv[]) { struct nlist *table[4] = { - (install("key", "value")), (install("key1", "value1")), - (install("key2", "value2")), (install("key3", "value3"))}; + (install("key", "value")), + (install("key1", "value1")), + (install("key2", "value2")), + (install("key3", "value3"))}; int i; diff --git a/source/cprogramming/chapter6/cprogs/ex_6.6.c b/source/cprogramming/chapter6/cprogs/ex_6.6.c index 5f32e687..a2296996 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.6.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.6.c @@ -1,35 +1,39 @@ -/* 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. - */ - -/* - * Use getword for #define, key and value - * and use install routines to install it. - * - */ - #include -#include #include #include #include +#define BUFSIZE 100 #define MAXWORD 1000 +#define IN 1 +#define OUT 0 +#define HASHSIZE 101 -int mgetword(char *, int, int *); -/* nlist from K&R Page 144 */ +char buf[BUFSIZE]; /* buffer for ungetch() */ +int bufp = 0; /* next free position in buf */ +static struct nlist *hashtab[HASHSIZE]; /* pointer table */ + +/* linked list. nlist from K&R Page 144 */ struct nlist { /* table entry: */ struct nlist *next; /* next entry in chain */ char *name; /* defined name */ char *defn; /* replacement text */ }; -#define HASHSIZE 101 -static struct nlist *hashtab[HASHSIZE]; /* pointer table */ +int getch(void) { /* get a (possibly pushed back) character */ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { /* push character back on input */ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; + return; +} /* hash: form hash value for string s */ unsigned hash(char *s) { @@ -42,7 +46,6 @@ unsigned hash(char *s) { } /* lookup: look for s in hashtab */ - struct nlist *lookup(char *s) { struct nlist *np; @@ -52,9 +55,6 @@ struct nlist *lookup(char *s) { return NULL; /* not found */ } -struct nlist *lookup(char *); -// char *strdup(char *); - /* install: put (name, defn) in hashtab */ struct nlist *install(char *name, char *defn) { struct nlist *np; @@ -96,35 +96,6 @@ struct nlist *undef(char *name) { return found; } -int main(void) { - - int lineno = 0; - char word[MAXWORD]; - - char key[MAXWORD], value[MAXWORD]; - - struct nlist *result; - - while (mgetword(word, MAXWORD, &lineno) != 'x') { - /* TODO: Strip the spaces */ - if (strcmp(word, "#define ") == 0) { - mgetword(key, MAXWORD, &lineno); - mgetword(value, MAXWORD, &lineno); - install(key, value); - result = lookup(key); - printf("%s->%s", result->name, result->defn); - } - } - - return 0; -} - -; - /* mgetword from Ex6.1 */ - -#define IN 1 -#define OUT 0 - int mgetword(char *word, int lim, int *lineno_addr) { int c, d, getch(void), comment, string, directive; void ungetch(int); @@ -138,9 +109,7 @@ int mgetword(char *word, int lim, int *lineno_addr) { *lineno_addr = *lineno_addr + 1; } } - /* Check if inside a comment */ - if (c == '/') { if ((d = getch()) == '*') { comment = IN; @@ -151,13 +120,11 @@ int mgetword(char *word, int lim, int *lineno_addr) { } /* Check if inside a quote */ - if (c == '\"') { string = IN; } /* Check if inside a directive */ - if (c == '#') { directive = IN; } @@ -225,22 +192,24 @@ int mgetword(char *word, int lim, int *lineno_addr) { return c; } -/* - * getch and ungetch are from K&R2, page 79 - */ -#define BUFSIZE 100 +int main(void) { -char buf[BUFSIZE]; /* buffer for ungetch() */ -int bufp = 0; /* next free position in buf */ + int lineno = 0; + char word[MAXWORD]; -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); -} + char key[MAXWORD], value[MAXWORD]; -void ungetch(int c) { /* push character back on input */ - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; - return; -} + struct nlist *result; + + while (mgetword(word, MAXWORD, &lineno) != 'x') { + if (strcmp(word, "#define ") == 0) { + mgetword(key, MAXWORD, &lineno); + mgetword(value, MAXWORD, &lineno); + install(key, value); + result = lookup(key); + printf("%s->%s", result->name, result->defn); + } + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter6/ex_6.1_getword.rst b/source/cprogramming/chapter6/ex_6.1_getword.rst index 2e7b28c0..66111e33 100644 --- a/source/cprogramming/chapter6/ex_6.1_getword.rst +++ b/source/cprogramming/chapter6/ex_6.1_getword.rst @@ -21,4 +21,12 @@ This is program from Section 6.3 implementing getword. Explanation =========== +This program identifies the keywords in the given input. + +:: + + $ ./ex_6.1_getword + this is a short sentence. + 1 short + diff --git a/source/cprogramming/chapter6/ex_6.2_identical_variables.rst b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst index 4af4e9ca..6f9dd1cc 100644 --- a/source/cprogramming/chapter6/ex_6.2_identical_variables.rst +++ b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst @@ -18,6 +18,8 @@ Make 6 a parameter that can be set from the command line. Explanation =========== - +This program reads a C program and groups similar list of variable names as similar words list. +It parses the C program and stores the variables names in a binary tree, then constructs a similar word list which have +a common prefix length. diff --git a/source/cprogramming/chapter6/ex_6.3.rst b/source/cprogramming/chapter6/ex_6.3.rst index d6ff7f13..b8aa9bec 100644 --- a/source/cprogramming/chapter6/ex_6.3.rst +++ b/source/cprogramming/chapter6/ex_6.3.rst @@ -16,6 +16,14 @@ like ``the, and`` and so on. Explanation =========== +This program is a cross-referencer that prints a list of all words in a document. + +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. + + + Here is an example execution of this program. :: diff --git a/source/cprogramming/chapter6/ex_6.4.rst b/source/cprogramming/chapter6/ex_6.4.rst index 730cc0c6..1f47fd45 100644 --- a/source/cprogramming/chapter6/ex_6.4.rst +++ b/source/cprogramming/chapter6/ex_6.4.rst @@ -15,6 +15,12 @@ decreasing order of frequency of occurrence. Precede each word by its count. Explanation =========== +This program prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Each word +is preceded by its count. + +This works by creating a Tree with word and count, just like tnode. +Parse the tree and create a new tree with count and list of words in the node. Print the new tree in-order traversal. + :: ab diff --git a/source/cprogramming/chapter6/ex_6.5.rst b/source/cprogramming/chapter6/ex_6.5.rst index 7136dbe4..1075d8e1 100644 --- a/source/cprogramming/chapter6/ex_6.5.rst +++ b/source/cprogramming/chapter6/ex_6.5.rst @@ -15,6 +15,18 @@ maintained by lookup and install. Explanation =========== +This program demonstrates implementing a hash table for inserting key -> value. +When there is a collision to inserting values against a key, it will create a linked list of values. + +So, it implements + +* install - installs the word in the hash table. Creates a linked list for the new value. +* lookup - looks up the word in the hash table. +* undef - removes the word in the hash table. + +For each of these operations, it takes word, calculates the hash value. +If there is a collision, it will add the word to the linked list in the hashtable key. + Sample run of this program. :: diff --git a/source/cprogramming/chapter6/ex_6.6.rst b/source/cprogramming/chapter6/ex_6.6.rst index 46ca2a08..57bd0970 100644 --- a/source/cprogramming/chapter6/ex_6.6.rst +++ b/source/cprogramming/chapter6/ex_6.6.rst @@ -16,6 +16,11 @@ also find getch and ungetch helpful. Explanation =========== +This implements a simple version of `#define` pre-processor used in C programs. +In the program program it identifies `#define key value` in the given text, and then using the previously taught +concepts of install, lookup and undef to create a hash table, to keep track of the identified key value pairs in +a hash table. + Example output. :: From e9c55d3e93a5c60859ea9b073317c9c192fa2f02 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 19:43:35 +0000 Subject: [PATCH 229/251] updated cprogramming concepts. --- .../concepts/cprogs/character_datatype.c | 13 +++++++++++++ .../concepts/cprogs/integer_float_data_types.c | 12 ++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 source/cprogramming/concepts/cprogs/character_datatype.c create mode 100644 source/cprogramming/concepts/cprogs/integer_float_data_types.c diff --git a/source/cprogramming/concepts/cprogs/character_datatype.c b/source/cprogramming/concepts/cprogs/character_datatype.c new file mode 100644 index 00000000..8afe8c10 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/character_datatype.c @@ -0,0 +1,13 @@ +#include + +int main(int argc, char *argv[]) { + char char_value; + char_value = 'c'; + printf("The value of my character datatype is %c\n", char_value); + + int i = 0; + for (i = 0; i <128; i++) { + char_value = (char) i; + printf("The value of my character datatype is %c for the integer value %d \n", char_value, i); + } +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/integer_float_data_types.c b/source/cprogramming/concepts/cprogs/integer_float_data_types.c new file mode 100644 index 00000000..bfa0c028 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/integer_float_data_types.c @@ -0,0 +1,12 @@ +#include + +int main(int argc, char *argv[]) { + int int_variable; + float float_variable; + + int_variable = 10; + float_variable = 10.10; + + printf("The value of the integer variable is %d\n", int_variable); + printf("The value of my float variable is %f\n", float_variable); +} \ No newline at end of file From 438e12f314b6ccb641a315949a558ad11e60b773 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 20:35:44 +0000 Subject: [PATCH 230/251] Updated C Programs. --- languages/cprogs/sec_8.3_open_creat.c | 2 +- languages/cprogs/sec_8_2_read_write.c | 2 - .../chapter2/cprogs/ex_2.1_cal_limits.c | 2 +- .../chapter3/cprogs/ex_3.1_binsearch-2.c | 19 +++---- .../chapter3/cprogs/ex_3.2_escape.c | 57 ++++++++----------- .../chapter3/cprogs/ex_3.3_expand.c | 43 +++++++------- .../chapter3/cprogs/ex_3.4-itoa-previous.c | 15 ----- .../chapter3/cprogs/ex_3.4_itoa-2.c | 52 +++++++---------- .../chapter3/cprogs/ex_3.5_itob.c | 38 ++++++------- .../chapter3/cprogs/ex_3.6_itoa-3.c | 39 ++++++------- 10 files changed, 105 insertions(+), 164 deletions(-) delete mode 100644 source/cprogramming/chapter3/cprogs/ex_3.4-itoa-previous.c 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/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c index 2377662e..053cbf30 100644 --- a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c @@ -7,7 +7,7 @@ */ /** - * Priminary Information: + * Preliminary Information: * * ~0 will give bits in 1s. * >> 1 right shift by 1 bit to remove the sign bit. diff --git a/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c b/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 index fe2b7b79..a2b482eb 100644 --- a/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c @@ -1,24 +1,5 @@ -/* 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; @@ -27,19 +8,19 @@ void escape(char s[], char t[]) { 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; + 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; @@ -56,3 +37,15 @@ int mgetline(char s[], int lim) { 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 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-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.4_itoa-2.c b/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 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 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 From 36b4b782e1d60f94d5ea28cae1c85b1fd80083a0 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Fri, 29 Nov 2024 20:47:26 +0000 Subject: [PATCH 231/251] Updated source link and show sphinx. --- source/conf.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/conf.py b/source/conf.py index 7ee9982e..e87f970a 100644 --- a/source/conf.py +++ b/source/conf.py @@ -69,10 +69,10 @@ html_use_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' From e17753c5e58bc75ef3f779a4e73acc23de2e6568 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 15:01:57 +0000 Subject: [PATCH 232/251] Shared Anki Website. --- source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index e87f970a..3d3b63a1 100644 --- a/source/conf.py +++ b/source/conf.py @@ -95,7 +95,7 @@ logo_height = 59, logo_url = "/", logo_width = 45, - header_links = "Computer Science Courses|https://courses.learntosolveit.com/, Projects|https://projects.learntosolveit.com/, Just Do Beaver|https://www.justdobeaver.com/", + 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/", ]), From f81e5e0184f0424aeb2d244365ccb737f6cf3bea Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 16:10:59 +0000 Subject: [PATCH 233/251] Added Configuration and Templates. --- source/_templates/layout.html | 10 ++++ .../chapter1/cprogs/ex_1.10_tbsblnkspaces.c | 3 +- .../chapter1/cprogs/ex_1.20_detab.c | 3 +- .../chapter1/cprogs/ex_1.22_fold.c | 32 +++++------- .../chapter1/cprogs/ex_1.9_sinblank.c | 3 +- .../cprogs/sec_1.10_external_variables.c | 49 +++++++++---------- .../cprogramming/chapter3/ex_3.6_itoa-3.rst | 2 +- .../cprogs/ex_4.10_calculator_getline.c | 4 +- .../chapter4/cprogs/ex_4.11_getch_static.c | 7 +-- .../chapter4/cprogs/ex_4.12_recursive_itoa.c | 4 +- .../chapter4/cprogs/ex_4.13_reverse_string.c | 17 ++----- .../cprogs/ex_4.4_rpn_top_two_elements.c | 8 +-- .../cprogs/ex_4.5_calculator_math_functions.c | 17 ++----- .../chapter4/cprogs/ex_4.7_ungets.c | 2 - .../cprogs/ex_4.8_getch_ungetch_pushback.c | 3 +- .../cprogs/ex_4.9_getch_ungetch_eof.c | 6 ++- 16 files changed, 76 insertions(+), 94 deletions(-) diff --git a/source/_templates/layout.html b/source/_templates/layout.html index b2cd13e8..d7fd7d41 100644 --- a/source/_templates/layout.html +++ b/source/_templates/layout.html @@ -1,4 +1,14 @@ {% extends "!layout.html" %} + +{% block extrahead %} + +{% endblock %} + +{% block extrabody %} +

    Choose only one master - Nature.

    +{% endblock %} + {% block content %} {{ super() }} diff --git a/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c b/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.20_detab.c b/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.22_fold.c b/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.9_sinblank.c b/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 07f71245..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,34 +1,26 @@ #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 mgetline(void); -void copy(void); -/* print longest input line; specialized version */ -int main() { - int len; - extern int max; - extern char longest[]; - max = 0; - while ((len = getline()) > 0) - if (len > max) { - max = len; - copy(); - } - if (max > 0) /* there was a line */ - printf("%s", longest); - return 0; +/* 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) + for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; @@ -38,11 +30,18 @@ int mgetline(void) { return i; } -/* copy: specialized version */ -void copy(void) { - int i; - extern char line[], longest[]; - i = 0; - while ((longest[i] = line[i]) != '\0') - ++i; -} +/* print longest input line; specialized version */ +int main() { + int len; + extern int max; + extern char longest[]; + max = 0; + while ((len = mgetline()) > 0) + if (len > max) { + max = len; + copy(); + } + if (max > 0) /* there was a line */ + printf("%s", longest); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst index 1ab9d5d1..c67fe780 100644 --- a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst +++ b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst @@ -39,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 f2edb01e..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,4 +1,6 @@ -/* Revise the Calculator program to use the getline instead of getch and ungetch */ +/** + * Revise the Calculator program to use the getline instead of getch and ungetch + **/ #include #include /* for atof() */ 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 3f4c73fa..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,4 +1,6 @@ -/* modify getop so that it does not need to use ungetch: Hint: static int lastc */ +/** + * modify getop so that it does not need to use ungetch: Hint: static int lastc + **/ #include #include @@ -121,5 +123,4 @@ int bufp; 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 566af2b1..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,4 +1,6 @@ -/* recursive version of itoa; that converts an integer string by calling a recursive routine */ +/** + * recursive version of itoa; that converts an integer string by calling a recursive routine + **/ #include #include 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 5c9ec5a4..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,4 +1,7 @@ -/* a recursive version of reverse(s); the string reverse function */ +/** + * a recursive version of reverse(s); the string reverse function + **/ + #include #include @@ -51,14 +54,4 @@ int main(void) { printf("%s", s); return 0; -} - - - - - - - - - - +} \ No newline at end of file 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 f7ec1c23..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,9 +1,3 @@ -/* Add commands to - - print top element of the stack,without poping - - duplicate it - - swap the top two elements - - Clear the stack */ - #include #include #include @@ -152,4 +146,4 @@ void ungetch(int c) { 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 e03615cb..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,13 +1,6 @@ -/* Include Mathematical Functions */ -/* Add commands to - - print top element of the stack,without poping - - duplicate it - - swap the top two elements - - Clear the stack */ - -/* IMPORTANT: compile with -lm flag(the static math library) - For eg: gcc -lm rpn-3.c -*/ +/** + * compile with -lm flag(the static math library) + **/ #include #include @@ -39,7 +32,6 @@ double pop(void); void mathfnc(char[]); /* reverse polish calculator */ - int main(void) { int type; double op2, op1; @@ -184,7 +176,6 @@ void ungetch(int c) { } /* mathfnc: check the string s for supported math function */ - void mathfnc(char s[]) { double op2; @@ -199,4 +190,4 @@ void mathfnc(char s[]) { push(pow(pop(), op2)); } else printf("error: %s is not supported\n", s); -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c index 3ad6bc1e..168aac21 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c @@ -1,9 +1,7 @@ /** - * * 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 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 index cc650c12..00d71525 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c @@ -1,7 +1,6 @@ /** - * Description: Suppose that there will never be more than one character + * Suppose that there will never be more than one character * for pushback. Modify getch and ungetch accordingly. - * **/ #include 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 3640a345..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,7 +1,9 @@ -/* getch and ungetch to handle EOF Character In all the ungetch and getch +/** + * 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 */ + * integer declared in stdio.h having the value -1 + **/ #include From de55f26fe128358b6037bcc47d3066153358fd4e Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 16:29:40 +0000 Subject: [PATCH 234/251] Tidying C Programs. --- .../chapter5/cprogs/ex_5.12_condientab.c | 8 +- .../chapter5/cprogs/ex_5.13_tailn.c | 9 +- .../chapter5/cprogs/ex_5.14_sortrevnum.c | 6 +- .../chapter5/cprogs/ex_5.15_sortfnr.c | 5 +- .../chapter5/cprogs/ex_5.16_sort_dfnr.c | 9 +- .../cprogs/ex_5.17_sortdfnr-withoption.c | 7 +- .../chapter5/cprogs/ex_5.19_undcl.c | 122 ++++++++---------- .../chapter5/cprogs/ex_5.20_dcl-funcargs.c | 4 +- 8 files changed, 84 insertions(+), 86 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c b/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c index f8cc3ee2..5161ede8 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c @@ -1,6 +1,8 @@ -/* Extend entab and detab to accept the shorthand entab -m +n - to mean tab stops every n columns; starting at column m. -choose convenient size for the default behaviour */ +/** + * Extend entab and detab to accept the shorthand entab -m +n + * to mean tab stops every n columns; starting at column m. + * choose convenient size for the default behaviour + **/ #include diff --git a/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c b/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c index 6142dbaa..629dde31 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c @@ -1,5 +1,7 @@ -/* Write a Program tail, which prints the last n lines of its input. By default n is 10. let us say; but it can be changed -by an optional argument so that tail -n */ +/** + * Write a Program tail, which prints the last n lines of its input. By default n is 10. let us say; + * but it can be changed by an optional argument so that tail -n. + **/ #include #include @@ -94,5 +96,4 @@ int mgetline(char s[], int lim) { s[i] = '\0'; return i; -} - +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c b/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c index 9a524244..51104759 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c @@ -1,5 +1,7 @@ -/* Modify the sort program to handle a -r flag, which indicates sorting in - reverse ( decreasing) order. Be sure that -r works with -n */ +/** + * Modify the sort program to handle a -r flag, which indicates sorting in reverse ( decreasing) order. + * Be sure that -r works with -n + **/ #include #include diff --git a/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c index 0345c8ef..9e6ebd7b 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c @@ -1,6 +1,7 @@ -/* Add the option -f to fold upper and lower cases together, so that case +/** + * Add the option -f to fold upper and lower cases together, so that case * distinctions are not made clearly during sorting;For eg:a and A compare equal - * */ + **/ #include #include diff --git a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c index ff930dfb..929ace09 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c @@ -1,5 +1,7 @@ -/* Add the -d ("Directory option") which makes comparision only on letters, numbers and blanks. - Make sure it works in conjunction with -f */ +/** + * Add the -d ("Directory option") which makes comparison only on letters, numbers and blanks. + * Make sure it works in conjunction with -f + **/ #include #include @@ -221,5 +223,4 @@ int mgetline(char s[], int lim) { s[i] = '\0'; return i; -} - +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c index f1b60cf8..e50bc729 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c @@ -1,5 +1,8 @@ -/* Add a field handling capablity, so sorting may be done on the fields within lines, - each field sorted according to an independent set of options. ( The index for the KnR Book was sorted with -df for the index category and -n for page number */ +/** + * Add a field handling capability, so sorting may be done on the fields within lines, + * each field sorted according to an independent set of options. + * The index for the KnR Book was sorted with -df for the index category and -n for page number + **/ #include #include diff --git a/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c b/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c index 84d4d68a..aa416444 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c @@ -1,80 +1,45 @@ -/* Modify undcl so that it does not add redundant parenthesiss to declarations */ +/** + * Modify undcl so that it does not add redundant parenthesis to declarations. + **/ #include #include #include #define MAXTOKEN 100 +#define BUFSIZE 100 enum { NAME, PARENS, BRACKETS }; -void dcl(void); - -void dirdcl(void); - - -int gettoken(void); - -int nexttoken(void); +enum { + NO, YES +}; int tokentype; char token[MAXTOKEN]; /* last token string */ char out[1000]; -/* undcl: convert word description to declaration */ - -int main(void) { - int type; - char temp[MAXTOKEN]; +extern int tokentype; /* type of last token */ +extern char token[]; /* last token string */ +int prevtoken = NO; /* there is no previous token */ - while (gettoken() != EOF) { - strcpy(out, token); +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; - while ((type = gettoken()) != '\n') - if (type == PARENS || type == BRACKETS) - strcat(out, token); - else if (type == '*') { - if ((type = nexttoken()) == PARENS || type == BRACKETS) - sprintf(temp, "(*%s)", out); - else - sprintf(temp, "*%s", out); - strcpy(out, temp); - } else if (type == NAME) { - sprintf(temp, " %s %s", token, out); - strcpy(out, temp); - } else - printf("invalid input at %s \n", token); - printf("%s\n", out); - } - return 0; +int getch(void) /* get a(possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); } -enum { - NO, YES -}; - -int gettoken(void); - -/* nexttoken: get the next token and push it back */ -int nexttoken(void) { - int type; - extern int prevtoken; - - type = gettoken(); - prevtoken = YES; - return type; +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; } -#include -#include - - -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -int prevtoken = NO; /* there is no previous token */ - int gettoken(void) /* return next token */ { int c, getch(void); @@ -110,19 +75,40 @@ int gettoken(void) /* return next token */ return tokentype = c; } -#define BUFSIZE 100 -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; +/* nexttoken: get the next token and push it back */ +int nexttoken(void) { + int type; + extern int prevtoken; -int getch(void) /* get a(possibly pushed back) character */ -{ - return (bufp > 0) ? buf[--bufp] : getchar(); + type = gettoken(); + prevtoken = YES; + return type; } -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; -} - + + +int main(void) { + int type; + char temp[MAXTOKEN]; + + while (gettoken() != EOF) { + strcpy(out, token); + + while ((type = gettoken()) != '\n') + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + if ((type = nexttoken()) == PARENS || type == BRACKETS) + sprintf(temp, "(*%s)", out); + else + sprintf(temp, "*%s", out); + strcpy(out, temp); + } else if (type == NAME) { + sprintf(temp, " %s %s", token, out); + strcpy(out, temp); + } else + printf("invalid input at %s \n", token); + printf("%s\n", out); + } + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c index 6fe46c5d..333a27e8 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c @@ -1,4 +1,6 @@ -/* Expand dcl to handle declarations with function argument types,qualifiers like const and so on */ +/** + * Expand dcl to handle declarations with function argument types,qualifiers like const and so on + **/ #include #include From a96a6ac252c9ea4f03e958231abf1a5a3926cc0c Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 17:40:55 +0000 Subject: [PATCH 235/251] updated sources. --- README.md | 4 +- .../chapter5/cprogs/ex_5.16_sort_dfnr.c | 131 ++++++++---------- .../concepts/cprogs/charater_array_string.c | 21 +++ ..._types.c => p1_integer_float_data_types.c} | 0 ...ter_datatype.c => p2_character_datatype.c} | 0 5 files changed, 82 insertions(+), 74 deletions(-) create mode 100644 source/cprogramming/concepts/cprogs/charater_array_string.c rename source/cprogramming/concepts/cprogs/{integer_float_data_types.c => p1_integer_float_data_types.c} (100%) rename source/cprogramming/concepts/cprogs/{character_datatype.c => p2_character_datatype.c} (100%) diff --git a/README.md b/README.md index 317ba80d..9d1b3bd9 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,11 @@ 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. -### Reference Books +### References * C Programming Language by Kernighan and Ritchie. +* https://github.com/jflaherty/ptrtut13/blob/master/md/ch1x.md +* https://manual.cs50.io/ [![Netlify Status](https://api.netlify.com/api/v1/badges/27a766e4-762c-420f-92e2-f35441c79f63/deploy-status)](https://app.netlify.com/sites/learntosolveit/deploys) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c index 929ace09..6e738ac3 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c @@ -5,71 +5,27 @@ #include #include +#include +#include #define NUMERIC 1 /* numeric sort */ #define DECR 2 /* sort in decreasing order */ #define FOLD 4 /* fold upper and lower cases */ #define MDIR 8 /* directory order */ #define LINES 100 /* maximum number of lines to be sorted */ +#define MAXLEN 1000 /* max length of any input line */ -int charcmp(char *, char *); - -int numcmp(char *, char *); - -int readlines(char *lineptr[], int maxlines); - -void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)); - -void writelines(char *lineptr[], int nlines, int order); +int mgetline(char *, int); +char *alloc(int); static char option = 0; -/* sort input lines */ - -int main(int argc, char *argv[]) { - char *lineptr[LINES]; /* pointer to text line */ - int nlines; - int c, rc = 0; - - while (--argc > 0 && (*++argv)[0] == '-') - while (c = *++argv[0]) - switch (c) { - case 'd': /* directory order */ - option |= MDIR; - break; - case 'f': - option |= FOLD; - break; - case 'n': - option |= NUMERIC; - break; - case 'r': - option |= DECR; - break; - default: - printf("sort: illegal option %c\n", c); - argc = 1; - rc = -1; - break; - } - - if (argc) - printf("Usage: sort -dfnr \n"); - else { - if ((nlines = readlines(lineptr, LINES)) > 0) { - if (option & NUMERIC) - myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); - else - myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) charcmp); - - writelines(lineptr, nlines, option & DECR); - } else { - printf("input too big to sort \n"); - rc = -1; - } - } +void swap(void *v[], int i, int j) { + void *temp; - return rc; + temp = v[i]; + v[i] = v[j]; + v[j] = temp; } /* charcmp: return <0 if s < t, 0 if s ==t, >0 if s > t */ @@ -97,10 +53,7 @@ int charcmp(char *s, char *t) { return a - b; } -#include - /* numcmp: compare s1 and s2 numerically */ - int numcmp(char *s1, char *s2) { double v1, v2; @@ -116,17 +69,7 @@ int numcmp(char *s1, char *s2) { } -void swap(void *v[], int i, int j) { - void *temp; - - temp = v[i]; - v[i] = v[j]; - v[j] = temp; -} - - /* 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); @@ -148,11 +91,7 @@ void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { } -#define MAXLEN 1000 /* max length of any input line */ - -int mgetline(char *, int); -char *alloc(int); /* readlines: read input lines */ int readlines(char *lineptr[], int maxlines) { @@ -187,7 +126,6 @@ void writelines(char *lineptr[], int nlines, int order) { #define ALLOCSIZE 10000 /* size of available space */ - static char allocbuf[ALLOCSIZE]; /* storage for alloc */ static char *allocp = allocbuf; /* next free position */ @@ -223,4 +161,51 @@ int mgetline(char s[], int lim) { s[i] = '\0'; return i; -} \ No newline at end of file +} + +/* sort input lines */ +int main(int argc, char *argv[]) { + char *lineptr[LINES]; /* pointer to text line */ + int nlines; + int c, rc = 0; + + while (--argc > 0 && (*++argv)[0] == '-') + while (c = *++argv[0]) + switch (c) { + case 'd': /* directory order */ + option |= MDIR; + break; + case 'f': + option |= FOLD; + break; + case 'n': + option |= NUMERIC; + break; + case 'r': + option |= DECR; + break; + default: + printf("sort: illegal option %c\n", c); + argc = 1; + rc = -1; + break; + } + + if (argc) + printf("Usage: sort -dfnr \n"); + else { + if ((nlines = readlines(lineptr, LINES)) > 0) { + if (option & NUMERIC) + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + else + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) charcmp); + + writelines(lineptr, nlines, option & DECR); + } else { + printf("input too big to sort \n"); + rc = -1; + } + } + + return rc; +} diff --git a/source/cprogramming/concepts/cprogs/charater_array_string.c b/source/cprogramming/concepts/cprogs/charater_array_string.c new file mode 100644 index 00000000..76abd679 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/charater_array_string.c @@ -0,0 +1,21 @@ +#include + +int main(int argc, char *argv[]) { + char s[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'}; + printf("%s\n", s); + + char s1[10]; + int i, j; + for (i = 65, j = 0; i < 70; i++) { + s1[j] = (char) i; + j++; + } + s1[j] = '\0'; + + printf("%s\n", s1); + + char s2[] = "string"; + + printf("%s\n", s2); + +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/integer_float_data_types.c b/source/cprogramming/concepts/cprogs/p1_integer_float_data_types.c similarity index 100% rename from source/cprogramming/concepts/cprogs/integer_float_data_types.c rename to source/cprogramming/concepts/cprogs/p1_integer_float_data_types.c diff --git a/source/cprogramming/concepts/cprogs/character_datatype.c b/source/cprogramming/concepts/cprogs/p2_character_datatype.c similarity index 100% rename from source/cprogramming/concepts/cprogs/character_datatype.c rename to source/cprogramming/concepts/cprogs/p2_character_datatype.c From 0582958e9e29d956d3c74af4d7e5be19bdae9a7d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 17:45:36 +0000 Subject: [PATCH 236/251] Tidying Chapter 5 sort dfnr. --- .../chapter5/cprogs/ex_5.16_sort_dfnr.c | 127 ++++++++---------- 1 file changed, 57 insertions(+), 70 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c index 6e738ac3..97e13a3e 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c @@ -14,10 +14,10 @@ #define MDIR 8 /* directory order */ #define LINES 100 /* maximum number of lines to be sorted */ #define MAXLEN 1000 /* max length of any input line */ +#define ALLOCSIZE 10000 /* size of available space */ -int mgetline(char *, int); -char *alloc(int); - +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ static char option = 0; void swap(void *v[], int i, int j) { @@ -28,46 +28,35 @@ void swap(void *v[], int i, int j) { v[j] = temp; } -/* charcmp: return <0 if s < t, 0 if s ==t, >0 if s > t */ -int charcmp(char *s, char *t) { - char a, b; - int fold = (option & FOLD) ? 1 : 0; - int dir = (option & MDIR) ? 1 : 0; - - do { - if (dir) { - while (!isalnum(*s) && *s != ' ' && *s != '\0') - s++; - while (!isalnum(*t) && *t != ' ' && *t != '\0') - t++; - } - a = fold ? tolower(*s) : *s; - s++; - b = fold ? tolower(*t) : *t; - t++; +/* mgetline: read a line s, return length */ +int mgetline(char s[], int lim) { + int c, i; - if (a == b && a == '\0') - return 0; - } while (a == b); + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } - return a - b; + s[i] = '\0'; + return i; } -/* 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 +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; + } else return 0; } +void afree(char *p) /* free storage pointed to by p */ +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} /* myqsort: sort v[left] ... v[right] into increasing order */ void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { @@ -90,9 +79,6 @@ void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { myqsort(v, last + 1, right, comp); } - - - /* readlines: read input lines */ int readlines(char *lineptr[], int maxlines) { int len, nlines; @@ -111,7 +97,6 @@ int readlines(char *lineptr[], int maxlines) { return nlines; } - /* writelines: write output lines */ void writelines(char *lineptr[], int nlines, int order) { int i; @@ -124,45 +109,47 @@ void writelines(char *lineptr[], int nlines, int order) { printf("%s\n", lineptr[i]); } +/* numcmp: compare s1 and s2 numerically */ +int numcmp(char *s1, char *s2) { + double v1, v2; -#define ALLOCSIZE 10000 /* size of available space */ -static char allocbuf[ALLOCSIZE]; /* storage for alloc */ -static char *allocp = allocbuf; /* next free position */ + v1 = atof(s1); + v2 = atof(s2); -char *alloc(int n) /* return pointer to n characters */ -{ - if (allocbuf + ALLOCSIZE - allocp >= n) { - allocp += n; - return allocp - n; - } else + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else return 0; } +/* charcmp: return <0 if s < t, 0 if s ==t, >0 if s > t */ +int charcmp(char *s, char *t) { + char a, b; + int fold = (option & FOLD) ? 1 : 0; + int dir = (option & MDIR) ? 1 : 0; -void afree(char *p) /* free storage pointed to by p */ -{ - if (p >= allocbuf && p < allocbuf + ALLOCSIZE) - allocp = p; -} - - -/* mgetline: read a line s, return length */ - -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; - } + do { + if (dir) { + while (!isalnum(*s) && *s != ' ' && *s != '\0') + s++; + while (!isalnum(*t) && *t != ' ' && *t != '\0') + t++; + } + a = fold ? tolower(*s) : *s; + s++; + b = fold ? tolower(*t) : *t; + t++; + if (a == b && a == '\0') + return 0; + } while (a == b); - s[i] = '\0'; - return i; + return a - b; } + /* sort input lines */ int main(int argc, char *argv[]) { char *lineptr[LINES]; /* pointer to text line */ @@ -208,4 +195,4 @@ int main(int argc, char *argv[]) { } return rc; -} +} \ No newline at end of file From 192b1e2c2fa4def779d159f4defdc05bb819d8a1 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sat, 30 Nov 2024 23:05:35 +0000 Subject: [PATCH 237/251] updated with more programs. --- source/_templates/layout.html | 4 --- source/conf.py | 2 +- source/cprogramming/concepts/concepts.rst | 3 ++- .../p11_defines_two_dimensional_arrays.c | 23 +++++++++++++++++ .../concepts/cprogs/p12_typedef.c | 9 +++++++ .../cprogramming/concepts/cprogs/p13_malloc.c | 25 +++++++++++++++++++ ...ay_string.c => p3_charater_array_string.c} | 0 .../concepts/cprogs/p9_structures.c | 22 ++++++++++++++++ 8 files changed, 82 insertions(+), 6 deletions(-) create mode 100644 source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c create mode 100644 source/cprogramming/concepts/cprogs/p12_typedef.c create mode 100644 source/cprogramming/concepts/cprogs/p13_malloc.c rename source/cprogramming/concepts/cprogs/{charater_array_string.c => p3_charater_array_string.c} (100%) create mode 100644 source/cprogramming/concepts/cprogs/p9_structures.c diff --git a/source/_templates/layout.html b/source/_templates/layout.html index d7fd7d41..774730ce 100644 --- a/source/_templates/layout.html +++ b/source/_templates/layout.html @@ -5,10 +5,6 @@ crossorigin="anonymous"> {% endblock %} -{% block extrabody %} -

    Choose only one master - Nature.

    -{% endblock %} - {% block content %} {{ super() }} diff --git a/source/conf.py b/source/conf.py index 3d3b63a1..64f0a298 100644 --- a/source/conf.py +++ b/source/conf.py @@ -99,4 +99,4 @@ footer_links = ",".join([ "Senthil Kumaran|https://senthil.learntosolveit.com/", ]), -) +) \ No newline at end of file diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst index a47c0d39..c3b6ee6e 100644 --- a/source/cprogramming/concepts/concepts.rst +++ b/source/cprogramming/concepts/concepts.rst @@ -14,4 +14,5 @@ C Programming Building Blocks 11. Using extern 12. Using enums 13. Important C headers. -14. Program Structure \ No newline at end of file +14. Program Structure +15. malloc and calloc \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c b/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c new file mode 100644 index 00000000..0765eb62 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c @@ -0,0 +1,23 @@ +#include + +#define ROWS 5 +#define COLS 10 + +int main(int argc, char *argv[]) { + int multi[ROWS][COLS]; + + int row, col; + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + multi[row][col] = row * col; + } + } + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + printf("\n%d ", multi[row][col]); + printf("%d ", *(*(multi + row) + col)); + } + } +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p12_typedef.c b/source/cprogramming/concepts/cprogs/p12_typedef.c new file mode 100644 index 00000000..1e29a6c2 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p12_typedef.c @@ -0,0 +1,9 @@ +#include + +int main(int argc, char *argv[]) { + typedef unsigned char byte; + + byte b[] = {'b', 'y', 't', 'e', '\0'}; + + printf("%s", b); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p13_malloc.c b/source/cprogramming/concepts/cprogs/p13_malloc.c new file mode 100644 index 00000000..7a68a359 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p13_malloc.c @@ -0,0 +1,25 @@ +#include +#include + +#define COLS 5 + + +int main(int argc, char *argv[]) { + + typedef int RowArray[COLS]; + RowArray *rptr; + + int nrows = 10; + int row, col; + + rptr = malloc(nrows * COLS * sizeof (int)); + + for (row = 0; row < nrows; row++ ) { + for (col = 0; col < COLS; col++) { + rptr[row][col] = row * col; + } + } + + free(rptr); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/charater_array_string.c b/source/cprogramming/concepts/cprogs/p3_charater_array_string.c similarity index 100% rename from source/cprogramming/concepts/cprogs/charater_array_string.c rename to source/cprogramming/concepts/cprogs/p3_charater_array_string.c diff --git a/source/cprogramming/concepts/cprogs/p9_structures.c b/source/cprogramming/concepts/cprogs/p9_structures.c new file mode 100644 index 00000000..b6ff38fd --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p9_structures.c @@ -0,0 +1,22 @@ +#include +#include + +int main(int argc, char *argv[]) { + struct tag { + char lname[20]; + char fname[20]; + int age; + float rate; + }; + + struct tag my_struct; + + strcpy(my_struct.lname, "Kumaran"); + strcpy(my_struct.fname, "Senthil"); + + printf("\n%s ", my_struct.fname); + printf("%s\n", my_struct.lname); + + return 0; +} + From d4c8679fcbd900dda1ca254ed52daec47c339e24 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 04:08:58 +0000 Subject: [PATCH 238/251] Conditional Compilation. --- .../cprogramming/concepts/cprogs/p14_macros.c | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 source/cprogramming/concepts/cprogs/p14_macros.c diff --git a/source/cprogramming/concepts/cprogs/p14_macros.c b/source/cprogramming/concepts/cprogs/p14_macros.c new file mode 100644 index 00000000..2d4716eb --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p14_macros.c @@ -0,0 +1,31 @@ +#ifndef MY_PROGRAM_HEADER +#define MY_PROGRAM_HEADER + +#define SQUARE(x) ((x) * (x)) +#define WINDOWS 1 +#define LINUX 2 +#define PLATFORM LINUX + +#include + +int main(int argc, char *argv[]) { + int num = 20; + printf("Square of the number is %d\n", SQUARE(num)); + + // Conditinal Compilation + +#ifdef PLATFORM +#if PLATFORM == WINDOWS + printf("Compiling for Windows\n"); +#define PATH_SEPARATOR "\\" +#elif PLATFORM == LINUX + printf("Compiling for Linux\n"); +#endif +#define PATH_SEPARATOR "/" +#else +#error Platform not defined! +#endif + +} + +#endif // MY_PROGRAM_HEADER \ No newline at end of file From 976d3b7348c566ac8e8b2289b3aa41f58732b8fb Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 04:14:47 +0000 Subject: [PATCH 239/251] Updated concepts. --- source/cprogramming/chapter8/ex_8.2.rst | 2 - source/cprogramming/concepts/concepts.rst | 45 +++++++++++++++-------- source/index.rst | 1 + 3 files changed, 31 insertions(+), 17 deletions(-) diff --git a/source/cprogramming/chapter8/ex_8.2.rst b/source/cprogramming/chapter8/ex_8.2.rst index d3a6d0cf..a6ce6a34 100644 --- a/source/cprogramming/chapter8/ex_8.2.rst +++ b/source/cprogramming/chapter8/ex_8.2.rst @@ -8,8 +8,6 @@ Question Rewrite fopen and _fillbuf with fields instead of explicit bit operations. Compare code size and execution speed. -**inprogress** - .. literalinclude:: cprogs/ex_8.2.c :language: c diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst index c3b6ee6e..c1600bf5 100644 --- a/source/cprogramming/concepts/concepts.rst +++ b/source/cprogramming/concepts/concepts.rst @@ -1,18 +1,33 @@ C Programming Building Blocks ============================= -1. Integer and float data types. -2. Character Datatype. -3. Character Array and String. -4. Pointers. -5. Structures. -6. Pointer to Structures. -7. TypeDefs -8. DEFS and IFDEFS Macros -9. Union and Pointer to Unions -10. Bitwise manipulation -11. Using extern -12. Using enums -13. Important C headers. -14. Program Structure -15. malloc and calloc \ No newline at end of file +These are simple C programs that provide an intuitive understanding of the entire +language. These are building blocks of programs that can help you understand any +complex program. This even this entire Learn To Solve It can be approached if the reader +has the intuitive understanding of these building block C Programs. + +Integer and float data types +---------------------------- + +.. literalinclude:: cprogs/p1_integer_float_data_types.c + :language: c + +Character Datatype +------------------ + +.. literalinclude:: cprogs/p2_character_datatype.c + :language: c + +Character Array and String +Pointers +Structures +Pointer to Structures +TypeDefs +DEFS and IFDEFS Macros +Union and Pointer to Unions +Bitwise manipulation +Using extern +Using enums +Important C headers +Program Structure +malloc and calloc \ No newline at end of file diff --git a/source/index.rst b/source/index.rst index ef961a19..0bb1bd48 100644 --- a/source/index.rst +++ b/source/index.rst @@ -25,3 +25,4 @@ C Programming ./cprogramming/chapter6/index.rst ./cprogramming/chapter7/index.rst ./cprogramming/chapter8/index.rst + ./concepts/concepts.rst From ec28c5523b3594534abf5b1c4e01f4d49a7a5fa9 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 14:49:55 +0000 Subject: [PATCH 240/251] updated C programming concepts --- source/cprogramming/concepts/cprogs/config.c | 11 ++++ source/cprogramming/concepts/cprogs/config.h | 11 ++++ source/cprogramming/concepts/cprogs/other.h | 12 ++++ .../cprogramming/concepts/cprogs/p15_union.c | 23 ++++++++ .../concepts/cprogs/p16_bitwise.c | 59 +++++++++++++++++++ .../cprogramming/concepts/cprogs/p17_extern.c | 21 +++++++ .../cprogramming/concepts/cprogs/p18_enums.c | 38 ++++++++++++ .../concepts/cprogs/p18_extern_config.c | 14 +++++ source/index.rst | 2 +- 9 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 source/cprogramming/concepts/cprogs/config.c create mode 100644 source/cprogramming/concepts/cprogs/config.h create mode 100644 source/cprogramming/concepts/cprogs/other.h create mode 100644 source/cprogramming/concepts/cprogs/p15_union.c create mode 100644 source/cprogramming/concepts/cprogs/p16_bitwise.c create mode 100644 source/cprogramming/concepts/cprogs/p17_extern.c create mode 100644 source/cprogramming/concepts/cprogs/p18_enums.c create mode 100644 source/cprogramming/concepts/cprogs/p18_extern_config.c diff --git a/source/cprogramming/concepts/cprogs/config.c b/source/cprogramming/concepts/cprogs/config.c new file mode 100644 index 00000000..0201010c --- /dev/null +++ b/source/cprogramming/concepts/cprogs/config.c @@ -0,0 +1,11 @@ +#include "config.h" + +struct Config app_config = { + .max_connections = 100, + .server_name = "localhost", + .port = 8080 +}; + +void init_config(void) { + // Initialize configuration +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/config.h b/source/cprogramming/concepts/cprogs/config.h new file mode 100644 index 00000000..2f966e59 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/config.h @@ -0,0 +1,11 @@ +#ifndef LEARNTOSOLVEIT_CONFIG_H +#define LEARNTOSOLVEIT_CONFIG_H + +extern struct Config { + int max_connections; + char *server_name; + int port; +} app_config; + +extern void init_config(void); +#endif //LEARNTOSOLVEIT_CONFIG_H diff --git a/source/cprogramming/concepts/cprogs/other.h b/source/cprogramming/concepts/cprogs/other.h new file mode 100644 index 00000000..2c7656f1 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/other.h @@ -0,0 +1,12 @@ +#ifndef LEARNTOSOLVEIT_OTHER_H +#define LEARNTOSOLVEIT_OTHER_H + +#include +int shared_value = 10; + +void modify_value(void) { + shared_value *= 2; + printf("Modified in other.h : %d\n", shared_value); +} + +#endif //LEARNTOSOLVEIT_OTHER_H diff --git a/source/cprogramming/concepts/cprogs/p15_union.c b/source/cprogramming/concepts/cprogs/p15_union.c new file mode 100644 index 00000000..3d286895 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p15_union.c @@ -0,0 +1,23 @@ +#include + +union Data { + int i; + float f; + char str[20]; +}; + +int main(int argc, char *argv[]) { + union Data data; + union Data *ptr; + + ptr = &data; + + data.i = 42; + printf("Integer value: %d \n", data.i); + + ptr->f = 3.14; + printf("Float value: %f\n", data.f); + + printf("Integer value again: %d \n", data.i); + printf("Since Union share memory, the integer value is lost."); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p16_bitwise.c b/source/cprogramming/concepts/cprogs/p16_bitwise.c new file mode 100644 index 00000000..ec4acb9b --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p16_bitwise.c @@ -0,0 +1,59 @@ +#include +#include + +/** + * %b specifier is available since C23 + * https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2630.pdf + * if %b is not available for your compiler + * we can use print_bin to see the binary + **/ + +void print_bin(unsigned char byte) +{ + int i = CHAR_BIT; /* however many bits are in a byte on your platform */ + while(i--) { + putchar('0' + ((byte >> i) & 1)); /* loop through and print the bits */ + } +} + +int main(int argc, char *argv[]) { + unsigned char a = 12 ; // Binary 00001100 + unsigned char b = 10; // Binary 00001010 + + printf("Original Values: \n"); + printf("a = %d (Binary: %08b)\n", a, a); + printf("b = %d (Binary: %08b)\n", b, b); + + printf("Decimal %d in Binary is", a); + print_bin(a); + + printf("\n"); + + printf("Decimal %d in Binary is", b); + print_bin(b); + + // Bitwise AND (&) + printf("\n Bitwise AND (&): \n"); + printf("%d & %d = %d (binary: %08b)\n", a, b, a & b, a & b); + + + // Bitwise OR (|) + printf("\n Bitwise OR (|): \n"); + printf("%d | %d = %d (binary: %08b)\n", a, b, a | b, a | b); + + // Bitwise XOR (^) + printf("\n Bitwise XOR (^): \n"); + printf("%d ^ %d = %d (binary: %08b)\n", a, b, a ^b, a ^b); + + // Left shift << + printf("\n Left Shift (<<): \n"); + printf("%d << 1 = %d (binary: %08b)\n", a, a << 1, a << 1); + + // Right shift >> + printf("\n Right Shift (>>): \n"); + printf("%d >> 1 = %d (binary: %08b)\n", a, a >> 1, a >> 1); + + // Bitwise NOT (~) + printf("\n Bitwise NOT (~) \n"); + printf("~%d = %d (binary: %08b)\n", a, (unsigned char) ~a, (unsigned char)~a); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p17_extern.c b/source/cprogramming/concepts/cprogs/p17_extern.c new file mode 100644 index 00000000..d2ea0a15 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p17_extern.c @@ -0,0 +1,21 @@ +#include +#include "other.h" + +// Declare the external variable +extern int shared_value; // This tells compiler variable is defined elsewhere +extern void modify_value(void); // Declare external function + +int main(int argc, char *argv[]) { + printf("Initial shared value: %d\n", shared_value); + + + // Modify the value in main + shared_value = 20; + printf("After modifying the value in main: %d\n", shared_value); + + + modify_value(); + printf("After calling modify_value: %d\n", shared_value); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p18_enums.c b/source/cprogramming/concepts/cprogs/p18_enums.c new file mode 100644 index 00000000..f2dac0d5 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p18_enums.c @@ -0,0 +1,38 @@ +#include + + +enum DayOfWeek { + SUNDAY = 1, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY +}; + +enum TaskStatus { + PENDING, // Will start at 0 + IN_PROGRESS, + COMPLETED, + CANCELLED +}; + +int main(int argc, char *argv[]) { + enum DayOfWeek today = WEDNESDAY; + printf("Day number of the week %d\n", today); + + + enum TaskStatus status = PENDING; + printf("\nTask Status: \n"); + printf("Initial Status: %d\n", status); + + status = COMPLETED; + printf("Updated status: %d\n", status); + + if (status == COMPLETED) { + printf("Task is Complete!\n"); + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p18_extern_config.c b/source/cprogramming/concepts/cprogs/p18_extern_config.c new file mode 100644 index 00000000..901b9c7d --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p18_extern_config.c @@ -0,0 +1,14 @@ +#include +#include "config.h" + +/** + * $ gcc p18_extern_config.c config.c -o p18_extern_config + * $ ./p18_extern_config + * Max connections: 100 + **/ + +int main(int argc, char *argv[]) { + init_config(); + printf("Max connections: %d\n", app_config.max_connections); + return 0; +} \ No newline at end of file diff --git a/source/index.rst b/source/index.rst index 0bb1bd48..a5ee9335 100644 --- a/source/index.rst +++ b/source/index.rst @@ -25,4 +25,4 @@ C Programming ./cprogramming/chapter6/index.rst ./cprogramming/chapter7/index.rst ./cprogramming/chapter8/index.rst - ./concepts/concepts.rst + ./cprogramming/concepts/concepts.rst From 32e3c3ecfd22f26580fe6ed9283f134f04309b1d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 15:11:33 +0000 Subject: [PATCH 241/251] updated concepts in C. --- source/cprogramming/concepts/concepts.rst | 85 ++++++++++++++++++- .../cprogs/{p18_enums.c => p19_enums.c} | 0 2 files changed, 82 insertions(+), 3 deletions(-) rename source/cprogramming/concepts/cprogs/{p18_enums.c => p19_enums.c} (100%) diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst index c1600bf5..2c5894b6 100644 --- a/source/cprogramming/concepts/concepts.rst +++ b/source/cprogramming/concepts/concepts.rst @@ -19,15 +19,94 @@ Character Datatype :language: c Character Array and String +-------------------------- + +.. literalinclude:: cprogs/p3_charater_array_string.c + :language: c + Pointers +-------- + +.. literalinclude:: cprogs/p4_pointer.c + :language: c + +.. literalinclude:: cprogs/p5_pointer.c + :language: c + +.. literalinclude:: cprogs/p6_pointer.c + :language: c + +.. literalinclude:: cprogs/p7_pointer.c + :language: c + +.. literalinclude:: cprogs/p8_pointer.c + :language: c + Structures +---------- + +.. literalinclude:: cprogs/p9_structures.c + :language: c + Pointer to Structures +--------------------- + +.. literalinclude:: cprogs/p10_pointer_to_structures.c + :language: c + TypeDefs +-------- + +.. literalinclude:: cprogs/p11_defines_two_dimensional_arrays.c + :language: c + DEFS and IFDEFS Macros +---------------------- + +.. literalinclude:: cprogs/p14_macros.c + :language: c + Union and Pointer to Unions +--------------------------- + +.. literalinclude:: cprogs/p15_union.c + :language: c + Bitwise manipulation +-------------------- + +.. literalinclude:: cprogs/p16_bitwise.c + :language: c + Using extern +------------ + +.. literalinclude:: cprogs/p17_extern.c + :language: c + +.. literalinclude:: cprogs/other.h + :language: c + +A practical program demonstrating the use of externs + +.. literalinclude:: cprogs/p18_extern_config.c + :language: c + +.. literalinclude:: cprogs/config.h + :language: c + +.. literalinclude:: cprogs/config.c + :language: c + + Using enums -Important C headers -Program Structure -malloc and calloc \ No newline at end of file +----------- + +.. literalinclude:: cprogs/p19_enums.c + :language: c + +malloc and calloc +----------------- + +.. literalinclude:: cprogs/p13_malloc.c + :language: c \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p18_enums.c b/source/cprogramming/concepts/cprogs/p19_enums.c similarity index 100% rename from source/cprogramming/concepts/cprogs/p18_enums.c rename to source/cprogramming/concepts/cprogs/p19_enums.c From 49323852faaf2082706d62880c7902af0a2f4853 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 15:14:48 +0000 Subject: [PATCH 242/251] Adding Ads.txt --- source/_static/Ads.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 source/_static/Ads.txt diff --git a/source/_static/Ads.txt b/source/_static/Ads.txt new file mode 100644 index 00000000..fc885ab1 --- /dev/null +++ b/source/_static/Ads.txt @@ -0,0 +1 @@ +google.com, pub-8197049942123554, DIRECT, f08c47fec0942fa0 \ No newline at end of file From ef14c73f3b0a2ecd9847766578fb8b1b5a9c5a43 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 15:32:02 +0000 Subject: [PATCH 243/251] html extra path. --- source/{_static => }/Ads.txt | 0 source/conf.py | 2 ++ 2 files changed, 2 insertions(+) rename source/{_static => }/Ads.txt (100%) diff --git a/source/_static/Ads.txt b/source/Ads.txt similarity index 100% rename from source/_static/Ads.txt rename to source/Ads.txt diff --git a/source/conf.py b/source/conf.py index 64f0a298..a7f2d269 100644 --- a/source/conf.py +++ b/source/conf.py @@ -50,6 +50,8 @@ html_static_path = ['_static'] +html_extra_path = ["Ads.txt"] + # These paths are either relative to html_static_path # or fully qualified paths (eg. https://...) From fc68ad3179b7a1a397f6bb15b41a6ac2caac4f50 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 16:47:16 +0000 Subject: [PATCH 244/251] Updated program on malloc. --- source/cprogramming/concepts/cprogs/p13_malloc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/cprogramming/concepts/cprogs/p13_malloc.c b/source/cprogramming/concepts/cprogs/p13_malloc.c index 7a68a359..e2ff5ff6 100644 --- a/source/cprogramming/concepts/cprogs/p13_malloc.c +++ b/source/cprogramming/concepts/cprogs/p13_malloc.c @@ -7,14 +7,14 @@ int main(int argc, char *argv[]) { typedef int RowArray[COLS]; - RowArray *rptr; + RowArray *rptr; int nrows = 10; int row, col; - rptr = malloc(nrows * COLS * sizeof (int)); + rptr = malloc(nrows * COLS * sizeof(int)); - for (row = 0; row < nrows; row++ ) { + for (row = 0; row < nrows; row++) { for (col = 0; col < COLS; col++) { rptr[row][col] = row * col; } From a5969dac9206359f71d09a439026f56eeec3459e Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 16:58:50 +0000 Subject: [PATCH 245/251] Updated C Pointer Examples. --- .../cprogs/p10_pointer_to_structures.c | 30 +++++++++++++++++++ .../cprogramming/concepts/cprogs/p4_pointer.c | 7 +++++ .../cprogramming/concepts/cprogs/p5_pointer.c | 17 +++++++++++ .../cprogramming/concepts/cprogs/p6_pointer.c | 16 ++++++++++ .../cprogramming/concepts/cprogs/p7_pointer.c | 22 ++++++++++++++ .../cprogramming/concepts/cprogs/p8_pointer.c | 24 +++++++++++++++ 6 files changed, 116 insertions(+) create mode 100644 source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c create mode 100644 source/cprogramming/concepts/cprogs/p4_pointer.c create mode 100644 source/cprogramming/concepts/cprogs/p5_pointer.c create mode 100644 source/cprogramming/concepts/cprogs/p6_pointer.c create mode 100644 source/cprogramming/concepts/cprogs/p7_pointer.c create mode 100644 source/cprogramming/concepts/cprogs/p8_pointer.c diff --git a/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c b/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c new file mode 100644 index 00000000..fa72b97f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c @@ -0,0 +1,30 @@ +#include +#include + +struct tag { /* the structure type */ + char lname[20]; /* last name */ + char fname[20]; /* first name */ + int age; /* age */ + float rate; /* e.g. 12.75 per hour */ +}; + +struct tag my_struct; /* define the structure */ +void show_name(struct tag *p); /* function prototype */ + +int main(void) { + struct tag *st_ptr; /* a pointer to a structure */ + st_ptr = &my_struct; /* point the pointer to my_struct */ + strcpy(my_struct.lname, "Jensen"); + strcpy(my_struct.fname, "Ted"); + printf("\n%s ", my_struct.fname); + printf("%s\n", my_struct.lname); + my_struct.age = 63; + show_name(st_ptr); /* pass the pointer */ + return 0; +} + +void show_name(struct tag *p) { + printf("\n%s ", p->fname); /* p points to a structure */ + printf("%s ", p->lname); + printf("%d\n", p->age); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p4_pointer.c b/source/cprogramming/concepts/cprogs/p4_pointer.c new file mode 100644 index 00000000..413a13da --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p4_pointer.c @@ -0,0 +1,7 @@ +#include + +int main() { + printf("size of a short is %d\\n", sizeof(short)); + printf("size of a int is %d\\n", sizeof(int)); + printf("size of a long is %d\\n", sizeof(long)); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p5_pointer.c b/source/cprogramming/concepts/cprogs/p5_pointer.c new file mode 100644 index 00000000..7e0f577f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p5_pointer.c @@ -0,0 +1,17 @@ +#include + +int main(void) { + + int j, k; + int *ptr; + j = 1; + k = 2; + ptr = &k; + printf("\n"); + printf("j has the value %d and is stored at %p\n", j, (void *) &j); + printf("k has the value %d and is stored at %p\n", k, (void *) &k); + printf("ptr has the value %p and is stored at %p\n", ptr, (void *) &ptr); + printf("The value of the integer pointed to by ptr is %d\n", *ptr); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p6_pointer.c b/source/cprogramming/concepts/cprogs/p6_pointer.c new file mode 100644 index 00000000..981a7090 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p6_pointer.c @@ -0,0 +1,16 @@ +#include + + +int main(void) { + + int my_array[] = {1, 23, 17, 4, -5, 100}; + int *ptr; + int i; + ptr = &my_array[0]; + printf("\n\n"); + for (i = 0; i < 6; i++) { + printf("my_array[%d] = %d ", i, my_array[i]); + printf("ptr + %d = %d\n", i, *(ptr + i)); + } + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p7_pointer.c b/source/cprogramming/concepts/cprogs/p7_pointer.c new file mode 100644 index 00000000..f119cb2b --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p7_pointer.c @@ -0,0 +1,22 @@ +#include + +int main(void) { + + char strA[80] = "A string to be used for demonstration purposes"; + char strB[80]; + + char *pA; /* a pointer to type character */ + char *pB; /* another pointer to type character */ + puts(strA); /* show string A */ + pA = strA; /* point pA at string A */ + puts(pA); /* show what pA is pointing to */ + pB = strB; /* point pB at string B */ + putchar('\n'); /* move down one line on the screen */ + while (*pA != '\0') /* line A (see text) */ + { + *pB++ = *pA++; /* line B (see text) */ + } + *pB = '\0'; /* line C (see text) */ + puts(strB); /* show strB on screen */ + return 0; +} diff --git a/source/cprogramming/concepts/cprogs/p8_pointer.c b/source/cprogramming/concepts/cprogs/p8_pointer.c new file mode 100644 index 00000000..5f05bc1f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p8_pointer.c @@ -0,0 +1,24 @@ +#include + +#define ROWS 5 +#define COLS 10 + +int multi[ROWS][COLS]; + +int main(void) { + int row, col; + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + multi[row][col] = row * col; + } + } + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + printf("\n%d ", multi[row][col]); + printf("%d ", *(*(multi + row) + col)); + } + } + + return 0; +} \ No newline at end of file From d04a844fbea6c5f4e3704910124182c25428ddff Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 17:17:52 +0000 Subject: [PATCH 246/251] Including DCL Func Args. --- source/cprogramming/chapter5/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/source/cprogramming/chapter5/index.rst b/source/cprogramming/chapter5/index.rst index 6ed5cecb..3a05cf99 100644 --- a/source/cprogramming/chapter5/index.rst +++ b/source/cprogramming/chapter5/index.rst @@ -25,4 +25,5 @@ Chapter 5 ex_5.17_sortdfnr-withoption ex_5.18_dcl-errorec ex_5.19_undcl + ex_5.20_dcl-funcargs From 5721909010c93e83a1a13fd552971b6e9f8d902d Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 19:14:33 +0000 Subject: [PATCH 247/251] Example Output for Exercise 5.20 --- .../chapter5/cprogs/ex_5.20_dcl-funcargs.c | 432 +++++++++++------- .../chapter5/ex_5.20_dcl-funcargs.rst | 33 ++ 2 files changed, 300 insertions(+), 165 deletions(-) diff --git a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c index 333a27e8..3f59eb93 100644 --- a/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c +++ b/source/cprogramming/chapter5/cprogs/ex_5.20_dcl-funcargs.c @@ -1,201 +1,303 @@ /** - * Expand dcl to handle declarations with function argument types,qualifiers like const and so on + * Exercise 5-20. Expand dcl to handle declarations with function argument types, qualifiers like const, and so on. **/ -#include -#include -#include - -enum { NAME, PARENS, BRACKETS}; -enum { NO, YES }; +#include +#include +#include + +#define MAXTOKEN 500 +#define MAXOUTPUT 5000 // value must be <= 1.8 million to prevent a buffer overflow attack (when x = 99,999, y = 1,800,032 in y = 18x + 50) +#define BUFSIZE MAXTOKEN * 2 // * 2 because system might need to push back two tokens worth of chars +#define NUMOFSTORAGECLASSES 5 +#define NUMOFTYPEQUALIFIERS 4 +#define NUMOFTYPESPECIFIERS 11 + +enum tokentype { VARIABLE, BRACKETS, STORAGECLASS, TYPEQUALIFIER, TYPESPECIFIER }; +enum returnstatus { OK, ERROR }; +enum boolean { FALSE, TRUE }; + +int processDeclaration(char *declaration, char expectParameter); +int dcl(char *name, char *out, char expectParameter); +int dirdcl(char *name, char *out, char expectParameter); +int parameters(char *out); +int gettoken(void); +int getch(void); +void ungetch(int c); +int contains(char **strs, char *name, int strCount); +char *saferstrcat(char *dst, const char *str, size_t dstsize); +int error(char *msg); -void dcl(void); -void dirdcl(void); -void errmsg(char *); +int tokentype; +char token[MAXTOKEN]; +int buf[BUFSIZE]; +int bufp = 0; +static char *storageClasses[NUMOFSTORAGECLASSES] = { "_Thread_local", "auto", "extern", "register", "static" }; +static char *typeQualifiers[NUMOFTYPEQUALIFIERS] = { "_Atomic", "const", "restrict", "volatile" }; +static char *typeSpecifiers[NUMOFTYPESPECIFIERS] = { "_Bool", "_Complex", "char", "double", "float", "int", "long", "short", "signed", "unsigned", "void" }; -int gettoken(void); -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -extern char name[]; /* identifier name */ -extern char datatype[]; /* data type = char,int, etc */ -extern char out[]; -extern int prevtoken; -/* dcl: parse a declarator */ - -void dcl(void) +int main(void) { - int ns; - - for(ns = 0; gettoken() == '*'; ) /* count *'s */ - ns++; - dirdcl(); - while(ns-- > 0) - strcat(out,"pointer to"); + char out[MAXOUTPUT]; + while (gettoken() != EOF) + { + processDeclaration(out, FALSE); + for (int c = tokentype; c != '\n' && c != EOF; ) // discard rest of line since last token could be ';' or an error occurred + if ((c = getch()) == EOF) + break; + } + return 0; } -/* dirdcl: parse a direct declaration */ -void dirdcl(void) +int processDeclaration(char *declaration, char expectParameter) { - int type; - void parmdcl(void); - - if(tokentype == '(') /* (dcl) */ - { - dcl(); - if( tokentype != ')') - errmsg("error: missing ) \n"); - } - else if(tokentype == NAME) - { - if(name[0] == '\0') - strcpy(name,token); - } - else - prevtoken = YES; - - while((type = gettoken()) == PARENS || type == BRACKETS || type == '(') - if( type == PARENS) - strcat(out,"function returning"); - else if (type == '(') - { - strcat(out,"function expecting"); - parmdcl(); - strcat(out,"and returning"); - } - else - { - strcat(out,"array"); - strcat(out,token); - strcat(out,"of"); - } + char datatype[MAXTOKEN]; // stores type qualifier, specifier, and storage class info + char name[MAXTOKEN]; // stores function/variable name + char out[MAXOUTPUT]; // used to store information gathered by dcl/dirdcl to be used in the final output + datatype[0] = '\0'; // ensure null terminated + + if (!(tokentype == STORAGECLASS || tokentype == TYPEQUALIFIER || tokentype == TYPESPECIFIER)) + return error("Error: expected a type"); + while (tokentype == STORAGECLASS || tokentype == TYPEQUALIFIER || tokentype == TYPESPECIFIER) + { + if (saferstrcat(datatype, " ", MAXTOKEN) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(datatype, token, MAXTOKEN) == NULL) + return error("Error: input too large to fit into buffer"); + gettoken(); // get tokens until no longer a token for datatype + } + for (int i = strlen(token) - 1; i >= 0; i--) // since the while loop gets an extra unneeded token, push it back in reverse order + ungetch(token[i]); + do + { + out[0] = '\0'; // ensure new out string each loop iteration + if (dcl(name, out, expectParameter) == ERROR) // dcl updates out based on input + return ERROR; + else if (tokentype != ';' && tokentype != ',' && tokentype != ')' && tokentype != '\n') // if the returned output is not one of these chars, an error occurred + return error("Syntax error"); + else + { + if (strcmp(datatype, " void") == 0 && strncmp(out + (strlen(out) - 10), " returning", 10) == 0) + snprintf(datatype, MAXTOKEN, "%s", " nothing"); // if is function (has the word returning at the end) and it is returning only void, then improve readability by changing type to "nothing" + if (strcmp(name, " unnamed") == 0) // if name starts with a space, then it is the special flag set by dirdcl for an unnamed parameter + snprintf(name, MAXTOKEN, "%s", " unnamed parameter"); + if (expectParameter) + { + if (out[0] == ' ') // this improves the output formatting. It finds the first variable that starts with a space and replaces the space with a ( + out[0] = '('; + else if (datatype[0] == ' ') + datatype[0] = '('; + snprintf(declaration, MAXOUTPUT, "%s %s%s)", name, out, datatype); // store data in declaration which is used by parameters function + } + else // if not expecting parameters, then this was called by main. print out English version of the declaration + printf("%s:%s%s\n", name, out, datatype); + } + } while (!expectParameter && tokentype == ','); // loop is just in case received multiple comma separated declarations that aren't function parameters + return OK; } -/* errmsg: print error message and indicate avail. token */ -void errmsg(char *msg) +int dcl(char *name, char *out, char expectParameter) { - printf("%s",msg); - prevtoken = YES; + int numPointers = 0; + while (gettoken() == '*') // identify the number of back to back asterisks + numPointers++; + if (dirdcl(name, out, expectParameter) == ERROR) + return ERROR; + while (numPointers-- > 0) + if (saferstrcat(out, " pointer to", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + return OK; } - -/* The source file parmdcl.c */ - -#include -#include -#include -#include - -#define MAXTOKEN 100 - -void dcl(void); -void errmsg(char *); -void dclspec(void); -int compare(char **,char **); -int gettoken(void); -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -extern char name[]; /* identifier name */ -extern char datatype[]; /* data type = char, int etc */ -extern char out[]; -extern int prevtoken; - -/* parmdcl: parse a parameter declarator */ - -void parmdcl(void) +int dirdcl(char *name, char *out, char expectParameter) { - do - { - dclspec(); - }while ( tokentype == ','); - - if(tokentype != ')') - errmsg("missing ) in parameter declaration \n"); + if (tokentype == '(') // ( dcl ) + { + if (dcl(name, out, expectParameter) == ERROR) + return ERROR; + if (tokentype != ')') + return error("Error: missing )"); + } + else if (tokentype == VARIABLE) + snprintf(name, MAXTOKEN, "%s", token); + else if (expectParameter) // if tokentype is not VARIABLE and expecting a parameter, then it is an unnamed parameter + { + snprintf(name, MAXTOKEN, "%s", " unnamed"); // the space added is a flag indicates that this is an unnamed parameter instead of a named parameter called unnamed + expectParameter = FALSE; + for (int i = strlen(token) - 1; i >= 0; i--) + ungetch(token[i]); // push unused token back to input in reverse order + } + else + return error("Error: expected variable name or (dcl)"); + while (gettoken() == '(' || tokentype == BRACKETS) + { + if (tokentype == '(') + { + if (parameters(out) == ERROR) // found a function so parse its parameters + return ERROR; + } + else + { + if (saferstrcat(out, " array", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, token, MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, " of", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } + } + return OK; } -/* compare: compare two strings for bsearch */ - -int compare(char **s,char **t) +int parameters(char *out) { - return strcmp(*s,*t); + char declaration[MAXOUTPUT], expectParameter = TRUE; + int parameterCount = 0; + + if (gettoken() == ')') // previous token was '(' which means () was found, an old K&R style declaration + { + if (saferstrcat(out, " obsolescent non-prototype function declaration with unknown parameters returning", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + return OK; + } + else if (tokentype == TYPESPECIFIER && strcmp(token, "void") == 0) + { + if (gettoken() == ')') // this is true when the type is void and it is the only parameter + expectParameter = FALSE; + else if (tokentype == ',') // very basic check to see if void is used incorrectly. Too much work to do it properly + return error("Syntax error: functions either can have void * parameters or only a single void parameter"); + else // the parameter is not (void), but rather pointer(s) to void (e.g. void *, void **, etc) or it is (int, void), etc. + { + for (int i = strlen(token) - 1; i >= 0; i--) + ungetch(token[i]); // push unused token back to input in reverse order + tokentype = TYPESPECIFIER; // reset tokentype since not (void) + snprintf(token, MAXTOKEN, "%s", "void"); // reset token since not (void) + } + } + // the ##### is used for padding and will be changed later. 5 #'s are to prevent buffer overflows caused by an insanely large input that fits in an oversized buffer + if (saferstrcat(out, " function expecting ##### parameters:", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (expectParameter) + do + { + if (parameterCount++ > 0) // don't call gettoken the first time, but call it each time thereafter + gettoken(); + if (processDeclaration(declaration, expectParameter) == ERROR) + return ERROR; + if (strncmp(declaration, " unnamed parameter ", 19) != 0) // check if declaration starts with string + if (saferstrcat(out, " parameter ", MAXOUTPUT) == NULL) // if parameter has a name, prefix out first before adding the declaration part + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, declaration, MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } while (tokentype == ','); // get all comma separated parameters + if (tokentype == ')') // after getting parameters, next token should be ) + { + // this complicated mess is so I can replace the "##### parameters:" string with the parameterMessage in the final output + char parameterMessage[MAXTOKEN], *p1 = out, *p2 = parameterMessage; + while (*p1 != '#') // move to first #. this will run before another "##### parameters" is added for the same declaration + p1++; + if (parameterCount == 0) + snprintf(parameterMessage, MAXTOKEN, "no parameters"); + else if (parameterCount == 1) + snprintf(parameterMessage, MAXTOKEN, "1 parameter:"); + else + snprintf(parameterMessage, MAXTOKEN, "%d parameters:", parameterCount); + while (*p2 != '\0') // copy parameterMessage to out until '\0' is reached. Don't copy '\0' + *p1++ = *p2++; + for (p2 = p1; *p2++ != ':'; ) // point p2 to p1 and then move p2 to after "##### parameters:" + ; + while ((*p1++ = *p2++)) // copy after the : to the end of out to where p1 is pointing (the end of the parameterMessage in out) + ; + if (saferstrcat(out, " returning", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } + else + return error("Error: expected closing parentheses after parameters"); + return OK; } - - -/* typequal: return YES if token is a type-qualifier */ -int typequal(void) +int gettoken(void) { - static char *typeq[] = - { - "const", - "volatile" - }; - - char *pt = token; - - if(bsearch(&pt,typeq,sizeof(typeq)/sizeof(char *),sizeof(char *),(int *) compare) == NULL) - return NO; - else - return YES; + int c; + char *p = token; + + while ((c = getch()) == ' ' || c == '\t') // skip spaces and tabs + ; + if (c == '(') + { + *(p + 1) = '\0'; // terminate token string + return *p = tokentype = '(';; + } + else if (c == '[') // get [#####] and store in token + { + for (*p++ = c; (*p++ = getch()) != ']'; ) + ; + *p = '\0'; + return tokentype = BRACKETS; + } + else if (isalpha(c) || c == '_') // get name + { + for (*p++ = c; isalnum(c = getch()) || c == '_'; ) + *p++ = c; + *p = '\0'; + ungetch(c); // push back the unneeded extra char + if (contains(typeSpecifiers, token, NUMOFTYPESPECIFIERS)) + return tokentype = TYPESPECIFIER; + else if (contains(storageClasses, token, NUMOFSTORAGECLASSES)) + return tokentype = STORAGECLASS; + else if (contains(typeQualifiers, token, NUMOFTYPEQUALIFIERS)) + return tokentype = TYPEQUALIFIER; + return tokentype = VARIABLE; + } + + *(p + 1) = '\0'; // terminate token string + return *p = tokentype = c; // since not one of the types above, return char as the type and store it's value in the token } - - -/* typespec: return YES if token is a type-specifier */ -int typespec(void) +int getch(void) { - static char *types[] = - { - "char", - "int", - "void" - }; - - char *pt = token; + return (bufp > 0) ? buf[--bufp] : getchar(); +} - if(bsearch(&pt,types,sizeof(types)/sizeof(char *),sizeof(char *), (int *) compare) == NULL) - return NO; +void ungetch(int c) +{ + if (bufp >= BUFSIZE) + fprintf(stderr, "ungetch: too many characters\n"); else - return YES; + buf[bufp++] = c; } +int contains(char **strs, char *name, int strCount) +{ + for (int i = 0; i < strCount; i++) + if (strcmp(strs[i], name) == 0) + return TRUE; + return FALSE; +} -/* dclspec: declaration specification */ +// concatenates str to end of dst; requires null terminated strings and dst buffer size. Returns null if provided bad pointers or buffer is too small, otherwise returns pointer to dst +char *saferstrcat(char *dst, const char *str, size_t dstsize) +{ + if (dst == NULL || str == NULL) // if either pointer is NULL, return NULL + return NULL; + char *dstStart = dst; // keep track of the base of the string + size_t dstLen = strlen(dst), strLen = strlen(str); // calcuate the length of both strings once. Prevents the need to do constant checks in the loop + if (dstLen + strLen >= dstsize) // strlen doesn't count '\0', so if size == dstsize, then not enough space for the '\0' at the end + return NULL; // concatenating the strings would result in a buffer overflow. So return NULL instead + dst += dstLen; // move pointer to '\0' at end of string + while ((*dst++ = *str++)) // copy str to end of dst until str == '\0'. If str == "", the loop copies '\0' and terminates + ; + return dstStart; +} -void dclspec(void) +int error(char *msg) { - char temp[MAXTOKEN]; - - temp[0] = '\0'; - gettoken(); - - do - { - if(tokentype != NAME) - { - prevtoken = YES; - dcl(); - } - else if(typespec() == YES) - { - strcat(temp," "); - strcat(temp,token); - gettoken(); - } - else if(typequal() == YES) - { - strcat(temp," "); - strcat(temp,token); - gettoken(); - } - else - errmsg("unknown type in parameter list \n"); - }while (tokentype != ',' && tokentype != ')'); - - strcat(out,temp); - if(tokentype == ',') - strcat(out,","); + fprintf(stderr, "%s\n", msg); + return ERROR; } + + diff --git a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst index f3f730a9..a18df686 100644 --- a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst +++ b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst @@ -8,6 +8,8 @@ Question Expand dcl to handle declarations with function argument types, qualifiers like const, and so on. +The implementation of this program is from https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_5:Exercise_20 + .. literalinclude:: cprogs/ex_5.20_dcl-funcargs.c :language: c :tab-width: 4 @@ -20,4 +22,35 @@ This program is a simple parser that reads a C declaration, breaks down the C de a human readable representation of the declaration. It handles basic declaration syntax including pointers, functions, arrays and parameter declarations. +:: + + int simple; + simple: int + int dec, *larator, lists[]; + dec: int + larator: pointer to int + lists: array[] of int + static char *storage; + storage: pointer to static char + volatile int qualifier; + qualifier: volatile int + long unsigned int compound; + compound: long unsigned int + void arguments(char *name, double time); + arguments: function expecting 2 parameters: parameter name (pointer to char) parameter time (double) returning nothing + int nested_args(char *(*read)(void), void (*write)(char *message)); + nested_args: function expecting 2 parameters: parameter read (pointer to function expecting no parameters returning pointer to char) parameter write (pointer to function expecting 1 parameter: parameter message (pointer to char) returning nothing) returning int + void unnamed(char (*)(long)); + unnamed: function expecting 1 parameter: unnamed parameter (pointer to function expecting 1 parameter: unnamed parameter (long) returning char) returning nothing + static const long unsigned int (*book2)[13], *book3[13], complex(volatile char (*(*book6(void))[])(char **book1,void *book4(),void (*book5)()),char (*(*book7[3])())[5]); + book2: pointer to array[13] of static const long unsigned int + book3: array[13] of pointer to static const long unsigned int + complex: function expecting 2 parameters: parameter book6 (function expecting no parameters returning pointer to array[] of pointer to function expecting 3 parameters: parameter book1 (pointer to pointer to char) parameter book4 (obsolescent non-prototype function declaration with unknown parameters returning pointer to void) parameter book5 (pointer to obsolescent non-prototype function declaration with unknown parameters returning nothing) returning volatile char) parameter book7 (array[3] of pointer to obsolescent non-prototype function declaration with unknown parameters returning pointer to array[5] of char) returning static const long unsigned int + _Thread_local static int multipleStorageClassSpecifiers; + multipleStorageClassSpecifiers: _Thread_local static int + const volatile int multipleTypeQualifiers; + multipleTypeQualifiers: const volatile int + void everythingSupported(char a, signed char a, unsigned char a, short a, signed short a, short int a, signed short int a, unsigned short a, unsigned short int a, int a, signed a, signed int a, unsigned a, unsigned int a, long a, signed long a, long int a, signed long int a, unsigned long a, unsigned long int a, long long a, signed long long a, long long int a, signed long long int a, unsigned long long a, unsigned long long int a, float a, double a, long double a, _Bool a, float _Complex a, double _Complex a, long double _Complex a, _Atomic int a, const int a, restrict int a, volatile int a, _Thread_local int a, auto int a, extern int a, register int a, static int a); + everythingSupported: function expecting 42 parameters: parameter a (char) parameter a (signed char) parameter a (unsigned char) parameter a (short) parameter a (signed short) parameter a (short int) parameter a (signed short int) parameter a (unsigned short) parameter a (unsigned short int) parameter a (int) parameter a (signed) parameter a (signed int) parameter a (unsigned) parameter a (unsigned int) parameter a (long) parameter a (signed long) parameter a (long int) parameter a (signed long int) parameter a (unsigned long) parameter a (unsigned long int) parameter a (long long) parameter a (signed long long) parameter a (long long int) parameter a (signed long long int) parameter a (unsigned long long) parameter a (unsigned long long int) parameter a (float) parameter a (double) parameter a (long double) parameter a (_Bool) parameter a (float _Complex) parameter a (double _Complex) parameter a (long double _Complex) parameter a (_Atomic int) parameter a (const int) parameter a (restrict int) parameter a (volatile int) parameter a (_Thread_local int) parameter a (auto int) parameter a (extern int) parameter a (register int) parameter a (static int) returning nothing + From 75fd974fa06d32590ac0372af3a41848dc2a55c4 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 11:19:22 -0800 Subject: [PATCH 248/251] Uthcode logo transparent --- static/uthcode-logo-transparent.png | Bin 0 -> 15965 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 static/uthcode-logo-transparent.png diff --git a/static/uthcode-logo-transparent.png b/static/uthcode-logo-transparent.png new file mode 100644 index 0000000000000000000000000000000000000000..9e3c6402e8aea7296d8ee90fb12f143b1d33b2c0 GIT binary patch literal 15965 zcmV-jKBB>iP)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv0RI600RN!9r;`8x z00(qQO+^Rj3;`1m7z{x!1poj&(@8`@RCwC$y?2}>XL;}YeJggHnVvkmlXkU1yDROk zRuM2JT13m(*uWte{J~t~i+z00@jchR_Z(jv+XrlHbBw`&x!{1!wXuE32rxlNC?KH# zl2#JZ<~%z)xnrgG{83%i)oG@C!p_R--)wJpS9Mjr_15!ypYT5K`wA%~9dyt^VAnuGOjHp> zO35=bkIIKH+!cP8Qi7Do%8$a&g2oRx+%AGo<#!8pV%UV5Gaa*l#<|c2hR@FX^@A`-^rie_Ztm=TuX@R7O*1tfsl)`@GC+o ze^-0~K|u&5+^&eqcmJgk*AisngN%3YWP8s(#!@@!OAMi_It9DHrQ$hGEV$l<*y> zB1{KYE*khCjURk7Z4vB^{w_+6kTk;o9PF!nj*vwt2oy9$!%$uu5pgo%EK8ls3moD~$Iq6igD(TVFx zQf3d`W*=#@hlHL&RWvk36P7H>ZnKY+(M?QCpa~sCsHnojm40~6!$S!FlR!a8j|yoe zNKw`Vf^gF+3DF3JVu5@=#LDWdv!ittIGpoD&eAfiQxw*I2}bHwF{#_CpED`g)9Aq1MHg_*;$0 zuxyJ`sf4Pk7>0rCy11?@J!RE{sZ`xWg|qp70WX!)}?zRz|Mkizr4D$}Z?J)S+NCrE?m){-z$-4ZwQMXH50 z+*0LF5RGVs1PhL@xuOsa&9cVYNmNKvqm`=4(*`M4s+X`=ze9#+E!LRx&`t|0s@_9$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AE= z)kS+Y8meP5cFY6G5b(yqbGZ1ywBQ0BHV3w+4XgbeZ zdLFwMuI7P-`}uO$mw6`f%(FHetf(rgtSm{U>pEM8MtQgLKKh^7$~Wi!9t(fGN2`eb z(kP@DK6)d4`E87jjd9&|*RgNkJ~Eliieo_5f+$Iar;?l-X86SQ^f1iU$*mkXaF7EB z_HT+7i{e>DkN{Cl5*?VOs;bm94NccEOoNx@Ud9cxH}K@_liZp7E)S+3Vo6_oR%sPY z)%=;~%RSnPqF|b)m>8Ylt@>}uEsyQyYtw(tS>=hgMye~WM)%Y<2G1Oz#~5IA`zQwv z9N?O3u3>0sNR(%)*)T{1s-u&>G)B+#Rdg4&km>Gae0-d}d-rkm)w>xS9Nh47tXTh> zdi7PJb}W3vKM|Uy$)E=~9*+}`$LTI~b8Y@wvNKr@>xX$P{wPNiN0~CGSkxESJ%xTf zVHgH6{G`nqk}xqbAzp3%yxj5hwfx}NUHmYA2N%_&RlF1~gRH}*`u~;n3a0cJ0v@DCo#YH(YGs~q* z)6C7yv9z>AsZm?wF zVHm{YaT19{cu$E$BGiy8p;Rg{H8myAojXT9zy5t+@pzn(kr9T6hyQ&LBtTS~1Z1&o zI~ZdkgHekCDFPBTB1d#Ry~|lg!IZASxc$IXOeT}W<8cv;kqO54*WSPDx>%M)u~@{i zENRtOq=OEYL5Cn6bg&FM1nHoIWzZo=2OTVf4naETU>W=`!s~DwdktF=00000 LNkvXXu0mjfW{(7u literal 0 HcmV?d00001 From 9290c84ddcdc4943e574555d4b63844eff6194d6 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 19:21:00 +0000 Subject: [PATCH 249/251] Updated to transparent logo. --- README.md | 9 --------- source/conf.py | 2 +- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/README.md b/README.md index 9d1b3bd9..7acf7011 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,6 @@ [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. -To practice the exercises, you can use the online compilers like - -* [https://www.tutorialspoint.com/compile_c_online.php](https://www.tutorialspoint.com/compile_c_online.php) -* [https://replit.com/](https://replit.com/) -* [https://www.jdoodle.com/c-online-compiler](https://www.jdoodle.com/c-online-compiler) -* [https://www.onlinegdb.com/online_c_compiler](https://www.onlinegdb.com/online_c_compiler) -* [https://www.codechef.com/ide](https://www.codechef.com/ide) -* [https://www.programiz.com/c-programming/online-compiler/](https://www.programiz.com/c-programming/online-compiler/). - 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. diff --git a/source/conf.py b/source/conf.py index a7f2d269..fe5ef092 100644 --- a/source/conf.py +++ b/source/conf.py @@ -91,7 +91,7 @@ # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", - logo = "uthcode.png", + logo = "uthcode-logo-transparent.png", logo_alt = "", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/", logo_height = 59, From b06044d289d23a718108504e8223d3296868819f Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 19:22:59 +0000 Subject: [PATCH 250/251] updated static file location --- source/_static/uthcode-logo-transparent.png | Bin 0 -> 15965 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 source/_static/uthcode-logo-transparent.png diff --git a/source/_static/uthcode-logo-transparent.png b/source/_static/uthcode-logo-transparent.png new file mode 100644 index 0000000000000000000000000000000000000000..9e3c6402e8aea7296d8ee90fb12f143b1d33b2c0 GIT binary patch literal 15965 zcmV-jKBB>iP)004R> z004l5008;`004mK004C`008P>0026e000+ooVrmw00006VoOIv0RI600RN!9r;`8x z00(qQO+^Rj3;`1m7z{x!1poj&(@8`@RCwC$y?2}>XL;}YeJggHnVvkmlXkU1yDROk zRuM2JT13m(*uWte{J~t~i+z00@jchR_Z(jv+XrlHbBw`&x!{1!wXuE32rxlNC?KH# zl2#JZ<~%z)xnrgG{83%i)oG@C!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qk}xqbAzp3%yxj5hwfx}NUHmYA2N%_&RlF1~gRH}*`u~;n3a0cJ0v@DCo#YH(YGs~q* z)6C7yv9z>AsZm?wF zVHm{YaT19{cu$E$BGiy8p;Rg{H8myAojXT9zy5t+@pzn(kr9T6hyQ&LBtTS~1Z1&o zI~ZdkgHekCDFPBTB1d#Ry~|lg!IZASxc$IXOeT}W<8cv;kqO54*WSPDx>%M)u~@{i zENRtOq=OEYL5Cn6bg&FM1nHoIWzZo=2OTVf4naETU>W=`!s~DwdktF=00000 LNkvXXu0mjfW{(7u literal 0 HcmV?d00001 From 0c8df15ac26467ab2e831303d75cb960a7a9a246 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Sun, 1 Dec 2024 19:27:36 +0000 Subject: [PATCH 251/251] non transparent looks better. --- source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/conf.py b/source/conf.py index fe5ef092..a7f2d269 100644 --- a/source/conf.py +++ b/source/conf.py @@ -91,7 +91,7 @@ # These are options specifically for the Wagtail Theme. html_theme_options = dict( project_name ="Learn To Solve It", - logo = "uthcode-logo-transparent.png", + logo = "uthcode.png", logo_alt = "", github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/", logo_height = 59,