filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/languages/Java/README_reduce_TL.md | Hey Folks! Being in the world of competitive programming, every one of us often face TLE (Time Limit Exceeded) Errors. Reducing TL of one's code is one of the most crucial phase of learning for programmers.
One of the most popular platform for competetive programming is **codechef**.
By-default : Codechef has the TL (Time Limit) for any problem as 1 sec. Java Language has a multiplier of 2 and phython has multiplier of 5.
[Java](https://iq.opengenus.org/tag/java/) being a heavy language, does uses extra space and time for loading the framework into code-cache along with the main program. But its not the memory issue, one generally faces but TLE.
So, one of the most common way of reducing TL of one's code is to use **fast input and otput methods**. This really helps. Java is also called a slow language because of its slow input and output. So, many a times, just by adding fast input output to their program and without making any changes in their logic, coders are able to get AC (ALL CORRECT).
Most problem setters explicitly reduce TL and multipliers of their problem so as to force users to learn and use fast input output methods.
Moreover, we often encounter problem statements saying: *"Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”*. This is a direct hint given to users to use Faster I/O techniques.
So, this is covered in a greater detail in this article.
Link to the article: https://iq.opengenus.org/reduce-time-limit-of-java-code/ |
code/languages/Java/Readme.md | An **Array List** is a dynamic version of array. It is similar to Dynamic Array class where we do not need to predefine the size. The size of array list grows automatically as we keep on adding elements. In this article, we will focus on 2D array list in Java.
In short, it is defined as:
```java
ArrayList<ArrayList<Integer> > arrLL = new ArrayList<ArrayList<Integer> >();
```
There are mainly two common variations of Array Lists, namely:
- 1-D Array Lists (or commonly called Array Lists)
- Multidimensional Array Lists
The most common and the simplest form of Multidimensional Array Lists used is **2-D Array Lists**. In this article, we'll dive deeper into it, studying about its implementation, advantages and disadvantages.
Link to the article : https://iq.opengenus.org/2d-array-list-java/
|
code/languages/Java/Reduce_Time_complexity.java | //Scanner class
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}
// Reader class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
Reader s = new Reader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
} |
code/languages/Java/String/Readme.md | #Java String Class
Used to perform various Operations on String.
Link to my Article = https://iq.opengenus.org/java-lang-string-class/ |
code/languages/Java/String/StringClass.java | class Cosmos {
public static void main(String[] args)
{
// 1st Example
String str1 = "CoSmOs";
String str2 = str1.toLowerCase();// Convert to lower case Characters
System.out.println(str2);
//2nd Example
String str3 = " Cosmos ";
String str4 = str3.trim();// "Cosmos" is stored in str4
System.out.println(str4);
}
} |
code/languages/Java/bubble-sort.java | // Building Bubble Sort for both strings and integer arrays
class bubble_sort {
public static void bubble_sort_int(int[] arr1) {
int i, j;
boolean areSwapped;
// Loops through to sort the array
for (i = 0; i < arr1.length - 1; i++) {
areSwapped = false;
for (j = 0; j < arr1.length - i - 1; j++) {
if (arr1[j] > arr1[j+1]) {
// swaps the two numbers if they are out of order
int temp = arr1[j];
arr1[j] = arr1[j+1];
arr1[j+1] = temp;
areSwapped = true;
}
}
// ends the algorithm if it is in sorted order
if (areSwapped == false) {
break;
}
}
}
public static void bubble_sort_string(String[] arr1) {
int i, j;
boolean areSwapped;
// Loops through to sort the array
for (i = 0; i < arr1.length; i++) {
areSwapped = false;
for (j = 0; j < arr1.length - i - 1; j++) {
// case doesn't matter for sorting, so we don't want an error
String atJ = arr1[j].toLowerCase();
String atJ1 = arr1[j+1].toLowerCase();
if (atJ.compareTo(atJ1) > 0) {
// swaps the two strings if they are out of order
String temp = arr1[j];
arr1[j] = arr1[j+1];
arr1[j+1] = temp;
areSwapped = true;
}
}
// ends the algorithm if it is in sorted order
if (areSwapped == false) {
break;
}
}
}
public static void intTester() {
// Tests the integer array sort function
int[] check = {3, 1, 4, 2, 43, 7, 9, 13, 0, 2, -1};
int i;
System.out.println("Before: ");
for (i = 0; i < check.length; i++) {
System.out.print(check[i] + " ");
}
bubble_sort_int(check);
System.out.println("\nAfter: ");
for (i = 0; i < check.length; i++) {
System.out.print(check[i] + " ");
}
}
public static void stringTester() {
// Tests the string array sort function
String[] check = {"Hi", "Bye", "Byex", "Alex", "Ale", "My", "Friend", "q", "Z"};
System.out.println("Before: ");
int i;
for (i = 0; i < check.length; i++) {
System.out.print(check[i] + " ");
}
bubble_sort_string(check);
System.out.println("\nAfter: ");
for (i = 0; i < check.length; i++) {
System.out.print(check[i] + " ");
}
}
public static void main(String[] args) {
// Runs the functions
intTester();
System.out.println();
stringTester();
System.out.println();
}
} |
code/languages/Java/readme-2DArray.md | An **Array** is a continuous memory allocation of the group of like-typed variables that are referred to by a common name. In this article, we have focused on **2D array in Java** which is a variant of the usual 1D array by introducing a new dimension.
In short, it is defined as:
```java
int[][] arr = new int[10][20];
```
There are mainly two common variations of Arrays, namely :
- 1-D Array (or commonly called Array)
- Multidimensional Arrays
2-D Array is the simplest form of a Multidimensional array. Now, we are going to explore 2-D arrays in a greater detail.
Link to the article : https://iq.opengenus.org/2d-arrays-in-java/ |
code/languages/Java/this_reference/Readme.md | # 'this' reference in Java
this is an Object which holds the Reference of another Object which invokes the member function.
Link to the article : https://iq.opengenus.org/use-of-this-in-java/
|
code/languages/Java/this_reference/this.java | //Code to show 'this' reference in Java
class Cosmos
{
int a;
int b;
// Parameterized constructor
Cosmos(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Cosmos object = new Cosmos(60, 100);
object.display();
}
}
|
code/languages/c#/BasicDataTypes.cs | using System;
/* This code demonstrates the various basic data types that C# provides */
// Char is used to store a character.
char character = 'K'; // Note we have to single quotes.
Console.WriteLine(character); // Outputs: K
// Strings are used to store text
string message = "Hello there!";
Console.WriteLine(message); // Outputs: Hello there!
// int represents integer numbers (no fractions).
int integer = 16;
Console.WriteLine(integer); // Outputs: 16
// float is a floating point number
float floatNumber = 15.254f; // Note that we use f here.
float anotherFloatNumber = 14.365F; // F is also acceptable.
Console.WriteLine(floatNumber); // Outputs: 15.254
// double is used for greater precision (more decimal places can be stored.)
double doubleNumber = 12.8888446d; // Note that we use d here.
double anotherDoubleNumber = 15.447893323D; // D is also acceptable.
Console.WriteLine(anotherDoubleNumber); // Outputs: 15.447893323
// decimal is typically only used for monetary transactions and provides
// the greatest precision.
decimal decimalNumber = 12.65m; // Note that we use m here.
decimal anotherDecimalNumber = 19.19M; // M is also acceptable.
Console.WriteLine(decimalNumber); // Outputs: 12.65
|
code/languages/c#/ForLoop.cs | using System;
/* This explains and will show a demonstration behind for loops in C#.
The format of a for loop is as follows:
for (int i = 0; i < 5; i++)
{
DoSomething();
}
The first part of the for loop is the initializer. This is only executed once and only once before
the rest of the statements are ran.
int i = 0;
Here, we set the variable i to 0. This variable is often referred to as the indexer.
Next, there is a termination condition. This condition, once false, will stop going through the loop.
i < 5;
In our example, as long as i is less than 5, the for loop will continue to execute.
Finally, the last statement is what is executed at the end of the loop. This will almost always be
an incrementing/decrementing statement.
i++
With our example, we increase i by 1 each time the loop is executed.
The body of the loop will execute if it passes the terminating conditional (running the theoretical
DoSomething method), then will run the third statement of the for loop (in our case i++), and
continue through the loop in this process until the terminating statement is no longer true.
So, knowing this, we can discern the loop will run 5 times. The first time the loop is executed,
i = 0. After the loop is executed the first time, i = 1. This repeats until i = 5, at which the loop
is terminated.
*/
// Counts from 1 to 100
for (int i = 1; i <= 100; i++)
{
Console.WriteLine(i); // This will print the value of i.
} |
code/languages/c#/IfElseIfElse.cs | using System;
/* This demonstrates the use of if/else if/else flow conditionals.
Why do we use these?
Simple! It's a way to 'make a decision' and have code based on that decision execute. An example
would be if you wanted to check if the user's age is under 21, you want to print an error message.
With if/else if/else statements, this is possible!
Let's look at some examples.
*/
Console.Write("Enter your age: ");
int age = Console.ReadLine();
// Here, we will check if the age is less than 21
if (age < 21)
{
Console.WriteLine("You are too young to access this!"); // This executes if age is less than 21.
}
// Note we do not need an else if/else; these are optional. Let's see an if/else in action!
if (age < 21)
{
Console.WriteLine("You are too young to access this!"); // This executes if age is less than 21.
}
else
{
Console.WriteLine("Welcome to the storefront."); // This will execute if age is above 20.
}
// Finally, we can use as many 'else if' statements as we want, as shown here
if (age < 21)
{
Console.WriteLine("You are too young to access this!"); // This executes if age is less than 21.
}
// These else if statements are then checked in the order they appear.
else if (age > 20 && age < 30)
{
Console.WriteLine("Enjoy your 20's!"); // This executes when the age is between 21 and 29
}
else if (age >= 65)
{
Console.WriteLine("You get a senior citizen discount!"); // This executes if age is at least 65.
}
// This will only execute if none of the other checks trigger.
else
{
Console.WriteLine("Welcome to the storefront.");
}
|
code/languages/c/README.md | # Introduction to C
C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, and it has therefore found lasting use in applications that were previously coded in assembly language. Such applications include operating systems, as well as various application software for computers ranging from supercomputers to embedded systems. **It is a Turing-Complete Language**
## Overview
Like most imperative languages in the ALGOL tradition, C has facilities for structured programming and allows lexical variable scope and recursion. Its static type system prevents unintended operations. In C, all executable code is contained within subroutines(also called "functions", though not strictly the same as in the sense of functional programming). Function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing pointer values. C program source text is free-format, using the semicolon as a statement terminator and curly braces for grouping blocks of statements.
### The C language also exhibits the following characteristics:
* There is a small, fixed number of keywords, including a full set of control flow primitives: for, if/else, while, switch, and do/while. User-defined names are not distinguished from keywords by any kind of sigil.
* There are a large number of arithmetic and logic operators: +, +=, ++, &, ~, etc.
* More than one assignment may be performed in a single statement.
* Function return values can be ignored when not needed.
* Typing is static, but weakly enforced; all data has a type, but implicit conversions are possible.
* Declaration syntax mimics usage context. C has no "define" keyword; instead, a statement beginning with the name of a type is taken as a declaration. There is no "function" keyword; instead, a function is indicated by the parentheses of an argument list.
* User-defined (typedef) and compound types are possible.
* Union is a structure with overlapping members; only the last member stored is valid.
* Array indexing is a secondary notation, defined in terms of pointer arithmetic. Unlike structs, arrays are not first-class objects: they cannot be assigned or compared using single built-in operators. There is no "array" keyword in use or definition; instead, square brackets indicate arrays syntactically, for example month[11].
* Strings are not a distinct data type, but are conventionally implemented as null-terminated character arrays.
* While C does not include certain features found in other languages (such as object orientation and garbage collection), these can be implemented or emulated, often through the use of external libraries (e.g., the GLib Object System or the Boehm garbage collector).
### Historical Background
The origin of C is closely tied to the development of the Unix operating system, originally implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson, incorporating several ideas from colleagues. Eventually,
In 1972, Ritchie started to improve B, which resulted in creating a new language C. C compiler and some utilities made by C were included in Version 2 Unix. At Version 4 Unix released at Nov. 1973, the Unix kernel was extensively re-implemented by C. By this time, the C language had acquired some powerful features such as struct types.
| Year | Version |
| ------------- |:-------------:|
| 1972 | Birth |
| 1978 | K&R C |
| 1989/1990 |ANSI C and ISO C |
| 1999|C 99 |
| 2011 |C 11 |
| 2017/2018 |C 18 |
### Hello World Program
``` c
#include <stdio.h>
int main(void)
{
printf("hello, world\n");
}
```
The first line of the program contains a preprocessing directive, indicated by **#include**. This causes the compiler to replace that line with the entire text of the stdio.h standard header, which contains declarations for standard input and output functions such as printf. The angle brackets surrounding stdio.h indicate that stdio.h is located using a search strategy that prefers headers provided with the compiler to other headers having the same name, as opposed to double quotes which typically include local or project-specific header files.
The next line indicates that a function named main is being defined. The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution. The type specifier int indicates that the value that is returned to the invoker (in this case the run-time environment) as a result of evaluating the main function, is an integer. The keyword void as a parameter list indicates that this function takes no arguments.
The opening curly brace indicates the beginning of the definition of the main function.
The next line calls (diverts execution to) a function named printf, which in this case is supplied from a system library. In this call, the printf function is passed (provided with) a single argument, the address of the first character in the string literal "hello, world\n". The string literal is an unnamed array with elements of type char, set up automatically by the compiler with a final 0-valued character to mark the end of the array (printf needs to know this). The \n is an escape sequence that C translates to a newline character, which on output signifies the end of the current line. The return value of the printf function is of type int, but it is silently discarded since it is not used. (A more careful program might test the return value to determine whether or not the printf function succeeded.) The semicolon ; terminates the statement.
The closing curly brace indicates the end of the code for the main function. According to the C99 specification and newer, the main function, unlike any other function, will implicitly return a value of 0 upon reaching the } that terminates the function. (Formerly an explicit return 0; statement was required.) This is interpreted by the run-time system as an exit code indicating successful execution.
**Source - Wikipedia, Programming in ANSI C- E Balagurusamy.**
|
code/languages/c/delete_array/README.md | Deletion of an array means that we need to deallocate the memory that was allocated to the array so that it can be used for other purposes.
Arrays occupy a lot of our memory space. Hence, to free up the memory at the end of the program, we must remove/deallocate the memory bytes used by the array to prevent wastage of memory.
If the array is declared statically, then we do not need to delete an array since it gets deleted by the end of the program/block in which it was declared.
But if the array is declared dynamically, i.e. using malloc/calloc, then we need to free up the memory space used up by them by the end of the program for the program to not crash down. It can be done by calling the free method and passing the array.
When we allocate memory dynamically, some part of information is stored before or after the allocated block. free uses this information to know how memory was allocated and then frees up the whole block of memory.
However, if we allocate memory for each array element, then we need to free each element before deleting the array.
Link to the article: https://iq.opengenus.org/delete-vs-free-in-cpp/
|
code/languages/c/delete_array/del.c | int *a=malloc(10*sizeof(int)); //allocating memory to an array
free(a); //freeing the array pointer
char ** a = malloc(10*sizeof(char*));
for(int i=0; i < 10; i++)
{
a[i] = malloc(i+1); //allocating memory for each array element
}
for (int i=0; i < 10; i++)
{
free(a[i]); //freeing each element before deleting the array.
}
free(a); //freeing the array pointer
|
code/languages/c/dynamic_memory_allocation/README.md | ## Dynamic memory allocation
The C programming language manages memory statically, automatically, or dynamically. Static-duration variables are allocated in main memory, usually along with the executable code of the program, and persist for the lifetime of the program; automatic-duration variables are allocated on the stack and come and go as functions are called and return. For static-duration and automatic-duration variables, the size of the allocation must be compile-time constant (except for the case of variable-length automatic arrays[5]). If the required size is not known until run-time (for example, if data of arbitrary size is being read from the user or from a disk file), then using fixed-size data objects is inadequate.
The lifetime of allocated memory can also cause concern. Neither static- nor automatic-duration memory is adequate for all situations. Automatic-allocated data cannot persist across multiple function calls, while static data persists for the life of the program whether it is needed or not. In many situations the programmer requires greater flexibility in managing the lifetime of allocated memory.
These limitations are avoided by using dynamic memory allocation in which ```memory``` is more explicitly (but more flexibly) managed, typically, by allocating it from the free store (informally called the "heap"), an area of memory structured for this purpose. In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to ```free``` which deallocates the memory so that it can be used for other purposes.
### Types of Functions
* malloc allocates the specified number of bytes
* realloc increases or decreases the size of the specified block of memory, moving it if necessary
* calloc allocates the specified number of bytes and initializes them to zero
* free releases the specified block of memory back to the system
### Function Prototype
* **malloc**
Syntax
ptr = (cast-type*) malloc(byte-size);
For Example:
ptr = (int*) malloc(100 * sizeof(int));
* **calloc**
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
* **realloc**
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
* **free**
Syntax:
free(ptr);
### Sample code for malloc
``` C
void foo(int n, int m) {
int i, *p;
/* Allocate a block of n ints */
p = (int *) malloc(n * sizeof(int));
if (p == NULL) {
perror("malloc");
exit(0);
}
/* Initialize allocated block */
for (i=0; i<n; i++)
p[i] = i;
/* Return p to the heap */
free(p);
}
```
### Sample code for realloc
```C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[2], i;
int *ptr = arr;
int *ptr_new;
arr[0] = 10;
arr[1] = 20;
// incorrect use of new_ptr: undefined behaviour
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
getchar();
return 0;
}
```
### Sample code for calloc
``` C
#include <stdio.h>
#include <stdlib.h>
int main () {
int i, n;
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ ) {
printf("%d ",a[i]);
}
free( a );
return(0);
}
```
|
code/languages/c/dynamic_memory_allocation/example.c | #include <stdio.h>
#include <stdlib.h>
#define NULL 0
int
main()
{
char *buffer;
/* Allocation memory */
if (buffer = (char *)malloc(10)) == NULL) {
printf ("malloc failed.\n");
exit (1);
} printf ("Buffer of size %d created \n", _msize(buffer));
strcpy (buffer, "HYDERABAD");
printf ("\nBuffer contains: %s \n", buffer);
/* Reallocation */
if ((buffer = (char *)realloc(buffer, 15)) == NULL) {
printf ("Reallocation failed. \n")
exit (1);
} printf ("\nBuffer size modified. \n");
printf ("\nBuffer still contains: %s \n", buffer);
strcpy (buffer, "SECUNDERABAD");
printf ("\nBuffer now contains: %s \n", buffer);
/* Freeing memory */
free (buffer);
} |
code/languages/c/linear_search/linear_search.c | #include <stdio.h>
#include <stdlib.h>
/*
Input : integer array indexed from 0, key to be searched
Ouput : Position of the key in the array if found, else -1
*/
int linearSearch(int a[], int n, int key) {
int pos = -1;
counter=0;
for (int i = 0; i < n; ++i) {
if (a[i] == key) {
pos = i;
break;
}
}
return pos;
}
int main() {
int a[] = {8, 12, 3, 4, 7, 2, 13};
int n = sizeof(a) / sizeof(a[0]);
int pos = linearSearch(a, n, 13);
if (pos != 1)
printf("Key found at position : %d \n", pos);
else
printf("Key not found \n");
return 0;
}
/*
Output :
Key found at position : 2
*/
|
code/languages/c/linear_search/linear_search_duplicates.c | #include <stdio.h>
#include <stdlib.h>
/*
Input : integer array indexed from 0, key to be searched
Ouput : Position(s) of the key in the array if found, else prints nothing
*/
int *linearSearch(int a[], int result[], int n, int key) {
int pos = -1, ind = 0;
for (int i = 0; i < n; ++i) {
if (a[i] == key) {
result[ind++] = i; // store the index of key, if found
} else
result[ind++] = -1; // store -1 if key not found
}
return result;
}
int main() {
int a[] = {8, 12, 3, 4, 4, 7, 2, 3, 13, 17, 3};
int n = sizeof(a) / sizeof(a[0]);
int result[n];
linearSearch(a, result, n, 3);
int size = sizeof(result) / sizeof(result[0]);
printf("Key found at position(s) : \n");
for (int i = 0; i < size; i++) {
if (result[i] != -1)
printf("%d \n", result[i]);
}
return 0;
}
/*
Output :
Key found at position(s) :
2
7
10
*/
|
code/languages/c/linear_search/linear_search_duplicates_linked_list.c | #include <stdio.h>
#include <stdlib.h>
/*
Input : integer linked list , key to be searched
Ouput : Position(s) of the key in the linked list if found, else print nothing
*/
struct node {
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insert(int pos, int x) {
struct node *temp = malloc(sizeof(struct node));
if (temp == NULL)
printf("Insertion not possible\n");
temp->data = x; // storing the value in data field
if (pos == 1) {
temp->nptr = hptr;
hptr = temp;
} else {
int i = 1;
struct node *thptr = hptr; // temporary pointer
while (i < pos - 1) {
thptr = thptr->nptr; // traversing to the position of insertion
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
void print() {
struct node *temp = hptr;
printf("Linked List contains : \n");
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->nptr;
}
}
int ind;
int *linearSearch(int key, int result[]) {
struct node *temp = hptr;
int i = 1;
ind = 0;
while (temp != NULL) {
if (temp->data == key) {
result[ind++] = i;
} else {
result[ind] = -1;
ind++;
}
i++;
temp = temp->nptr;
}
return result;
}
int main() {
int result[10];
insert(1, 11);
insert(2, 6);
insert(3, 12);
insert(4, 14);
insert(5, 6);
insert(6, 10);
insert(7, 6);
print();
printf("Position(s) of the key is : \n");
linearSearch(6, result);
for (int i = 0; i < ind; i++) {
if (result[i] != -1)
printf("%d \n", result[i]);
}
return 0;
}
/*Output
Linked List contains :
11
6
12
14
6
10
6
Position(s) of the key is :
2
5
7
*/
|
code/languages/c/linear_search/linear_search_linked_list.c | #include <stdio.h>
#include <stdlib.h>
/*
Input : integer linked list , key to be searched
Ouput : Position of the key in the linked list if found, else -1
*/
struct node {
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insert(int pos, int x) {
struct node *temp = malloc(sizeof(struct node));
if (temp == NULL)
printf("Insertion not possible\n");
temp->data = x; // storing the value in data field
if (pos == 1) {
temp->nptr = hptr;
hptr = temp;
} else {
int i = 1;
struct node *thptr = hptr; // temporary pointer
while (i < pos - 1) {
thptr = thptr->nptr; // traversing to the position of insertion
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
void print() {
struct node *temp = hptr;
printf("Linked List contains : \n");
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->nptr;
}
}
int linearSearch(int key) {
struct node *temp = hptr;
int i = 1;
while (temp != NULL) {
if (temp->data == key)
return i;
i++;
temp = temp->nptr;
}
return -1;
}
int main() {
insert(1, 11);
insert(2, 13);
insert(3, 12);
insert(4, 14);
insert(5, 6);
insert(6, 10);
print();
printf("Position of the key is : %d\n", linearSearch(6));
return 0;
}
/*Output
Linked List contains :
11
13
12
14
6
10
Position of the key is : 5
*/
|
code/languages/c/loop/While.c | /*A while loop in C programming repeatedly executes a target statement as long as a given condition is true.*/
/*It is an entry controlled loop i.e. a test condition is checked and only if it evaluates to true, is the body of the loop executed.*/
#include <stdio.h>
int
main()
{
int n = 1, times = 5; /*local variable initialization*/
while (n <= times) /*while loops execution*/
{
printf("C while loops: %d\n", n);
++n;
}
return (0);
}
/*output:*/
/*C while loops:1*/
/*C while loops:2*/
/*C while loops:3*/
/*C while loops:4*/
/*C while loops:5*/
|
code/languages/c/loop/break.c | #include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num);
if (num==2)
{
/*
Break statement stops the execution of the loop when num = 2.
Hence, the program exits the while loop even when the condition (in while statement) is true.
*/
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
/*
value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop
*/
|
code/languages/c/loop/continue.c | #include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==5)
{
/* The continue statement is encountered when
* the value of j is equal to 4.
*/
continue;
}
/* This print statement would not execute for the
* loop iteration where j ==4 because in that case
* this statement would be skipped.
*/
printf("%d ", j);
}
return 0;
}
/*
0 1 2 3 4 6 7 8
*/
|
code/languages/c/loop/do-while.c | /* do-while loop*/
/*C program to print sum of first 5 natural numbers using do..while loop*/
/*do- while loop is a loop for performing repetitive tasks. In this loop the body of the loop is executed*/
/*atleast once, and then the test condition is checked. If it evaluates to true, the loop continues to run otherwise it is exited.*/
#include <stdio.h>
int
main()
{
int sum = 0, i = 1; /*initialization of counter variable i*/
do {
sum += i;
++i; /*increment of counter variable*/
} while (i <= 5); /*condition of do while*/
printf("sum of first 5 natural numbers = %d", sum);
return (0);
} /*end of program*/
/*output:*/
/*sum of first 5 natural numbers = 15*/
|
code/languages/c/loop/for.c | #include <stdio.h>
int main()
{
int i;
for (i=1; i<=5 i++)
{
printf("%d\n", i);
}
return 0;
}
/*
1
2
3
4
5
*/
|
code/languages/c/loop/switch-case.c | #include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case2: Value is: %d", num);
case 3:
printf("Case3: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
/*
Default: value is: 2
*/
|
code/languages/c/rock_paper_scissor/rock_game.c | // Part of Cosmos by OpenGenus
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generaterandomfunc(int n)
{
srand(time(NULL));
return rand() % n;
}
int greater(char char1, char char2)
{
// return 1 if c1>c2 and 0 otherwise . if c1==c2 it will return -1
if (char1 == char2)
{
return -1;
}
else if ((char1 == 'r') && (char2 == 's'))
{
return 1;
}
else if ((char2 == 'r' && char1 == 's'))
{
return 0;
}
else if ((char1 == 'p') && (char2 == 'r'))
{
return 1;
}
else if ((char2 == 'p') && (char1 == 'r'))
{
return 0;
}
else if ((char1 == 's') && (char2 == 'p'))
{
return 1;
}
else if ((char2 == 's') && (char1 == 'p'))
{
return 0;
}
}
int main()
{
int playerscore = 0, compscore = 0, temp;
char playerchar, compchar;
char dict[45] = {'r', 'p', 's'};
printf("welcome to the rock paper scissor game\n");
for (int i = 0; i < 3; i++)
{
printf("choose 1 for rock choose 2 for paper choose 3 for scissor \n");
printf("player no.1 turn \n");
scanf("%d", &temp);
playerchar = dict[temp - 1];
printf("you choose %c\n", playerchar);
printf("choose 1 for rock choose 2 for paper choose 3 for scissor \n");
printf("player no.1 turn \n");
temp = generaterandomfunc(3) + 1;
compchar = dict[temp - 1];
printf("cpu choose %c\n", compchar);
if (greater(compchar, playerchar) == 1) //compchar is greater than player char
{
compscore += 1;
printf("cpu got it hurray\n");
}
else if (greater(compchar, playerchar) == -1)
{
compscore += 1;
playerscore += 1;
printf("its a draw \n");
}
else
{
playerscore += 1;
printf("you got it hurray\n");
}
printf("you : %d \ncpu : %d \n", playerscore, compscore);
}
if (playerscore > compscore)
{
printf("you win \n");
}
else if (compscore > playerscore)
{
printf("cpu win \n");
}
else
{
printf("match is draw");
}
return 0;
}
|
code/languages/cpp/begin_and_end/README.md | **array::begin()** function is a library function of array and it is used to get the first element of the array, it returns an iterator pointing to the first element of the array.
Here, it's the syntax:
```cpp
array::begin();
```
**array::end()** function is a library function of array and it is used to get the last element of the array, it returns an iterator pointing to the last element of the array.
Here, it's the syntax:
```cpp
array::end();
```
Both the function returns iterator-
**Iterators** are used to point at the memory addresses of STL container and used to traverse a container like array and to access its elements.They reduce the complexity and execution time of program.
In this article, we'll get more information about begin() and end() function of an array and the basic idea about the iterators as well.
Link to the article: https://iq.opengenus.org/begin-and-end-array-cpp/
|
code/languages/cpp/begin_and_end/begin_and_end.cpp | // Implementation of begin() function
#include <array>
#include <iostream>
using namespace std;
int main()
{
// declaration of array container
array<int, 5> myarray{ 1, 2, 3, 4, 5 };
// using begin() to print array
for (auto it = myarray.begin(); it! =myarray. end(); ++it)
cout << ' ' << *it;
return 0;
}
// Implementation of end() function
#include <array>
#include <iostream>
using namespace std;
int main()
{
// declaration of array container
array<int, 5> myarray{ 10, 20, 30, 40, 50 };
// using end() to print array
for (auto it = myarray.begin();
it != myarray.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
code/languages/cpp/binary_search/README.md | Binary search is a specialized algorithm.It takes advantage of data that has been sorted in an array or a list.
Binary search is used on sorted arrays,and it more often when used with binary search trees
There is a dramatic speed enhancement in the runtime as the time complexity of binary search is O(log(n)),where n is the number of elements being searched.
Algorithm to search an element using Binary Search
1) Compare x with the middle element.
2) If x matches with the middle element, we return the mid index.
3) Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
4) Else (x is smaller) recur for the left half. |
code/languages/cpp/binary_search/binary_search_implementation.cpp | // /* Part of Cosmos by OpenGenus Foundation */
// There are mainly three methods by which you can implement Binary Search.
// By Iterative Approach
#include <bits/stdc++.h>
using namespace std;
int BinarySearch(int sorted_array[], int left, int right, int element)
{
while (left <= right)
{
int middle = (left + right) / 2;
// Check if element is present at middle position or not
if (sorted_array[middle] == element)
return middle;
// If element is greater, ignore left half
if (sorted_array[middle] < element)
left = middle + 1;
// If element is smaller, ignore right half
else
right = middle - 1;
}
// if element is not present then return -1
return -1;
}
int main()
{
int a[] = { 10, 12, 20, 32, 50, 55, 65, 80, 99 };
int element = 12;
int size = sizeof(a) / sizeof(a[0]);
sort(a, a + size);
int result = BinarySearch(a, 0, size - 1, element);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
// By Recursive Approach
#include <bits/stdc++.h>
using namespace std;
int BinarySearch(int sorted_array[], int left, int right, int element)
{
if (right >= left)
{
int middle = (left + right) / 2;
// If the element is present at the middle itself
if (sorted_array[middle] == element)
return middle;
// If element < middle, then it can only be present in left subarray
if (sorted_array[middle] > element)
return BinarySearch(sorted_array, left, middle - 1, element);
// Else the element can only be present in right subarray
return BinarySearch(sorted_array, middle + 1, right, element);
}
// We reach here when element is not
// present in array
return -1;
}
int main()
{
int a[] = { 1, 5, 7, 3, 4, 8, 2, 9, 6 };
int element = 5;
int size = sizeof(a) / sizeof(a[0]);
sort(a, a + size);
int result = BinarySearch(a, 0, size - 1, element);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
// Using STL Function
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[] = { 10, 12, 20, 32, 50, 55, 65, 80, 99 };
int element = 12;
int size = sizeof(a) / sizeof(a[0]);
sort(a, a + size);
if (binary_search(a, a + size, element))
cout << "\nElement found in the array";
else
cout << "\nElement not found in the array";
return 0;
}
|
code/languages/cpp/calculator/simpleCalculator.cpp | # include <iostream>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter operator: +, -, *, /: ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}
|
code/languages/cpp/delete_vs_free/README.md | The differences between delete,delete[] and free are as follows:
1. free is a library function whereas delete and delete[] are both operator.
2. free does not call any destructor while delete calls a destructor, if present whereas delete[] calls all the destructors that are present, according to the array size.
3. free deallocates any block of memory created using malloc, calloc or realloc while delete deallocates a non-array object that has been created with new.whereas delete[] deallocates an array that has been created with new[].
4. Freeing or deleting a null pointer with free, delete or delete[] causes no harm.
5. free() uses C run time heap while delete and delete[] may be overloaded on class basis to use private heap.
We cannot allocate an object with malloc() and free it using delete or allocate with new and delete with free() or use realloc() on an array allocated by new.The C++ operators new and delete guarantee proper construction and destruction; where constructors or destructors need to be invoked, they are. The C-style functions malloc(), calloc(), free(), and realloc() don’t ensure that. Furthermore, there is no guarantee that the mechanism used by new and delete to acquire and release raw memory is compatible with malloc() and free()
Link to the article: https://iq.opengenus.org/delete-vs-free-in-cpp/
|
code/languages/cpp/delete_vs_free/free_vs_delete.cpp | //Example of free() function using malloc and realloc:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
char *ptr;
ptr = (char*) malloc(10*sizeof(char)); //Allocating memory to thr character pointer
strcpy(ptr,"Hello C++");
cout << "Before reallocating: " << ptr << endl;
ptr = (char*) realloc(ptr,20); //Reallocating memory
strcpy(ptr,"Hello, Welcome to C++");
cout << "After reallocating: " <<ptr << endl;
free(ptr); //Freeing the character pointer
cout << endl << "Garbage Value: " << ptr;
return 0;
}
// Example of deleting a single object:
#include<iostream>
using namespace std;
int main()
{
int *d = new int(10); //Integer object created
cout<< "The value at the address pointed by the pointer variable : " << *d << "\n";
cout<< "The memory address allocated to the pointer variable : " << d << "\n";
delete d; //Single integer object deleted
cout<< "The value at the address pointed by pointer variable : " << *d << "\n";
cout<< "The memory address allocated to the pointer variable : " << d;
}
//Example of deleting multiple objects:
#include<iostream>
using namespace std;
int main()
{
int *d = new int[100]; //creation of multiple objects
delete [] d; //deletion of multiple objects
}
|
code/languages/cpp/detect_cycle_undirected_graph_using_degrees_of_nodes/README.md | **Detect cycle in a graph using degree of nodes of the graph**
There are different ways to detect cycle in an undirected graph. This article explains an intuitive and simple approach to detect cycle
and print the nodes forming the cycle in the graph.
We make use of :
* Map to maintain the adjacency list
* Queue to store all nodes/vertices with degree 1
* Boolean Array to keep track of the visited vertices
**Link to article :** https://iq.opengenus.org/p/9c85d01c-bd61-4423-949d-09812391b0f1/
|
code/languages/cpp/detect_cycle_undirected_graph_using_degrees_of_nodes/detect_cycle_graph_using_degree.cpp | // Detect cycle in a graph using Degree of graph
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
class graph {
private:
map<int, vector<int>> adjList;
int n, e; // no of vertices and edges
public:
void detect_cycle();
void input();
};
void graph::input() {
cout << "Enter the number of vertices : \n";
cin >> n;
cout << "Enter the number of edges : \n";
cin >> e;
cout << "Enter the adj list for the undirected graph \n";
for (int i = 0; i < e; i++) {
int start, end;
cin >> start;
cin >> end;
adjList[start].push_back(end);
adjList[end].push_back(start);
}
// print adj list
cout << "The adj list is :\n";
for (auto &val : adjList) {
cout << val.first << " : ";
for (int el : val.second) {
cout << el << " ";
}
cout << "\n";
}
}
void graph::detect_cycle() {
unordered_map<int, int> deg;
for (int i = 0; i < n; i++) {
deg[i] = adjList[i].size();
}
bool visited[n];
for (int i = 0; i < n; i++)
visited[i] = false;
queue<int> q;
while (1) {
// pushing all degree 1 nodes into the queue
// recursively updating the nodes with degree 1
for (auto &val : deg) {
if (val.second == 1 && visited[val.first] == false)
q.push(val.first);
}
if (q.empty())
break;
while (!q.empty()) {
int temp = q.front(); // deleting node with degree 1
q.pop();
visited[temp] = true;
for (int i = 0; i < adjList[temp].size(); i++) {
deg[adjList[temp][i]]--;
}
}
}
int f = 0;
for (int i = 0; i < n; i++) {
if (visited[i] == false)
f = 1;
}
if (f == 0)
cout << "No cycle detected !\n";
else {
cout << "Cycle detected \n";
for (int i = 0; i < n; i++) {
if (visited[i] == false)
cout << i << " ";
}
}
}
int main() {
graph g;
g.input();
g.detect_cycle();
return 0;
}
|
code/languages/cpp/double_to_string/README.md | There are various ways of converting string to double in the C++ language; but before going into the ways, let me give you a quick intro to string and double.
C++ provides the programmers a wide variety of built-in as well as user defined data types. String and double are both data types but they differ in a few respects:
Double is a built-in/primitive data type while std::string is a part of the standard library that comes with the C++ compiler which can be used after including the string.h header file.
String is a sequence of 0 or more characters while a variable of type double can hold floating point numbers upto 8 bytes.
Now we shall look into the various ways we can convert double to string in C++. The diferent ways are listed below:
1. double to String using C++’s std::to_string
2. double to String using ostringstream
3. double to String/character array using sprintf
4. double to String boost’s lexical_cast
Link to the article: https://iq.opengenus.org/convert-double-to-string-in-cpp/
|
code/languages/cpp/double_to_string/double_to_str.cpp | //double to String using C++’s std::to_string:
#include <iostream>
#include <string>
#include <sstream> //to use ostringstream
#include <cstring> //to use sprintf
#include <boost/lexical_cast.hpp> //to use boost's lexical cast
using namespace std;
int main()
{
double d1 = 23.43;
double d2 = 1e-9;
double d3 = 1e40;
double d4 = 1e-40;
double d5 = 123456789;
string d_str1 = to_string(d1);
string d_str2 = to_string(d2);
string d_str3 = to_string(d3);
string d_str4 = to_string(d4);
string d_str5 = to_string(d5);
cout << "Number: " << d1 << '\n'
<< "to_string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to_string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to_string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to_string: " << d_str4 << "\n\n"
<< "Number: " << d5 << '\n'
<< "to_string: " << d_str5 << '\n';
//double to String using ostringstream
ostringstream ss1,ss2,ss3,ss4;
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<d1;
ss2<<d2;
ss3<<d3;
ss4<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//Code to convert double to string with osstringstream to get the output as fixed-point notation inplace of scientific notation.
ostringstream ss1,ss2,ss3,ss4;
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<fixed<<d1;
ss2<<fixed<<d2;
ss3<<fixed<<d3;
ss4<<fixed<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//double to string with custom precision by setting the precision in stringstream as below
ostringstream ss1,ss2,ss3,ss4;
ss1.precision(2);
ss2.precision(2);
ss3.precision(2);
ss4.precision(2);
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<fixed<<d1;
ss2<<fixed<<d2;
ss3<<fixed<<d3;
ss4<<fixed<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//double to String/character array using sprintf
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
char s[200];
sprintf(s," 23.43 converts to %.2f \n 6789898989.339994 converts to %.3f \n 1e40 converts to %.4f \n 1e-40 converts to %.5f",d1,d2,d3,d4);
cout<<s<<"\nsize of the above string is:"<<strlen(s);
//double to String using boost’s lexical_cast
double d1 = 23.43;
double d2 = 1e-9;
double d3 = 1e40;
double d4 = 1e-40;
double d5 = 123456789;
string d_str1 = boost::lexical_cast<string>(d1);
string d_str2 = boost::lexical_cast<string>(d2);
string d_str3 = boost::lexical_cast<string>(d3);
string d_str4 = boost::lexical_cast<string>(d4);
string d_str5 = boost::lexical_cast<string>(d5);
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n"
<< "Number: " << d5 << '\n'
<< "to string: " << d_str5 << '\n';
return 0;
}
|
code/languages/cpp/initializing_multimap/README.md | Different ways of Initializing multimap in C++ :
In this article we explore different ways to initialize a multimap in C++. They are :
* Inserting using make_pair
* Inserting using pair (with only 1 pair object)
* Inserting usin pai
* Initializing with Initializer List
* Constructing a multimap n from another multimap m
* Using copy constructor
* Using emplace_hint()
We also explore different ways to print the contents of the multimap container in C++
https://iq.opengenus.org/initializing-multimap-in-cpp/
|
code/languages/cpp/initializing_multimap/multimap.cpp | #include<iostream>
#include<cstdlib>
#include<map>
using namespace std;
int main()
{
//common way to initialize a multimap
std::multimap<char, int> m; //empty multimap container
m.insert({'a',1}); //inserting (a,1)
m.insert({'a',1}); //inserting (a,1)
m.insert({'b',2}); //inserting (b,2)
m.insert({'c',3}); //inserting (c,3)
m.insert({'a',2}); //inserting (a,2)
m.insert({'d',4}); //inserting (d,4)
//Method 1
std::multimap<char, int> m; //empty multimap container
m.insert(make_pair('a',1)); //inserting (a,1)
m.insert(make_pair('a',1)); //inserting (a,1)
m.insert(make_pair('b',2)); //inserting (b,2)
m.insert(make_pair('c',3)); //inserting (c,3)
m.insert(make_pair('a',2)); //inserting (a,2)
m.insert(make_pair('d',4)); //inserting (d,4)
//Method 2
pair<char, int> x;
std::multimap<char, int> m; //empty multimap container
x.first='a';x.second=1;
m.insert(x); //inserting (a,1)
x.first='a';x.second=1;
m.insert(x); //inserting (a,1)
x.first='b';x.second=2;
m.insert(x); //inserting (b,2)
x.first='c';x.second=3;
m.insert(x); //inserting (c,3)
x.first='a';x.second=2;
m.insert(x); //inserting (a,2)
x.first='d';x.second=4;
m.insert(x); //inserting (d,4)
//Method 3
std::multimap<char, int> m; //empty multimap container
m.insert(pair<char, int>('a',1)); //inserting (a,1)
m.insert(pair<char, int>('a',1)); //inserting (a,1)
m.insert(pair<char, int>('b',2)); //inserting (b,2)
m.insert(pair<char, int>('c',3)); //inserting (c,3)
m.insert(pair<char, int>('a',2)); //inserting (a,2)
m.insert(pair<char, int>('d',4)); //inserting (d,4)
//Method 4
std::multimap<char, int> m={
{'a',1}, {'a',1}, {'b',2}, {'c',3}, {'a',2}, {'d',4}
};
//Method 5
std::multimap<char, int> n(m.begin(),m.end());
//Method 6
std::multimap<char, int> n(m);
//Method 7
std::multimap<char, int> mp;
mp.emplace_hint(mp.begin(), 'a', 1);
mp.emplace_hint(mp.begin(), 'a', 1);
mp.emplace_hint(mp.begin(), 'b', 2);
mp.emplace_hint(mp.begin(), 'c', 3);
mp.emplace_hint(mp.begin(), 'a', 2);
mp.emplace_hint(mp.begin(), 'd', 4);
//Printing contents of the multimap :
//Method 1
for(auto& el : mp)
cout<<el.first<<" "<<el.second<<endl;
//Method 2
multimap<char, int>::iterator it;
for(it=m.begin();it!=m.end();it++)
cout<<it->first<<" "<<it->second<<"\n";
//Method 3
for(pair<char, int> elem: m)
cout<<elem.first<<" "<<elem.second<<endl;
return 0;
}
|
code/languages/cpp/largest-element-in-an-array/Largest_element.cpp | #include <iostream>
using namespace std;
int findlargestelement(int arr[], int n){
int largest = arr[0];
for(int i=0; i<n; i++) {
if(largest<arr[i]) {
largest=arr[i];
}
}
return largest;
}
int main() {
int n;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter array elements: ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
int largest = findlargestelement(arr, n);
cout<<"largest Element is: "<<largest;
return 0;
}
|
code/languages/cpp/largest-element-in-an-array/README.md | <h3>Finding largest element in an array</h3>
We are given an integer array of size N or we can say number of elements is equal to N.
We have to find the largest/ maximum element in an array.
Approach
Firstly, program asks the user to input the values.
We assign the first element value to the largest variable.
Then we compare largest with all other elements inside a loop.
If the largest is larger than all other elements,
Then we return largest which store first element value as largest element.
But if the element is larger than the largest,
Then we store that element value into largest.
This way largest will always store the largest value.
Then we return largest.
Time complexity: O(N) where there are N elements in the array
Space complexity: O(1)
<p align="center">
For more insights, refer to <a href="https://iq.opengenus.org/largest-element-in-an-array/">Scheduling to finding largest element in an array</a>
</p>
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
|
code/languages/cpp/linear_search/Linear Search In A LinkedList With Duplicates.cpp | #include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insert(int pos, int x)
{
struct node *temp = new node;
if (temp == NULL)
cout<<"Insertion not possible\n";
temp->data = x; // storing the value in data field
if (pos == 1)
{
temp->nptr = hptr;
hptr = temp;
}
else
{
int i = 1;
struct node *thptr = hptr; // temporary pointer
while (i < pos - 1)
{
thptr = thptr->nptr; // traversing to the position of insertion
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
void print()
{
struct node *temp = hptr;
cout<<"Linked List contains : \n";
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->nptr;
}
}
int ind;
int *linearSearch(int key, int result[])
{
struct node *temp = hptr;
int i = 1;
ind = 0;
while (temp != NULL)
{
if (temp->data == key)
{
result[ind++] = i;
}
else
{
result[ind] = -1;
ind++;
}
i++;
temp = temp->nptr;
}
return result;
}
int main()
{
int result[10];
insert(1, 11);
insert(2, 6);
insert(3, 12);
insert(4, 14);
insert(5, 6);
insert(6, 10);
insert(7, 6);
print();
printf("\nPosition(s) of the key is : ");
linearSearch(6, result);
for (int i = 0; i < ind; i++)
{
if (result[i] != -1)
cout<<result[i]<<" ";
}
return 0;
}
|
code/languages/cpp/linear_search/Linear Search In Array.cpp | // C++ code to linearly search x in arr[].
//If x is present then return its location, otherwise return -1
#include <iostream>
using namespace std;
int search(int arr[], int N, int x)
{
int i;
for (i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver's code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, N, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
|
code/languages/cpp/linear_search/Linear Search In Duplicate Array.cpp | // C++ code to linearly search x in arr[].
//If x is present then return its location, otherwise return -1
#include <iostream>
using namespace std;
int *linearSearch(int arr[], int result[], int N, int x)
{
int pos = -1, ind = 0;
for (int i = 0; i <N; ++i)
{
if (arr[i] == x)
{
result[ind++] = i+1; // store the index of key, if found
}
else
result[ind++] = -1; // store -1 if key not found
}
return result;
}
// Driver's code
int main(void)
{
int arr[] = {2, 3, 4, 10, 40, 3, 10, 2, 10 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
int result[N];
linearSearch(arr, result, N, x);
int size = sizeof(result) / sizeof(result[0]);
cout<<"Key found at position(s) : \n";
for (int i = 0; i < size; i++)
{
if (result[i] != -1)
cout<<result[i]<<" ";
}
return 0;
}
|
code/languages/cpp/linear_search/README.md | Linear Search in C++ Programming Language :
This article covers the topics :
* Linear Search in an array
* Linear Search in a linked list
* Linear Search in an array with duplicates
* Linear Search in a linked list with duplicates
https://iq.opengenus.org/linear-search-in-c/
|
code/languages/cpp/linear_search/Search In Linked List.cpp | #include <iostream>
using namespace std;
struct node
{
int num;
node *nextptr;
}*stnode; //node defined
void makeList(int n);
void searchList(int item, int n);
int main()
{
int n,num,item;
cout<<"Enter the number of nodes: ";
cin>>n;
makeList(n);
cout<<"\nEnter element you want to search: ";
cin>>item;
searchList(item,n);
return 0;
}
void makeList(int n) //function to create linked list.
{
struct node *frntNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL)
{
cout<<" Memory can not be allocated";
}
else
{
cout<<"Enter the data for node 1: ";
cin>>num;
stnode-> num = num;
stnode-> nextptr = NULL; //Links the address field to NULL
tmp = stnode;
for(i=2; i<=n; i++)
{
frntNode = (struct node *)malloc(sizeof(struct node));
if(frntNode == NULL) //If frontnode is null no memory cannot be allotted
{
cout<<"Memory can not be allocated";
break;
}
else
{
cout<<"Enter the data for node "<<i<<": "; // Entering data in nodes.
cin>>num;
frntNode->num = num;
frntNode->nextptr = NULL;
tmp->nextptr = frntNode;
tmp = tmp->nextptr;
}
}
}
}
void searchList(int item, int n) //function to search element in the linked list
{
struct node *tmp;
int i=0,flag=0;
tmp = stnode;
if(tmp == NULL)
{
cout<<"\nEmpty List\n";
}
else
{
while (tmp!=NULL)
{
if(tmp->num == item) //If element is present in the list
{
cout<<"Item found at location: "<<(i+1);
flag=0;
}
else
{
flag++;
}
i++;
tmp = tmp -> nextptr;
}
if(flag==n) //If element is not present in the list
{
cout<<"Item not found\n";
}
}
}
|
code/languages/cpp/loop/continue.cpp | #include <iostream>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==5)
{
/* The continue statement is encountered when
* the value of j is equal to 5.
*/
continue;
}
/* This print statement would not execute for the
* loop iteration where j ==5 because in that case
* this statement would be skipped.
*/
std::cout << j;
}
return 0;
}
/*
0 1 2 3 4 6 7 8
*/
|
code/languages/cpp/reverse_linked_list/README.md | Reversing a linked list using 2 pointers using XOR :
We reverse a given linked list by link reversal and not by swapping the values of the nodes in the linked list.
The common technique to reverse a linked list involves using 3 pointers.
But by using properties of the xor operation, we learn to reverse the linked list with only 2 pointers.
By using xor, we eliminate the need for an extra pointer.
For the 2 pointer technique, we need to caste the pointers to type unitpr_t and then perform bitwise operations (in this case, xor operation) since we cannot perform bitwise operations directly on pointers.
https://iq.opengenus.org/reverse-linked-list-using-2-pointers-xor/
|
code/languages/cpp/reverse_linked_list/reverse_linked_list_2pointers.cpp | // Reverse a Linked List using 2 pointers using XOR
// https://iq.opengenus.org/p/8046f2c5-2cc6-4df0-b343-dd4f4a69d567/
#include <cstdlib>
#include <iostream>
typedef uintptr_t ut;
// structure of the linked list
struct node {
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insertNode(int pos, int x) {
struct node *temp = new node;
if (temp == NULL)
std::cout << "Insert not possible\n";
temp->data = x;
if (pos == 1) {
temp->nptr = hptr;
hptr = temp;
} else {
int i = 1;
struct node *thptr = hptr;
while (i < pos - 1) {
thptr = thptr->nptr;
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
// function to reverse the linked list
void reverseList() {
struct node *current = hptr;
struct node *prev = NULL;
while (current != NULL) {
current = (struct node *)((ut)prev ^ (ut)current ^ (ut)(current->nptr) ^
(ut)(current->nptr = prev) ^
(ut)(prev = current)); // link reversal
}
hptr = prev; // updating the head pointer
}
// printing the contents of the linked list
void print() {
struct node *temp = hptr;
while (temp != NULL) {
std::cout << temp->data << "\n";
temp = temp->nptr;
}
}
int main() {
insertNode(1, 10);
insertNode(2, 20);
insertNode(3, 30);
insertNode(4, 40);
insertNode(5, 50);
reverseList();
print();
return 0;
}
|
code/languages/cpp/reverse_linked_list/reverse_linked_list_3pointers.cpp | // Reverse a linked list using 3 pointers
// https://iq.opengenus.org/reverse-linked-list-using-2-pointers-xor/
#include <cstdlib>
#include <iostream>
struct node {
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insertNode(int pos, int x) {
struct node *temp = new node;
if (temp == NULL)
std::cout << "Insert not possible\n";
temp->data = x;
if (pos == 1) {
temp->nptr = hptr;
hptr = temp;
} else {
int i = 1;
struct node *thptr = hptr;
while (i < pos - 1) {
thptr = thptr->nptr;
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
// function to reverse the linked list
void reverseList() {
struct node *current = hptr;
struct node *next;
struct node *prev = NULL;
// link reversal
while (current != NULL) {
next = current->nptr;
current->nptr = prev;
prev = current;
current = next;
}
// updating the head pointer after link reversal
hptr = prev;
}
// function to print the contents of the linked list
void print() {
struct node *temp = hptr;
while (temp != NULL) {
std::cout << temp->data << "\n";
temp = temp->nptr;
}
}
int main() {
insertNode(1, 10);
insertNode(2, 20);
insertNode(3, 30);
insertNode(4, 40);
insertNode(5, 50);
reverseList();
print();
return 0;
}
|
code/languages/cpp/sort_vector/sorting_vector.cpp | //sorting using vectors
#include<bits/stdc++.h>
using namespace std;
int main;
{
vector<int> v;
cout<<"size of array"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
v.push_back(i);
}
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
sort(v.begin(),vec.end());
for(int x:v)
{
cout<<x<<" ";
}
return 0;
}
|
code/languages/cpp/spiral_matrix/spiral_matrix.cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the size of the array :";
cin>>n; /*n Size of the array*/
int A[n][n];
int len=n,k=1,p=0,i; /*k is to assign the values to the array from 1...n*n */
/*len is used to update(decrease) array size so that values cans be assign to them */
while(k<=n*n)
{
for(i=p;i<len;i++) /*Loop to access the first row of the array*/
{
A[p][i]=k++;
}
for(i=p+1;i<len;i++) /*Loop tp access the last column of the array*/
{
A[i][len-1]=k++;
}
for(i=len-2;i>=p;i--) /*Loop to access the last row of the array*/
{
A[len-1][i]=k++;
}
for(i=len-2;i>p;i--) /*Loop to access the first column of the array*/
{
A[i][p]=k++;
}
p++,len=len-1;
}
if(!n%2) /*This block will run only if n is even*/
{
A[(n+1)/2][(n+1)/2]=n*n; /*It will assign the last value to the centremost element*/
}
for(i=0;i<n;i++) /*This loop will print the array in matrix format*/
{
for(int j=0;j<n;j++)
{
cout<<A[i][j]<<"\t";
}
cout<<endl;
}
return 0;
} |
code/languages/cpp/uint8_t/README.md | ## uint8_t
uint8_t is a [fixed width integer datatype](https://iq.opengenus.org/fixed-width-integer-types-in-cpp/) in C++ of size 8 bits. |
code/languages/cpp/uint8_t/int8_t_test.cpp | #include <iostream>
int main() {
uint8_t number = 4;
std::cout << "Number=" << +number << std::endl;
return 0;
} |
code/languages/cpp/vector-to-map.cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
map<string,int> mp1;
mp1["Shivani"] = 500;
mp1["Kumari"] = 100;
mp1["Hacktoberfest"] = 400;
vector<pair<string,int>> vec1;
for(auto i : mp1) //inserting map values into vector
{
vec1.push_back(make_pair(i.first,i.second));
}
for(auto j : vec1)
cout<<j.first<<" : "<<j.second<<endl;
return 0;
}
|
code/languages/cpp/vector_to_map/readme.md | ## An approach to find different ways to convert vector to map in C++.
Maps are a part of the C++ Standard Template Library
maps are used to replicate associative arrays.
maps contains sorted key-value pair , in which each key is unique and cannot be changed and it can be inserted or deleted but cannot be altered.
Each element has a key value and a mapped value. No two mapped values can have same key values.
Maps store the key values in ascending order by default
Vectors are part of the C++ Standard Template Library. vector can provide memory flexibility.
vector being a dynamic array, doesn't need size during declaration
vectors are like arrays that are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically.
i.e we can change the size of the vector during the execution of a program as per our requirements.
The vector class provides various methods to perform different operations on vectors.
Vector of maps can be used to design complex and efficient data structures.
Link to the article: https://iq.opengenus.org/convert-vector-to-map-in-cpp/
|
code/languages/dart/01.data_types.dart | void main() {
// Text er jonno String
String x = 'ikram';
// Whole number er jonno int
int y = 5;
// floating point ba fractional number er jonno double
double z = 5.3;
print(x);
print(y);
print(z);
print(x + ' 2');
print(y + 2);
}
|
code/languages/dart/02.condition.dart | void main() {
// we're setting the value of x
int x = 3;
// if else condition
// checking if else is 10 or not
if(x==10) {
print('x is 10');
}
// checking if x is 5 or not
else if(x==5) {
print('x is 5');
}
// if none of the above is true, then
// this code will run
else {
print('x is not 10 or 5');
}
} |
code/languages/dart/03.loop.dart | void main() {
for (int x = 1; x <= 10; x = x + 1) {
print('$x ikram');
}
}
|
code/languages/dart/04.data_structure.dart | void main() {
// Create a list named nameList
List nameList = ['ikram', 'jahidul', 'habib', 'zahid', 'sharmin'];
// Add an item to the list
nameList.add('forhad');
// Remove an item from the list
nameList.removeAt(0);
// To get the lenght of the list
// we use list.length
print(nameList.length);
// Creating a loop to print all the items
for (int i = 0; i < nameList.length; i = i + 1) {
print(nameList[i]);
}
// Map stores a key, value pair
Map studentMap = {
'name': 'Ikram',
'age': 23,
};
Map studentMap2 = {
'name': 'Forhad',
'age': 25,
};
// Add the map to a list
List studentList = [studentMap,studentMap2];
print(studentList);
}
|
code/languages/dart/README.md | ### Task 1
Write dart code of a program that reads two numbers from the user, and prints their sum, product, and difference.
==========================================================
*hint: Subtract the second number from the first one*
==========================================================
**Example01:**
Input:\
4\
5
Output:\
Sum = 9\
Product = 20\
Difference = -1
==========================================================
**Example02:**
Input:\
30\
2
Output:\
Sum = 32\
Product = 60\
Difference = 28
==========================================================
### Task 2
Write dart code of a program that reads two numbers from the user. Your program should then print "First is greater" if the first number is greater, "Second is greater" if the second number is greater, and "The numbers are equal" otherwise.
==========================================================
**Example:**
Input:\
-4\
-4
Output:\
The numbers are equal
==========================================================
**Example:**
Input:\
-40\
-4
Output:\
Second is greater
### Task 3
Write dart code of a program that reads two numbers, subtracts the smaller number from the larger one, and prints the result.
*hint(1): First check which number is greater*
==========================================================
**Example:**
Input:\
-40\
-4
Output:\
36
==========================================================
**Example:**
Input:\
6\
2
Output:\
4
### Task 4
Write dart code of a program that reads a number, and prints "The number is even" or "The number is odd", depending on whether the number is even or odd.
*hint(1): use the modulus (%) operator*
*hint(2): You can consider the number to be an integer*
==========================================================
**Example:**
Input:\
5
Output:\
The number is odd
==========================================================
**Example:**
Input:\
-44
Output:\
The number is even
### Task 5
Write dart code of a program that prints your name 5 times using for loop
==========================================================
**Example:**
Output:\
Ikram Hasan
Ikram Hasan
Ikram Hasan
Ikram Hasan
Ikram Hasan
==========================================================
|
code/languages/python/2d-array-numpy/2d-array-numpy.py | import numpy as np
# 1D array
arr = np.array([2,4,6],dtype='int32')
print(arr)
# 2D array
arr = np.array([[1,2,3],[4,5,6]])
print(arr)
print(arr.shape)
print(arr.dtype)
print(arr[1,1])
print(arr[1,:])
arr = np.ones((4,4))
t = arr[1:3,1:3]
print(t)
arr_zeros = np.zeros((3,5))
print(arr_zeros)
arr_ones = 2*np.ones((3,5))
print(arr_ones)
arr_rand = np.random.rand(3,4)
print(arr_rand)
arr_i = np.identity(3)
print(arr_i)
a = np.array([[1,2,3],[4,6,2],[0,7,1]])
print(a+2)
print(a-4)
print(a*3)
print(a/2)
print(a**2)
a = np.array([[1,2,3],[4,6,2],[0,7,1]])
b = np.array([[3,6],[1,4],[7,2]])
c = np.array([[1,0,3],[2,3,1],[0,0,1]])
add = a+c
mul = np.matmul(a,b)
print(add)
print(mul)
print(np.min(b))
print(np.max(b))
print(np.linalg.det(a))
print(np.sum(b,axis=0))
print(np.sum(b,axis=1))
before = np.array([[1,2,3,4],[5,6,7,8]])
after = before.reshape(4,2)
print(after)
a = np.identity(2)
b = np.array([[1,2],[2,1]])
hstack = np.hstack((a,b))
print(hstack)
a = np.identity(2)
b = np.array([[1,2],[2,1]])
vstack = np.vstack((a,b))
print(vstack)
|
code/languages/python/2d-array-numpy/README.md | # 2D Arrays in NumPy
## [Article for 2D arrays in Python using Numpy](https://iq.opengenus.org/2d-array-in-numpy)
Array is a Linear Datastructure which consists of list of elements. Arrays can be 1 Dimensional, 2 Dimensional, 3 Dimensional and so on. 2 Dimensional arrays are often called as Matrix.<br>
Arrays created with NumPy are stored in contiguous memory locations so it leds to faster operations on it. It is more efficient as compared to traditional arrays and Lists.
This article covers various topics such as :
* Introduction and Installation of NumPy
* What is an Array?
* Creating an Array
* Various funtion on Array
* Indexing
* Initialization
* Operations on 2D array
* Reorganizing arrays
This article will give you the basic knowledge of Numpy and 2D arrays. The code for it can be found in 2D-array-numpy.py file.
|
code/languages/python/Image Encryption Decryption/README.md | ## ✔ IMAGE ENCRYPTION DECRYPTION
- An Image Encryption Decryption is an image processing application created in python with tkinter gui and OpenCv library.
- In this application user can select an image and can encrypt that image to gray scale image and can even decrpyt also.
- Also after encrypting and decrypting user can also save the edited image anywhere in the local system.
- Also there is option to reset to the original image.
****
### REQUIREMENTS :
- python 3
- os module
- cv2 module
- tkinter module
- filedialog from tkinter
- messagebox
- from PIL import Image, ImageTk
- numpy
- random
****
### HOW TO Use it :
- User just need to download the file, and run the image_encryption_decryption.py, on local system.
- After running a GUI window appears, where user needs to choose an image file using CHOOSE button on the top right corner.
- After selecting the image, two images will appear on screen one on left side, which is original and one on write in which Encrypted Decrypted format will be shown.
- Now user can start encryption and decryption using Encrypt and Decrypt button.
- After editing user can also save the edited image to any location in local system using SAVE button.
- Also there is a RESET button, clicking on which resets the edited image to original format.
- Also there is exit button, clicking on which we get a exit dialog box asking the permission to exit.
### Purpose :
- This scripts helps us to easily encrypt any image for security purpose and can even decrypt also.
### Compilation Steps :
- Install tkinter, PIL, numpy, cv2, os, random
- After that download the code file, and run image_encryption_decryption.py on local system.
- Then the script will start running and user can explore it by encrypting and decrypting any image and saving it.
****
### SCREENSHOTS :
<p align="center">
<img width = 1000 src="Images/1.jpg" /><br>
<img width = 1000 src="Images/2.jpg" /><br>
<img width = 1000 src="Images/3.jpg" /><br>
<img width = 1000 src="Images/4.jpg" /><br>
<img width = 1000 src="Images/5.jpg" /><br>
<img width = 1000 src="Images/6.jpg" /><br>
<img width = 1000 src="Images/7.jpg" /><br>
<img width = 1000 src="Images/8.jpg" /><br>
<img width = 1000 src="Images/9.jpg" /><br>
<img width = 1000 src="Images/10.jpg" /><br>
<img width = 1000 src="Images/11.jpg" /><br>
</p>
|
code/languages/python/Image Encryption Decryption/image_encryption_decryption.py |
# Image Encryption Decryption
# Part of OpenGenus Cosmos
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image
import cv2
import os
import numpy as np
from cv2 import *
import random
#created main window
window = Tk()
window.geometry("1000x700")
window.title("Image Encryption Decryption")
# defined variable
global count, emig
# global bright, con
# global frp, tname # list of paths
frp = []
tname = []
con = 1
bright = 0
panelB = None
panelA = None
# function defined to get the path of the image selected
def getpath(path):
a = path.split(r'/')
# print(a)
fname = a[-1]
l = len(fname)
location = path[:-l]
return location
# function defined to get the folder name from which image is selected
def getfoldername(path):
a = path.split(r'/')
# print(a)
name = a[-1]
return name
# function defined to get the file name of image is selected
def getfilename(path):
a = path.split(r'/')
fname = a[-1]
a = fname.split('.')
a = a[0]
return a
# function defined to open the image file
def openfilename():
filename = filedialog.askopenfilename(title='"pen')
return filename
# function defined to open the selected image
def open_img():
global x, panelA, panelB
global count, eimg, location, filename
count = 0
x = openfilename()
img = Image.open(x)
eimg = img
img = ImageTk.PhotoImage(img)
temp = x
location = getpath(temp)
filename = getfilename(temp)
# print(x)
if panelA is None or panelB is None:
panelA = Label(image=img)
panelA.image = img
panelA.pack(side="left", padx=10, pady=10)
panelB = Label(image=img)
panelB.image = img
panelB.pack(side="right", padx=10, pady=10)
else:
panelA.configure(image=img)
panelB.configure(image=img)
panelA.image = img
panelB.image = img
# function defined for make the sketch of image selected
def en_fun():
global x, image_encrypted, key
# print(x)
image_input = imread(x, IMREAD_GRAYSCALE)# 'C:/Users/aakas/Documents/flower.jpg'
(x1, y) = image_input.shape
image_input = image_input.astype(float) / 255.0
# print(image_input)
mu, sigma = 0, 0.1 # mean and standard deviation
key = np.random.normal(mu, sigma, (x1, y)) + np.finfo(float).eps
# print(key)
image_encrypted = image_input / key
imwrite('image_encrypted.jpg', image_encrypted * 255)
imge = Image.open('image_encrypted.jpg')
imge = ImageTk.PhotoImage(imge)
panelB.configure(image=imge)
panelB.image = imge
mbox.showinfo("Encrypt Status", "Image Encryted successfully.")
# function defined to make the image sharp
def de_fun():
global image_encrypted, key
image_output = image_encrypted * key
image_output *= 255.0
imwrite('image_output.jpg', image_output)
imgd = Image.open('image_output.jpg')
imgd = ImageTk.PhotoImage(imgd)
panelB.configure(image=imgd)
panelB.image = imgd
mbox.showinfo("Decrypt Status", "Image decrypted successfully.")
# function defined to reset the edited image to original one
def reset():
# print(x)
image = cv2.imread(x)[:, :, ::-1]
global count, eimg
count = 6
global o6
o6 = image
image = Image.fromarray(o6)
eimg = image
image = ImageTk.PhotoImage(image)
panelB.configure(image=image)
panelB.image = image
mbox.showinfo("Success", "Image reset to original format!")
# function defined to same the edited image
def save_img():
global location, filename, eimg
print(filename)
# eimg.save(location + filename + r"_edit.png")
filename = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
if not filename:
return
eimg.save(filename)
mbox.showinfo("Success", "Encrypted Image Saved Successfully!")
# top label
start1 = tk.Label(text = "Image Encryption\nDecryption", font=("Arial", 40), fg="magenta") # same way bg
start1.place(x = 350, y = 10)
# original image label
start1 = tk.Label(text = "Original\nImage", font=("Arial", 40), fg="magenta") # same way bg
start1.place(x = 100, y = 270)
# edited image label
start1 = tk.Label(text = "Encrypted\nDecrypted\nImage", font=("Arial", 40), fg="magenta") # same way bg
start1.place(x = 700, y = 230)
# choose button created
chooseb = Button(window, text="Choose",command=open_img,font=("Arial", 20), bg = "orange", fg = "blue", borderwidth=3, relief="raised")
chooseb.place(x =30 , y =20 )
# save button created
saveb = Button(window, text="Save",command=save_img,font=("Arial", 20), bg = "orange", fg = "blue", borderwidth=3, relief="raised")
saveb.place(x =170 , y =20 )
# Encrypt button created
enb = Button(window, text="Encrypt",command=en_fun,font=("Arial", 20), bg = "light green", fg = "blue", borderwidth=3, relief="raised")
enb.place(x =150 , y =620 )
# decrypt button created
deb = Button(window, text="Decrypt",command=de_fun,font=("Arial", 20), bg = "orange", fg = "blue", borderwidth=3, relief="raised")
deb.place(x =450 , y =620 )
# reset button created
resetb = Button(window, text="Reset",command=reset,font=("Arial", 20), bg = "yellow", fg = "blue", borderwidth=3, relief="raised")
resetb.place(x =800 , y =620 )
# function created for exiting
def exit_win():
if mbox.askokcancel("Exit", "Do you want to exit?"):
window.destroy()
# exit button created
exitb = Button(window, text="EXIT",command=exit_win,font=("Arial", 20), bg = "red", fg = "blue", borderwidth=3, relief="raised")
exitb.place(x =880 , y =20 )
window.protocol("WM_DELETE_WINDOW", exit_win)
window.mainloop()
|
code/languages/python/counter_objects/README.md | # Counter Objects in Python
## [Article on counter objects in python](https://iq.opengenus.org/counter-objects-in-python/)
Counters are a subclass of dictionary that are used to keep a track of elements. This article covers topics such as :
* Creating python counter objects
* Accessing counters in python
* Getting & setting count of elements
* Deleting elements from counter
* Python Counter methods
* Operations on python counters
* Implementation
* Application
This article will give you the knowledge of counter objects in python language.
|
code/languages/python/counter_objects/counter_obj.py | from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])
|
code/languages/python/rock_paper_scissors/rock_paper_scissor.py | from random import choice
while (True):
print("Rock \nPaper \nScissors!!!!!")
player1 = input("Enter your choice: ")
choices = ["ROCK", "PAPER", "SCISSORS"]
player2 = choice(choices)
print("SHOOT!!!")
print(f"player 2 played {player2}")
if (player1 != player2):
if (player1.upper() == "ROCK") and (player2.upper() == "SCISSORS"):
print("player 1 wins")
elif (player1.upper() == "SCISSORS") and (player2.upper() == "PAPER"):
print("player 1 wins")
elif (player1.upper() == "PAPER") and (player2.upper() == "ROCK"):
print("player 1 wins")
else:
print("player 2 wins")
else:
print("Tied")
print("---------------------------------------")
flag = input("Do you want to continue? ")
if flag.lower() == "no":
break
elif flag.lower() == "yes":
continue |
code/languages/python/static-class-variable/Readme.md | # Static Class Variables in Python
## [Article on Static Class Variable in Python](https://iq.opengenus.org/static-class-variable-in-python/)
This article covers topics such as :
* what is class?
* what is objects?
* What is Static Variable?
* Creating Static variable in python
* Classification of static variable in python
* Accessing class variable inside the class
* Accessing class variable outside of the class
* Question
This article will give you the knowledge of Static Class Variable in python language.
|
code/languages/python/static-class-variable/StaticClassVariable.py | # Python program to show that the variables with a value
# assigned in class declaration, are class variables
# Class for different type of Instrument
class Instrument:
courseoffered = 'yes' # Class Variable
def __init__(self,price,tax):
self.Instrumentname = Instrumentname # Instance Variable
self.count = count # Instance Variable
# Objects of CSStudent class
a = Instrument('Guitar', 1)
b = Instrument('piaono', 2)
print(a.courseoffered) # prints "yes"
print(b.courseoffered) # prints "yes"
print(a.Instrumentname) # prints "Guitar"
print(b.Instrumentname) # prints "Piaono"
print(a.count) # prints "1"
print(b.count) # prints "2"
# Class variables can be accessed using class
# name also
print(Instrument.courseoffered) # prints "yes"
# Now if we change the courseoffered for just a it won't be changed for b
a.courseoffered = 'No'
print(a.courseoffered) # prints 'no'
print(b.courseoffered) # prints 'yes'
# To change the courseoffered for all instances of the class we can change it
# directly from the class
instrument.courseoffered = 'yes'
print(a.courseoffered) # prints 'yes'
print(b.courseoffered) # prints 'no'
|
code/languages/python/stock_data/Stock_data.py | from nsetools import Nse
from pprint import pprint
nse = Nse()
company = str(input("Enter the symbol of the company : "))
#data = nse.get_quote('zylog')
data = nse.get_quote(company)
print('=================================='+ data['companyName']+'\t' + data['symbol']+'=================================================================')
print("Previous Day close (" , end="")
print(data['recordDate'] ,end="")
print(") : " ,end="")
print(data['previousClose'] , end="\t")
print("Trade Day : " ,end = "" )
print (data['secDate'])
print('================================== 52 week =================================================================')
print("52 week high : " , end = "")
print(data['high52'] , end = "\t")
print("52 week low : " , end = "")
print(data['low52'] )
print("Last close : " , end="")
print(data['previousClose'])
print('================================== Trade History =================================================================')
print("Sell \t\t Qty \t\t\t Buy \t Qty" )
print("---- \t\t --- \t\t\t --- \t ---")
print(data['sellPrice1'] ,end="")
print(" \t ",end = "")
print(data['sellQuantity1'] , end = "")
print(" \t\t " , end = "")
print(data['buyPrice1'] ,end="")
print(" \t ",end = "")
print(data['buyQuantity1'],end="\n")
print(data['sellPrice2'] ,end="")
print(" \t ",end = "")
print(data['sellQuantity2'] , end = "")
print(" \t\t " , end = "")
print(data['buyPrice2'] ,end="")
print(" \t ",end = "")
print(data['buyQuantity2'],end="\n")
print(data['sellPrice3'] ,end="")
print(" \t ",end = "")
print(data['sellQuantity3'] , end = "")
print(" \t\t " , end = "")
print(data['buyPrice3'] ,end="")
print(" \t ",end = "")
print(data['buyQuantity3'],end="\n")
print(data['sellPrice4'] ,end="")
print(" \t ",end = "")
print(data['sellQuantity4'] , end = "")
print(" \t\t " , end = "")
print(data['buyPrice4'] ,end="")
print(" \t ",end = "")
print(data['buyQuantity4'],end="\n")
print(data['sellPrice5'] ,end="")
print(" \t ",end = "")
print(data['sellQuantity5'] , end = "")
print(" \t\t " , end = "")
print(data['buyPrice5'] ,end="")
print(" \t ",end = "")
print(data['buyQuantity5'],end="\n")
print("Day open : " , end = "")
print(data['open'] , end = "\n")
print("Day High : " , end ="")
print(data['dayHigh'] , end = "\t\t")
print(" Day Low : " , end ="")
print(data['dayLow'] , end = "\n")
print('ClosePrice : ' , end ="")
print(data['closePrice'],end = "\t")
print(' AveragePrice : ' , end ="")
print(data['averagePrice'],end = "\n")
print('TotalTradedVolume : ' , end ="")
print(data['totalTradedVolume'],end = "\n")
|
code/languages/python/tuple/README.md | # Tuple
## [Article explaining Tuple in Python at OpenGenus IQ](https://iq.opengenus.org/tuple-python/)
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. The important difference between a list and a tuple is that tuples are immutable.
Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
### Defining and Using Tuples
* Tuples are identical to lists in all respects, except for the following properties:
* Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
* Tuples can be defined without being enclosed in parentheses and just separated by commas.
```python
z = 3, 7, 4, 2
```
* Tuples are immutable.
Here is a short example showing a tuple definition, indexing, and slicing:
```Python
>>> t = ('foo', 'bar', 'baz', 'aux', 'quux', 'corge')
>>> t
('foo', 'bar', 'baz', 'aux', 'quux', 'corge')
>>> t[0]
'foo'
>>> t[-1]
'corge'
>>> t[1::2]
('bar', 'aux', 'corge')
```
string and list reversal mechanism works for tuples as well:
```python
>>> t[::-1]
('corge', 'quux', 'aux', 'baz', 'bar', 'foo')
```
### Why use a tuple instead of a list?
* Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)
* Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.
* There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.
### Packing and Unpacking of tuple
In Python there is a very powerful tuple assignment feature that assigns right hand side of values into left hand side. In other way it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.
### Example
```Python
# Program to understand about
# packing and unpacking in Python
# this lines PACKS values
# into variable a
a = ("MIT", 5000, "Engineering")
# this lines UNPACKS values
# of variable a
(college, student, type_ofcollege) = a
# print college name
print(college)
# print no of student
print(student)
# print type of college
print(type_ofcollege)
```
**Output**
```
MIT
5000
Engineering
```
**NOTE** : In unpacking of tuple number of variables on left hand side should be equal to number of values in given tuple a.
|
code/languages/python/tuple/example.py | def countX(tup, x):
count = 0
for ele in tup:
if (ele == x):
count = count + 1
return count
# Driver Code
tup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
enq = 4
enq1 = 10
enq2 = 8
print(countX(tup, enq))
print(countX(tup, enq1))
print(countX(tup, enq2))
|
code/languages/python/validate-parentheses/README.md | # Validate Parentheses
## Summary
Give a string containing just the characters: ( ) [ ] { } and determine if the input string is valid
## Example
([(){()}()]) --> Valid
({[(])}({})) --> Invalid |
code/languages/python/validate-parentheses/validate-parentheses.py | def validateParentheses(parentheses):
queue=[]
for ch in parentheses:
#enqueue for open-character
if ch in ('(','{','['):
queue.append(ch)
#dequeue for close-character
elif ch in (')','}',']'):
pre_ch = queue.pop()
#Validate for matching pair open and close character
if ( ch==')' and pre_ch!='(' ) or ( ch==']' and pre_ch!='[' ) or ( ch=='}' and pre_ch!='{' ) :
return False
#any different character
else:
return False
#any remain character
if (len(queue) > 0):
return False
#Success
return True
parentheses = input('Enter a string to validate:')
print(validateParentheses(parentheses))
|
code/languages/python/web_programming/README.md | # Web Programming For Python Developer
It contains about or how the python language works as a web programming
### Get CO2 emission data from the UK CarbonIntensity API
- [Co2 Emission](co2_emission.py)
### Covid stats via path
This is to show simple COVID19 info fetching from worldometers site using lxml The main motivation to use lxml in place of bs4 is that it is faster and therefore. more convenient to use in Python web projects (e.g. Django or Flask-based)
- [Covid stats via xpath](covid_stats_via_xpath.py)
### Crawl Google results
- [Crawl google result](crawl_google_results.py)
### Current stock price
- [Current stock price](current_stock_price.py)
### Current weather
- [Current weather](current_weather.py)
### Daily Horoscope
- [Daily Horoscope](daily_horoscope.py)
### Get the site emails from URL
- [Email from url](emails_from_url.py)
### Fetch BBC NEWS
- [Fetch BBC NEWS](fetch_bbc_news.py)
### Fetch Github Info
Basic authentication using an API password is deprecated and will soon no longer work.
Visit [github info]( https://developer.github.com/changes/2020-02-14-deprecating-password-auth)
for more information around suggested workarounds and removal dates.
- [Fetch Github info](fetch_github_info.py)
### Scraping jobs given job title and location from indeed website
- [Fetch jobs](fetch_jobs.py)
### Get IMDB top 250 movies CSV
- [Get IMBDB top 250 movies CSV](get_imdb_top_250_movies_csv.py)
### GET top IMDB
- [Get IMDB Top](get_imdbtop.py)
### Instagram Crawler
- [Instagram crawler](instagram_crawler.py)
### Recaptcha Verification
Below a Django function for the views.py file contains a login form for demonstrating
recaptcha verification.
- [Recaptcha verification](recaptcha_verification.py)
### Slack Message
- [Slack Message](slack_message.py)
### Get world Covid19 stats
Provide the current worldwide COVID-19 statistics.
This data is being scrapped from 'https://www.worldometers.info/coronavirus/'.
- [World Covid19 stats](world_covid19_stats.py) |
code/languages/python/web_programming/__init__.py | |
code/languages/python/web_programming/co2_emission.py | """Get CO2 emission data from the UK CarbonIntensity API"""
__author__ = "Danang Haris Setiawan"
__email__ = "[email protected]"
__github__ = "https://github.com/danangharissetiawan/"
from datetime import date
import requests
BASE_URL = "https://api.carbonintensity.org.uk/intensity"
# Emission in the last half hour
def fetch_last_half_hour() -> str:
last_half_hour = requests.get(BASE_URL).json()["data"][0]
return last_half_hour["intensity"]["actual"]
# Emissions in a specific date range
def fetch_from_to(start, end) -> list:
return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"]
if __name__ == "__main__":
for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
print("from {from} to {to}: {intensity[actual]}".format(**entry))
print(f"{fetch_last_half_hour() = }")
|
code/languages/python/web_programming/covid_stats_via_xpath.py | """
This is to show simple COVID19 info fetching from worldometers site using lxml
* The main motivation to use lxml in place of bs4 is that it is faster and therefore
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
import requests
from lxml import html
covid_data = namedtuple("covid_data", "cases deaths recovered")
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
|
code/languages/python/web_programming/crawl_google_results.py | import sys
import webbrowser
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print("Googling.....")
url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
res = requests.get(url, headers={"UserAgent": UserAgent().random})
# res.raise_for_status()
with open("project1a.html", "wb") as out_file: # only for knowing the class
for data in res.iter_content(10000):
out_file.write(data)
soup = BeautifulSoup(res.text, "html.parser")
links = list(soup.select(".eZt8xd"))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get("href"))
else:
webbrowser.open(f"http://google.com{link.get('href')}")
|
code/languages/python/web_programming/current_stock_price.py | import requests
from bs4 import BeautifulSoup
def stock_price(symbol: str = "AAPL") -> str:
url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}"
soup = BeautifulSoup(requests.get(url).text, "html.parser")
class_ = "My(6px) Pos(r) smartphone_Mt(6px)"
return soup.find("div", class_=class_).find("span").text
if __name__ == "__main__":
for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
|
code/languages/python/web_programming/current_weather.py | import requests
APPID = "" # <-- Put your OpenWeatherMap appid here!
URL_BASE = "http://api.openweathermap.org/data/2.5/"
def current_weather(q: str = "Chicago", appid: str = APPID) -> dict:
"""https://openweathermap.org/api"""
return requests.get(URL_BASE + "weather", params=locals()).json()
def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict:
"""https://openweathermap.org/forecast5"""
return requests.get(URL_BASE + "forecast", params=locals()).json()
def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict:
"""https://openweathermap.org/api/one-call-api"""
return requests.get(URL_BASE + "onecall", params=locals()).json()
if __name__ == "__main__":
from pprint import pprint
while True:
location = input("Enter a location:").strip()
if location:
pprint(current_weather(location))
else:
break
|
code/languages/python/web_programming/daily_horoscope.py | import requests
from bs4 import BeautifulSoup
def horoscope(zodiac_sign: int, day: str) -> str:
url = (
"https://www.horoscope.com/us/horoscopes/general/"
f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}"
)
soup = BeautifulSoup(requests.get(url).content, "html.parser")
return soup.find("div", class_="main-horoscope").p.text
if __name__ == "__main__":
print("Daily Horoscope. \n")
print(
"enter your Zodiac sign number:\n",
"1. Aries\n",
"2. Taurus\n",
"3. Gemini\n",
"4. Cancer\n",
"5. Leo\n",
"6. Virgo\n",
"7. Libra\n",
"8. Scorpio\n",
"9. Sagittarius\n",
"10. Capricorn\n",
"11. Aquarius\n",
"12. Pisces\n",
)
zodiac_sign = int(input("number> ").strip())
print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n")
day = input("enter the day> ")
horoscope_text = horoscope(zodiac_sign, day)
print(horoscope_text)
|
code/languages/python/web_programming/emails_from_url.py | """Get the site emails from URL."""
__author__ = "Danang Haris Setiawan"
__email__ = "[email protected]"
__github__ = "https://github.com/danangharissetiawan/"
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class Parser(HTMLParser):
def __init__(self, domain: str):
HTMLParser.__init__(self)
self.data = []
self.domain = domain
def handle_starttag(self, tag: str, attrs: str) -> None:
"""
This function parse html to take takes url from tags
"""
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in data.
if value not in self.data:
url = parse.urljoin(self.domain, value)
self.data.append(url)
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
"""
This function get the main domain name
>>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'c.d'
>>> get_domain_name("Not a URL!")
''
"""
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
"""
>>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'a.b.c.d'
>>> get_sub_domain_name("Not a URL!")
''
"""
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list:
"""
This function takes url and return all valid urls
"""
# Get the base domain from the url
domain = get_domain_name(url)
# Initialize the parser
parser = Parser(domain)
try:
# Open URL
r = requests.get(url)
# pass the raw HTML to the parser to get links
parser.feed(r.text)
# Get links and loop through
valid_emails = set()
for link in parser.data:
# open URL.
# read = requests.get(link)
try:
read = requests.get(link)
# Get the valid email.
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
# If not in list then append it.
for email in emails:
valid_emails.add(email)
except ValueError:
pass
except ValueError:
exit(-1)
# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
print("\n".join(sorted(emails)))
|
code/languages/python/web_programming/fetch_bbc_news.py | import requests
_NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
def fetch_bbc_news(bbc_news_api_key: str) -> None:
# fetching a list of articles in json format
bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page["articles"], 1):
print(f"{i}.) {article['title']}")
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
|
code/languages/python/web_programming/fetch_github_info.py | """
Basic authentication using an API password is deprecated and will soon no longer work.
Visit https://developer.github.com/changes/2020-02-14-deprecating-password-auth
for more information around suggested workarounds and removal dates.
"""
import requests
_GITHUB_API = "https://api.github.com/user"
def fetch_github_info(auth_user: str, auth_pass: str) -> dict:
"""
Fetch GitHub info of a user using the requests module
"""
return requests.get(_GITHUB_API, auth=(auth_user, auth_pass)).json()
if __name__ == "__main__":
for key, value in fetch_github_info("<USERNAME>", "<PASSWORD>").items():
print(f"{key}: {value}")
|
code/languages/python/web_programming/fetch_jobs.py | """
Scraping jobs given job title and location from indeed website
"""
from __future__ import annotations
from typing import Generator
import requests
from bs4 import BeautifulSoup
url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l="
def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]:
soup = BeautifulSoup(requests.get(url + location).content, "html.parser")
# This attribute finds out all the specifics listed in a job
for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}):
job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip()
company_name = job.find("span", {"class": "company"}).text.strip()
yield job_title, company_name
if __name__ == "__main__":
for i, job in enumerate(fetch_jobs("Bangalore"), 1):
print(f"Job {i:>2} is {job[0]} at {job[1]}")
|
code/languages/python/web_programming/get_imdb_top_250_movies_csv.py | from __future__ import annotations
import csv
import requests
from bs4 import BeautifulSoup
def get_imdb_top_250_movies(url: str = "") -> dict[str, float]:
url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250"
soup = BeautifulSoup(requests.get(url).text, "html.parser")
titles = soup.find_all("td", attrs="titleColumn")
ratings = soup.find_all("td", class_="ratingColumn imdbRating")
return {
title.a.text: float(rating.strong.text)
for title, rating in zip(titles, ratings)
}
def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None:
movies = get_imdb_top_250_movies()
with open(filename, "w", newline="") as out_file:
writer = csv.writer(out_file)
writer.writerow(["Movie title", "IMDb rating"])
for title, rating in movies.items():
writer.writerow([title, rating])
if __name__ == "__main__":
write_movies()
|
code/languages/python/web_programming/get_imdbtop.py | import requests
from bs4 import BeautifulSoup
def imdb_top(imdb_top_n):
base_url = (
f"https://www.imdb.com/search/title?title_type="
f"feature&sort=num_votes,desc&count={imdb_top_n}"
)
source = BeautifulSoup(requests.get(base_url).content, "html.parser")
for m in source.findAll("div", class_="lister-item mode-advanced"):
print("\n" + m.h3.a.text) # movie's name
print(m.find("span", attrs={"class": "genre"}).text) # genre
print(m.strong.text) # movie's rating
print(f"https://www.imdb.com{m.a.get('href')}") # movie's page link
print("*" * 40)
if __name__ == "__main__":
imdb_top(input("How many movies would you like to see? "))
|
code/languages/python/web_programming/instagram_crawler.py | #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on Travis CI)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = requests.get(self.url, headers=headers).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
from os import getenv
if getenv("CONTINUOUS_INTEGRATION"):
return # test failing on Travis CI
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "[email protected]"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
|
code/languages/python/web_programming/recaptcha_verification.py | """
Recaptcha is a free captcha service offered by Google in order to secure websites and
forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha
keys and see the keys that your have already created.
* Keep in mind that recaptcha doesn't work with localhost
When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey.
ClientKey should be kept in your site's front end
SecretKey should be kept in your site's back end
# An example HTML login form with recaptcha tag is shown below
<form action="" method="post">
<h2 class="text-center">Log in</h2>
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" required="required">
</div>
<div class="form-group">
<button type="submit">Log in</button>
</div>
<!-- Below is the recaptcha tag of html -->
<div class="g-recaptcha" data-sitekey="ClientKey"></div>
</form>
<!-- Below is the recaptcha script to be kept inside html tag -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Below a Django function for the views.py file contains a login form for demonstrating
recaptcha verification.
"""
import requests
try:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
except ImportError:
authenticate = login = render = redirect = print
def login_using_recaptcha(request):
# Enter your recaptcha secret key here
secret_key = "secretKey"
url = "https://www.google.com/recaptcha/api/siteverify"
# when method is not POST, direct user to login page
if request.method != "POST":
return render(request, "login.html")
# from the frontend, get username, password, and client_key
username = request.POST.get("username")
password = request.POST.get("password")
client_key = request.POST.get("g-recaptcha-response")
# post recaptcha response to Google's recaptcha api
response = requests.post(url, data={"secret": secret_key, "response": client_key})
# if the recaptcha api verified our keys
if response.json().get("success", False):
# authenticate the user
user_in_database = authenticate(request, username=username, password=password)
if user_in_database:
login(request, user_in_database)
return redirect("/your-webpage")
return render(request, "login.html")
|
code/languages/python/web_programming/slack_message.py | import requests
def send_slack_message(message_body: str, slack_url: str) -> None:
headers = {"Content-Type": "application/json"}
response = requests.post(slack_url, json={"text": message_body}, headers=headers)
if response.status_code != 200:
raise ValueError(
f"Request to slack returned an error {response.status_code}, "
f"the response is:\n{response.text}"
)
if __name__ == "__main__":
# Set the slack url to the one provided by Slack when you create the webhook at
# https://my.slack.com/services/new/incoming-webhook/
send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
|
code/languages/python/web_programming/world_covid19_stats.py | #!/usr/bin/env python3
"""
Provide the current worldwide COVID-19 statistics.
This data is being scrapped from 'https://www.worldometers.info/coronavirus/'.
"""
import requests
from bs4 import BeautifulSoup
def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict:
"""
Return a dict of current worldwide COVID-19 statistics
"""
soup = BeautifulSoup(requests.get(url).text, "html.parser")
keys = soup.findAll("h1")
values = soup.findAll("div", {"class": "maincounter-number"})
keys += soup.findAll("span", {"class": "panel-title"})
values += soup.findAll("div", {"class": "number-table-main"})
return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)}
if __name__ == "__main__":
print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n")
for key, value in world_covid19_stats().items():
print(f"{key}\n{value}\n")
|
code/mathematical_algorithms/mathematical_algorithms/Solve_Pi/README.md | # Use random points to calculate PI (Estimate)
## Summary
Given number randow points that x and y coordinations are less than 1 unit.
Find compute PI (estimate)
## Solve
- Let draw a square with size 2 units
- Let draw a circle with radius 1 unit inside the square
- Area of the square = size * size = 2 * 2 = 4
- Area of the circle = Pi * radius * radius = Pi * 1 * 1 = Pi
- x and y uniform random less than 1 so the ratio
Area of the circle / Area of the square = number points inside circle / total points
- Known x * x + y * y <= 1 then (x,y) is inside cirle
- Therefore: Pi/4 = number points inside circle / total points
**Pi = 4 * number points inside circle / total points**
### Let write the solution in Python
|
code/mathematical_algorithms/mathematical_algorithms/Solve_Pi/Solve_Pi.py | import numpy as np
# given n in 1000 points. The large number n then Pi (estimate) is more accurate value
n = int(input("Enter number random points (000):"))*1000
# random uniform
x=np.random.uniform(0,1,n)
y=np.random.uniform(0,1,n)
# get (x,y) points
xy = zip(x,y)
# number in the circle
inside_cirles =sum([1 if (p[0]**2+p[1]**2)<=1 else 0 for p in xy])
# result
print(f"Pi (estimate) = {4*inside_cirles/n}") |
code/mathematical_algorithms/mathematical_algorithms/Solve_Sum_2PositiveIntegers/README.md | # Sum of two large positive integer numbers (100+ digits)
## Summary
There is no premitive data type to hold an interger number with 100 plus digits.
Write a program to add 2 large positive integer numbers
## Solve
- Solve this problem is very simple way like elementary school teacher teach
- Add two digits from far right to left
- If more than 10, then add 1 into next addition
**Let solve the problem in Python** |
code/mathematical_algorithms/mathematical_algorithms/Solve_Sum_2PositiveIntegers/Sum_2largeNumbers.py | a = input("Enter 1st number: ")
b = input("Enter 2nd number: ")
if (a.isdigit() and b.isdigit()):
m=0
sum=""
n1 = list(a)
n2 = list(b)
while True:
#Take far right digits
digit1 = n1.pop() if len(n1) > 0 else None
digit2 = n2.pop() if len(n2) > 0 else None
#no more digit to take escape
if ( digit1 == None and digit2 == None):
break
#still a digit in sencond
elif digit1 == None:
sum_digit = int(digit2) + m
#still a digit in first
elif digit2 == None:
sum_digit = int(digit1) + m
# both have a digit
else:
sum_digit = int(digit1) + int(digit2) + m
# remember 1 if greater than 10
m = sum_digit//10
# add the digit to sum string
sum = str(sum_digit%10) + sum
# make sure add 1 to sum string if needs
sum = (str(m) if m==1 else "") + sum
# output
print(f"Sum is {sum}")
|
code/mathematical_algorithms/mathematical_algorithms/Solve_x_y/FindX_Y.py | import math
print("Find (x, y) solutions for 1/x + 1/y=1/n")
# Input N
n = int(input("Enter a positive integer (n):"))
# Smallest y
y = n+1
# Calculate x
x = (n*y)/(y-n)
# loop to find solutions
while (x>=y):
# x is a position integer, then a solution is found
if (x.is_integer()):
x_int = math.floor(x)
print(f"(x={x_int},y={y}) solution for 1/{n} = 1/{x_int}+1/{y}")
# new y
y += 1
# new x
x = (n*y)/(y-n)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.