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 (...
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<I...
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)...
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(...
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 (...
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]...
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)...
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(mes...
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 ...
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/els...
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...
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 ...
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]); ...
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...
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"); pri...
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] == ...
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) { ...
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) { struc...
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 in...
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 variab...
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) ...
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...
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 i...
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...
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) { re...
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 las...
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; retur...
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 ...
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 =...
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 '-'...
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. fre...
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 reallocat...
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 sto...
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 i...
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 respe...
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...
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 mul...
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.ins...
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]; ...
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 w...
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 ...
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(vo...
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) { ...
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...
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 ca...
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...
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 point...
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...
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...
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 ...
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....
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. Ea...
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...
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); ...
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:** In...
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...
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 create...
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...
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...
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 & ...
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() =...
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...
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 # Instanc...
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']+'===============================================...
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 tu...
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 pa...
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...
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__ = "mr.danangharissetiawan@gmail.com" __github__ = "https://github.com/danangharissetiawan/" from datetime import date import requests BASE_URL = "https://api.carbonintensity.org.uk/intensity" # Emission in th...
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 htm...
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.r...
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_).fi...
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_...
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 so...
code/languages/python/web_programming/emails_from_url.py
"""Get the site emails from URL.""" __author__ = "Danang Haris Setiawan" __email__ = "mr.danangharissetiawan@gmail.com" __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...
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...
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_g...
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...
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...
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",...
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...
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,...
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 retur...
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...
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...
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]...
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 ...
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...
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...