code-rag-bench/online-tutorials huggingface dataset:
Non-Restoring Division For Unsigned Integer - GeeksforGeeks

04 Oct, 2018
In earlier post Restoring Division learned about restoring division. Now, here perform Non-Restoring division, it is less complex than the restoring one because simpler operation are involved i.e. addition and subtraction, also now restoring step is performed. In the method, rely on the sign bit of the register which initially contain zero named as A.
Here is the flow chart given below.
Let’s pick the step involved:
Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend)
Step-2: Check the sign bit of register A
Step-3: If it is 1 shift left content of AQ and perform A = A+M, otherwise shift left AQ and perform A = A-M (means add 2’s complement of M to A and store it to A)
Step-4: Again the sign bit of register A
Step-5: If sign bit is 1 Q[0] become 0 otherwise Q[0] become 1 (Q[0] means least significant bit of register Q)
Step-6: Decrements value of N by 1
Step-7: If N is not equal to zero go to Step 2 otherwise go to next step
Step-8: If sign bit of A is 1 then perform A = A+M
Step-9: Register Q contain quotient and A contain remainderExamples: Perform Non_Restoring Division for Unsigned IntegerDividend =11
Divisor  =3  
-M =11101
NMAQAction400011000001011Start00001011_Left shift AQ11110011_A=A-M3111100110Q[0]=011100110_Left shift AQ11111110_A=A+M2111111100Q[0]=011111100_Left Shift AQ00010100_A=A+M1000101001Q[0]=100101001_Left Shift AQ00010001_A=A-M0000100011Q[0]=1Quotient  = 3 (Q)
Remainder = 2 (A)
My Personal Notes
arrow_drop_upSave
Examples: Perform Non_Restoring Division for Unsigned Integer
Dividend =11
Divisor  =3  
-M =11101

Quotient  = 3 (Q)
Remainder = 2 (A)

SubhajitNandi
utkarshkalia
Computer Organization & Architecture
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cache Memory in Computer Organization
Addressing Modes
Logical and Physical Address in Operating System
Computer Organization | RISC and CISC
Random Access Memory (RAM) and Read Only Memory (ROM)
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Introduction to memory and memory units
Difference between RAM and ROM
Find maximum difference between nearest left and right smaller elements in Python

Suppose we have an array of integers; we have to find the maximum absolute difference between the nearest left and the right smaller element of each of the elements in the array. If there is no smaller element on the right-hand side or left-hand side of any element then we will put zero as the smaller element.
So, if the input is like A = [3, 5, 9, 8, 8, 10, 4], then the output will be 4 as left elements L = [0, 3, 5, 5, 5, 8, 3], right elements R = [0, 4, 8, 4, 4, 4, 0], maximum absolute difference L[i] - R[i] = 8 - 4 = 4.
To solve this, we will follow these steps −
Define a function left_small_element() . This will take A, temp
Define a function left_small_element() . This will take A, temp
n := size of A
n := size of A
stack := a new list
stack := a new list
for i in range 0 to n, dowhile stack is not empty and top element of stack >= A[i], dodelete last element from stackif stack is not empty, thentemp[i]:= top element of stackotherwise,temp[i]:= 0insert A[i] at the end of stack
for i in range 0 to n, do
while stack is not empty and top element of stack >= A[i], dodelete last element from stack
while stack is not empty and top element of stack >= A[i], do
delete last element from stack
delete last element from stack
if stack is not empty, thentemp[i]:= top element of stack
if stack is not empty, then
temp[i]:= top element of stack
temp[i]:= top element of stack
otherwise,temp[i]:= 0
otherwise,
temp[i]:= 0
temp[i]:= 0
insert A[i] at the end of stack
insert A[i] at the end of stack
From the main method, do the following −
From the main method, do the following −
n := size of A
n := size of A
left:= a list of size n and fill with 0
left:= a list of size n and fill with 0
right:= a list of size n and fill with 0
right:= a list of size n and fill with 0
left_small_element(A, left)
left_small_element(A, left)
left_small_element(reversed A, right)
left_small_element(reversed A, right)
res := -1
res := -1
for i in range 0 to n, dores := maximum of res, |left[i] - right[n-1-i]|
for i in range 0 to n, do
res := maximum of res, |left[i] - right[n-1-i]|
res := maximum of res, |left[i] - right[n-1-i]|
Let us see the following implementation to get better understanding −
 Live Demo
def left_small_element(A, temp):
   n = len(A)
   stack = []
   for i in range(n):
      while(stack != [] and stack[len(stack)-1] >= A[i]):
         stack.pop()
      if(stack != []):
         temp[i]=stack[len(stack)-1]
      else:
         temp[i]=0
      stack.append(A[i])
def find_maximum_difference(A):
   n = len(A)
   left=[0]*n
   right=[0]*n
   left_small_element(A, left)
   left_small_element(A[::-1], right)
   res = -1
   for i in range(n):
      res = max(res, abs(left[i] - right[n-1-i]))
   return res
A = [3, 5, 9, 8, 8, 10, 4]
print(find_maximum_difference(A))
[3, 5, 9, 8, 8, 10, 4]
4
JSTL - Core <c:param> Tag

The <c:param> tag allows proper URL request parameter to be specified with URL and also does the necessary URL encoding required.
Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute indicates the parameter value −
The <c:param> tag has the following attributes −
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as shown below −
<c:url value = "/index.jsp" var = "myURL">
   <c:param name = "trackingId" value = "1234"/>
   <c:param name = "reportType" value = "summary"/>
</c:url>
<c:import url = "${myURL}"/>
The above request will pass the URL as below - Try it yourself.
"/index.jsp?trackingId=1234;reportType=summary"


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Difference between process.cwd() and __dirname in Node.js - GeeksforGeeks

23 Feb, 2021
NodeJS is a JavaScript runtime that was built on top of Chrome’s V8 Engine. The traditional JavaScript is executed in browsers but with Node.js we can execute JavaScript on servers, hardware devices, etc.
process.cwd(): Similar to window objects on browsers, Node.js has got a global object called global, and the process object lies inside the global object. This process object provides information about, and control over, the current Node.js process. It gives the current working directory of the Node.js process.
__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
Difference between process.cwd() vs __dirname in Node.js is as follows:
Example 1:
index.js
// Logging process.cwd() outputconsole.log("process.cwd(): ", process.cwd());  // Logging __dirname outputconsole.log("__dirname: ", __dirname);
Run the index.js file using the following command:
node index.js
Output:
process.cwd(): C:\src
__dirname: C:\src
In this case node process is running in the current directory
Example 2: Create the following 2 files with the following folder structure:
src/
___ index.js
___ src2/
    ___index2.js
FilePath: src/index.js
index.js
// Read and execute the index2.js file require('./sub1/index2.js')
FilePath: src/src2/index2.js
index2.js
// Logging process.cwd() outputconsole.log("process.cwd(): ", process.cwd());  // Logging __dirname outputconsole.log("__dirname: ", __dirname);
Run the index.js file using the following command:
node index2.js
Output:
process cwd:  C:\src
__dirname:  C:\src\src2
This shows that the current node process was running in src/ folder i.e node index.js and the directory of the file index2.js was at src/src2.
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
How to build a basic CRUD app with Node.js and ReactJS ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
What is the syntax for passing Scanner object as a parameter in a method using java?

Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes.
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.
By default, whitespace is considered as the delimiter (to break the data into tokens).
To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().
You can pass Scanner object to a method as a parameter.
The following Java program demonstrates how to pass a Scanner object to a method. This object reads the contents of a file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ScannerExample {
   public String sampleMethod(Scanner sc){
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.nextLine());
      }
      return sb.toString();
   }
   public static void main(String args[]) throws IOException {
      //Instantiating the inputStream class
      InputStream stream = new FileInputStream("D:\\sample.txt");
      //Instantiating the Scanner class
      Scanner sc = new Scanner(stream);
      ScannerExample obj = new ScannerExample();
      //Calling the method
      String result = obj.sampleMethod(sc);
      System.out.println("Contents of the file:");
      System.out.println(result);
   }
}
Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line
content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
In the following example, we creating a Scanner object which has Standard input (System.in) as source and passing it as a parameter to a method.
import java.io.IOException;
import java.util.Scanner;
public class ScannerExample {
   public void sampleMethod(Scanner sc){
      StringBuffer sb = new StringBuffer();
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your age: ");
      String age = sc.next();
      System.out.println("Hello "+name+" You are "+age+" years old");
   }
   public static void main(String args[]) throws IOException {
      //Instantiating the Scanner class
      Scanner sc = new Scanner(System.in);
      ScannerExample obj = new ScannerExample();
      //Calling the method
      obj.sampleMethod(sc);
   }
}
Enter your name:
Krishna
Enter your age:
25
Hello Krishna You are 25 years old
Ways to sum to N using array elements with repetition allowed in C++

In this problem, we are given an array of integers and a number N. Our task is to count the total number of ways N can be generated by adding elements of the array. All combinations and repetitions are allowed.
Let’s take an example to understand the problem,
arr = {1, 3, 5} N = 6
8
The ways are −
5+1, 1+5, 3+3, 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3, 1+1+1+1+1+1
To solve this problem, we need to use a different approach as all types of combinations will be treated differently so, if the number is a sum of 4 elements of array 4 different ways are considered(as shown in example). For solve such a problem, we need to use dynamic programming approach and the below program will show the implementation.
 Live Demo
#include <iostream>
#include <cstring>
using namespace std;
int arraySumWays(int array[], int size, int N){
   int count[N + 1];
   memset(count, 0, sizeof(count));
   count[0] = 1;
   for (int i = 1; i <= N; i++)
      for (int j = 0; j < size; j++)
         if (i >= array[j])
            count[i] += count[i - array[j]];
   return count[N];
}
int main() {
   int array[] = {1, 5, 6};
   int size = sizeof(array) / sizeof(array[0]);
   int N = 7;
   cout<<"Total number of ways inwhich "<<N<<" can be generated using sum of elements of array is "      <<arraySumWays(array, size, N);
   return 0;
}
Total number of ways inwhich 7 can be generated using sum of elements of array is 6
Python | Split on last occurrence of delimiter

25 Jun, 2022
The splitting of strings has always been discussed in various applications and use cases. One of the interesting variations of list splitting can be splitting the list on delimiter but this time only on the last occurrence of it. Let’s discuss certain ways in which this can be done.
Method #1: Using rsplit(str, 1) The normal string split can perform the split from the front, but Python also offers another method that can perform this very task from the rear end, hence increasing the versatility of applications. 
Python3
# Python3 code to demonstrate# Split on last occurrence of delimiter# using rsplit() # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string)) # using rsplit()# Split on last occurrence of delimiterres = test_string.rsplit(', ', 1) # print resultprint("The splitted list at the last comma : " + str(res))
The original string : gfg, is, good, better, and best
The splitted list at the last comma : ['gfg, is, good, better', 'and best']
  Method #2: Using rpartition() This function can also perform the desired reverse partition, but the drawbacks to using this is the construction of additional delimiter value and also the speed is slower than the above method and hence not recommended. 
Python3
# Python3 code to demonstrate# Split on last occurrence of delimiter# using rpartition() # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string)) # using rpartition()# Split on last occurrence of delimiterres = test_string.rpartition(', ') # print resultprint("The splitted list at the last comma : " + str(res))
The original string : gfg, is, good, better, and best
The splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best')
Method #3 : Using split() and replace() methods.
Python3
# Python3 code to demonstrate# Split on last occurrence of delimiter  # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string))  # Split on last occurrence of delimiterp=test_string.count(",")c=0new=""for i in test_string:    if(i=="," and c<p-1):        new+="*"        c+=1    else:        new+=ix=new.split(",")  x[0]=x[0].replace("*",",") # print resultprint("The splitted list at the last comma : " + str(x))
The original string : gfg, is, good, better, and best
The splitted list at the last comma : ['gfg, is, good, better', ' and best']
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Group Similar items to Dictionary Values List

29 Apr, 2022
Given a list of elements, perform grouping of similar elements, as different key-value list in dictionary.
Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences. Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Explanation : Similar items grouped together on occurrences.
Method #1 : Using defaultdict() + loop
This is one of the ways in which this task can be performed. In this, we construct a defaultdict() with default list and keep appending similar values into similar list.
Python3
# Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using defaultdict + loopfrom collections import defaultdict # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint("The original list : " + str(test_list)) # using defaultdict for default listres = defaultdict(list)for ele in test_list:         # appending Similar values    res[ele].append(ele) # printing resultprint("Similar grouped dictionary : " + str(dict(res)))
The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}
Method #2 : Using dictionary comprehension + Counter()
This is yet another way in which this task can be performed. In this, we extract frequency using Counter() and then repeat occurrences using multiplication.
Python3
# Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using dictionary comprehension + Counter()from collections import Counter # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint("The original list : " + str(test_list)) # using * operator to perform multiplicationres = {key : [key] * val for key, val in Counter(test_list).items()} # printing resultprint("Similar grouped dictionary : " + str(res))
The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}
ajmalhussain410
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
TCS Coding Practice Question | Average of 2 Numbers

09 Apr, 2019
Given two numbers, the task is to find the average of two numbers using Command Line Arguments.
Examples:
Input: n1 = 10, n2 = 20
Output: 15

Input: n1 = 100, n2 = 200
Output: 150

Approach:
Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line
Extract the input numbers from the command line argument
This extracted numbers will be in String type.
Convert these numbers into integer type and store it in variables, say num1 and num2
Find the average of the numbers using the formula ((num1 + num2)/2)
Print or return the average
Program:
C
Java
// C program to compute the average of two numbers// using command line arguments  #include <stdio.h>#include <stdlib.h> /* atoi */  // Function to compute the average of two numbersint average(int a, int b){    return (a + b) / 2;}  // Driver codeint main(int argc, char* argv[]){      int num1, num2;      // Check if the length of args array is 1    if (argc == 1)        printf("No command line arguments found.\n");      else {          // Get the command line argument and        // Convert it from string type to integer type        // using function "atoi( argument)"        num1 = atoi(argv[1]);        num2 = atoi(argv[2]);          // Find the average and print it        printf("%d\n", average(num1, num2));    }    return 0;}
// Java program to compute the average of two numbers// using command line arguments  class GFG {      // Function to compute the average of two numbers    static int average(int a, int b)    {        return (a + b) / 2;    }      // Driver code    public static void main(String[] args)    {          // Check if length of args array is        // greater than 0        if (args.length > 0) {              // Get the command line argument and            // Convert it from string type to integer type            int num1 = Integer.parseInt(args[0]);            int num2 = Integer.parseInt(args[1]);              // Find the average            int res = average(num1, num2);              // Print the average            System.out.println(res);        }        else            System.out.println("No command line "                               + "arguments found.");    }}
In C:
In Java:
TCS
TCS-coding-questions
C++ Programs
Java Programs
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to implement Singly Linked List in C++ using class
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Dynamic _Cast in C++
MD5 hash in Java
Java Programming Examples
Convert a String to Character Array in Java
Initializing a List in Java
How to Sort a LinkedList in Java?
The yield Keyword in Ruby

18 Oct, 2019
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method.
Simple Yield: When the yield keyword used inside the body of a method, will allow us to call that method with a block of code. Below is simple yield program to understand.
# Ruby program of using yield keyworddef geeks   puts "In the geeks method"     # using yield keyword   yield   puts "Again back to the geeks method"   yieldendgeeks {puts "This is block"}
Output:
In the geeks method
This is block
Again back to the geeks method
This is block
 Yield with argument: Below is the program of yield with argument.
# Ruby program of using yield keyword # with argumentdef gfg   yield 2*3   puts "In the method gfg"   yield 100endgfg {|i| puts "block #{i}"}
Output :
block 6
In the method gfg
block 100
In above example, the yield statement is written followed by parameters. we can even pass more than one parameter after yield. To accept the parameters we placed a variable(i) between two vertical lines (||).
Yield with Return value: It is possible to get the return value of a block by simply assigning the return value of a yield to a variable. if we use yield with an argument, it will pass that argument to the block.
# Ruby program of using yield keyword# with return valuedef yield_with_return_value  geeks_for_geeks = yield    puts geeks_for_geeksend  yield_with_return_value { "Welcome to geeksforgeeks" } 
Output:
Welcome to geeksforgeeks
The geeks_for_geeks variable get the “Welcome to geeksforgeeks” returned by the block and display it by using puts.
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Zip different sized list

07 Feb, 2019
In Python, zipping is a utility where we pair one list with the other. Usually, this task is successful only in the cases when the sizes of both the lists to be zipped are of the same size. But sometimes we require that different sized lists also to be zipped. Let’s discuss certain ways in which this problem can be solved if it occurs.
Method #1 : Using enumerate() + loopThis is the way in which we use the brute force method to achieve this particular task. In this process, we loop both the list and when one becomes larger than other we cycle the elements to begin them from the beginning.
# Python3 code to demonstrate # zipping of two different size list # using enumerate() + loop  # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6]  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using enumerate() + loop# zipping of two different size list res = []for i, j in enumerate(test_list1):    res.append((j, test_list2[i % len(test_list2)]))  # printing result print ("The zipped list is : " +  str(res))
The original list 1 is : [7, 8, 4, 5, 9, 10]
The original list 2 is : [1, 5, 6]
The zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]

 Method #2 : Using itertools.cycle()This is yet another way to perform this particular task, in this we cycle the smaller list so that it can begin zipping from beginning in case the smaller list gets exhausted using a zip function.
# Python3 code to demonstrate # zipping of two different size list # using itertools.cycle()from itertools import cycle  # initializing liststest_list1 = [7, 8, 4, 5, 9, 10]test_list2 = [1, 5, 6]  # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # using itertools.cycle()# zipping of two different size list res = list(zip(test_list1, cycle(test_list2))            if len(test_list1) > len(test_list2)            else zip(cycle(test_list1), test_list2))  # printing result print ("The zipped list is : " +  str(res))
The original list 1 is : [7, 8, 4, 5, 9, 10]
The original list 2 is : [1, 5, 6]
The zipped list is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to zip a Python Dictionary and List together?

The zip() function can be used to zip one key-value pair from dictionary and correspoinding item in a list together
>>> dictionary = {'A':1, 'B':2, 'C':3}
>>> num_list = [1, 2, 3]
>>> zipped = zip(dictionary.items(), num_list)
>>> zipped
<zip object at 0x000000886641B9C8>
This zipped object when converted to list, shows following output
>>> list(zipped)
[(('A', 1), 1), (('B', 2), 2), (('C', 3), 3)]
How to use Typography Component in ReactJS?

05 Mar, 2021
Use typography to present your design and content as clearly and efficiently as possible. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Typography Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldernam.
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Typography from "@material-ui/core/Typography";  export default function App() {  return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to use Typography Component in ReactJS?</h4>      <Typography variant="h4" gutterBottom>        GeeksforGeeks with Typography Component      </Typography>        <h4>GeeksforGeeks without Typography Component</h4>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/typography/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
PyQt5 – QTableWidget

11 May, 2020
In this article, we will learn how to add and work with a table in our PyQt5 application. A table is an arrangement of data in rows and columns and widely used in communication, research, and data analysis. We can add one or more tables in our PyQt application using QTableWidget.
For a better understanding of the concept, we will take an example where we want to display the name and the city of different people in a table in our application. We can extract the data from a database, JSON file, or any other storage platform.
Example:
import sysfrom PyQt5.QtWidgets import *                        #Main Windowclass App(QWidget):    def __init__(self):        super().__init__()        self.title = 'PyQt5 - QTableWidget'        self.left = 0        self.top = 0        self.width = 300        self.height = 200           self.setWindowTitle(self.title)        self.setGeometry(self.left, self.top, self.width, self.height)           self.createTable()           self.layout = QVBoxLayout()        self.layout.addWidget(self.tableWidget)        self.setLayout(self.layout)           #Show window        self.show()       #Create table    def createTable(self):        self.tableWidget = QTableWidget()          #Row count        self.tableWidget.setRowCount(4)           #Column count        self.tableWidget.setColumnCount(2)            self.tableWidget.setItem(0,0, QTableWidgetItem("Name"))        self.tableWidget.setItem(0,1, QTableWidgetItem("City"))        self.tableWidget.setItem(1,0, QTableWidgetItem("Aloysius"))        self.tableWidget.setItem(1,1, QTableWidgetItem("Indore"))        self.tableWidget.setItem(2,0, QTableWidgetItem("Alan"))        self.tableWidget.setItem(2,1, QTableWidgetItem("Bhopal"))        self.tableWidget.setItem(3,0, QTableWidgetItem("Arnavi"))        self.tableWidget.setItem(3,1, QTableWidgetItem("Mandsaur"))           #Table will fit the screen horizontally        self.tableWidget.horizontalHeader().setStretchLastSection(True)        self.tableWidget.horizontalHeader().setSectionResizeMode(            QHeaderView.Stretch)   if __name__ == '__main__':    app = QApplication(sys.argv)    ex = App()    sys.exit(app.exec_())
Output:
Python-gui
Python-PyQt
Project
Python
Python Programs
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
10 Best Web Development Projects For Your Resume
OpenCV C++ Program for Face Detection
Simple Chat Room using Python
Twitter Sentiment Analysis using Python
Student Information Management System
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
PyQt5 - QComboBox Widget

A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item.
A Combo box can be set to be editable; it can also store pixmap objects. The following methods are commonly used −
addItem()
Adds string to collection
addItems()
Adds items in a list object
Clear()
Deletes all items in the collection
count()
Retrieves number of items in the collection
currentText()
Retrieves the text of currently selected item
itemText()
Displays text belonging to specific index
currentIndex()
Returns index of selected item
setItemText()
Changes text of specified index
The following methods are commonly used in QComboBox Signals −
activated()
When the user chooses an item
currentIndexChanged()
Whenever the current index is changed either by the user or programmatically
highlighted()
When an item in the list is highlighted
Let us see how some features of QComboBox widget are implemented in the following example.
Items are added in the collection individually by addItem() method or items in a List object by addItems() method.
self.cb.addItem("C++")
self.cb.addItems(["Java", "C#", "Python"])

QComboBox object emits currentIndexChanged() signal. It is connected to selectionchange() method.
Items in a combo box are listed using itemText() method for each item. Label belonging to the currently chosen item is accessed by currentText() method.
def selectionchange(self,i):
   print "Items in the list are :"
	
   for count in range(self.cb.count()):
      print self.cb.itemText(count)
   print "Current index",i,"selection changed ",self.cb.currentText()
The entire code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class combodemo(QWidget):
   def __init__(self, parent = None):
      super(combodemo, self).__init__(parent)
      
      layout = QHBoxLayout()
      self.cb = QComboBox()
      self.cb.addItem("C")
      self.cb.addItem("C++")
      self.cb.addItems(["Java", "C#", "Python"])
      self.cb.currentIndexChanged.connect(self.selectionchange)
		
      layout.addWidget(self.cb)
      self.setLayout(layout)
      self.setWindowTitle("combo box demo")

   def selectionchange(self,i):
      print "Items in the list are :"
		
      for count in range(self.cb.count()):
         print self.cb.itemText(count)
      print "Current index",i,"selection changed ",self.cb.currentText()
		
def main():
   app = QApplication(sys.argv)
   ex = combodemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()
The above code produces the following output −
Items in the list are −
C
C++
Java
C#
Python
Current selection index 4 selection changed Python
How to fill the area under a curve in a Seaborn distribution plot?

To fill the area under a curve in a Seaborn distribution plot, we can use distplot() and fill_between() methods.
Set the figure size and adjust the padding between and around the subplots.
Create a list of data points.
Plot a univariate distribution of observations.
To fill the area under the curve, use fill_between() method.
Set or retrieve autoscaling margins, x=0 and y=0.
To display the figure, use show() method.
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = [2.0, 7.5, 9.0, 8.5]
ax = sns.distplot(x, fit_kws={"color": "red"}, kde=False, fit=stats.gamma, hist=None, label="label 1")
l1 = ax.lines[0]

x1 = l1.get_xydata()[:, 0]
y1 = l1.get_xydata()[:, 1]

ax.fill_between(x1, y1, color="red", alpha=0.3)
ax.margins(x=0, y=0)

plt.show()
Matplotlib - Twin Axes

It is considered useful to have dual x or y axes in a figure. Moreso, when plotting curves with different units together. Matplotlib supports this with the twinxand twiny functions.
In the following example, the plot has dual y axes, one showing exp(x) and the other showing log(x) −
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
x = np.arange(1,11)
a1.plot(x,np.exp(x))
a1.set_ylabel('exp')
a2 = a1.twinx()
a2.plot(x, np.log(x),'ro-')
a2.set_ylabel('log')
fig.legend(labels = ('exp','log'),loc='upper left')
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Retrieving the first document in a MongoDB collection?

To retrieve the first document in a collection, you can use findOne(). Following is the syntax
var anyVariableName=db.yourCollectionName.findOne();
//To print result at MongoDB console write the variable name
yourVariableName
Let us first create a collection with documents
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2325966324ffac2a7dc6d")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2326266324ffac2a7dc6e")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2327566324ffac2a7dc70")
}
Following is the query to display all documents from a collection with the help of find() method
> db.retrieveFirstDocumentDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
   "ClientName" : "Robert",
   "ClientAge" : 23
}
{
   "_id" : ObjectId("5ca2326266324ffac2a7dc6e"),
   "ClientName" : "Chris",
   "ClientAge" : 26
}
{
   "_id" : ObjectId("5ca2326a66324ffac2a7dc6f"),
   "ClientName" : "Larry",
   "ClientAge" : 29
}
{
   "_id" : ObjectId("5ca2327566324ffac2a7dc70"),
   "ClientName" : "David",
   "ClientAge" : 39
}
Following is the query to retrieve first document in a collection
> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne();
> firstDocumentOnly;
This will produce the following output
{
   "_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
   "ClientName" : "Robert",
   "ClientAge" : 23
}
Haskell - Zippers

Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree.
Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right?
But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree.
In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure.
data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)
type Zipper_List a = ([a],[a])    

go_Forward :: Zipper_List a -> Zipper_List a   
go_Forward (x:xs, bs) = (xs, x:bs)   
   
go_Back :: Zipper_List a -> Zipper_List a   
go_Back (xs, b:bs) = (b:xs, bs)    

main = do 
   let list_Ex = [1,2,3,4] 
   print(go_Forward (list_Ex,[]))       
   print(go_Back([4],[3,2,1])) 
When you compile and execute the above program, it will produce the following output −
([2,3,4],[1]) 
([3,4],[2,1])

Here we are focusing on an element of the entire string while going forward or while coming backward.
 Print
 Add Notes
 Bookmark this page
Can we fetch multiple values with MySQL WHERE Clause?

Yes, we can fetch, but use MySQL OR for conditions. Let us first create a −
mysql> create table DemoTable1421
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20),
   -> EmployeeSalary int
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Chris',10000);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Bob',15000);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('David',8000);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Carol',8500);
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable1421(EmployeeName,EmployeeSalary) values('Mike',14500);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select −
mysql> select * from DemoTable1421;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
|          1 | Chris       |           10000 |
|          2 | Bob         |           15000 |
|          3 | David       |            8000 |
|          4 | Carol       |            8500 |
|          5 | Mike        |           14500 |
+------------+--------------+----------------+
5 rows in set (0.00 sec)
Here is the query to fetch multiple values with OR −
mysql> select * from DemoTable1421 where EmployeeId=1 OR EmployeeName='David' OR EmployeeSalary=14500;
This will produce the following output −
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
|          1 | Chris        |          10000 |
|          3 | David        |           8000 |
|          5 | Mike         |          14500 |
+------------+--------------+----------------+
3 rows in set (0.00 sec)
Python - Directory Listing

Python can be used to get the list of content from a directory. We can make program to list the content of directory which is in the same machine where python is running.
We can also login to the remote system and list the content from the remote directory.
In the below example we use the listdir() method to get the content of the current directory. To also indicate the type of the content like 
file or directory, we use more functions to evaluate the nature of the content.
for  name in os.listdir('.'):
    if os.path.isfile(name): print 'file: ', name
    elif os.path.isdir(name): print 'dir: ', name
    elif os.path.islink(name): print 'link: ', name
    else: print 'unknown', name
When we run the above program, we get the following output −
file: abcl.htm
dir: allbooks
link: ulink

Please note the content above is specific to the system where the python program was run. The result will vary depending on the system and its content.
We can list the content of the remote directory by using ftp to access the remote system. Once the connection is established we can use commands that will
list the directory contents in a way similar to the listing of local directories.
from ftplib import FTP
def main():
    ftp = FTP('ftp.ibiblio.org')
    ftp.login()
    ftp.cwd('pub/academic/biology/') # change to some other subject
    entries = ftp.nlst()
    ftp.quit()

    print(len(entries), "entries:")
    for entry in sorted(entries):
        print(entry)

if __name__ == '__main__':
    main()
When we run the above program, we get the following output −
(6, 'entries:')
INDEX
README
acedb
dna-mutations
ecology+evolution
molbio


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C# | How to get the HashCode for the string - GeeksforGeeks

01 Aug, 2019
GetHashCode() method is used to get the hash code of the specified string. When you apply this method to the string this method will return a 32-bit signed integer hash code of the given string.
Syntax:
public override int GetHashCode ();
Return Value: The return type of this method is System.Int32. This method return a 32-bit signed integer hash code.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# program to illustrate // the GetHashCode() methodusing System;  public class GFG {          // main method    static public void Main()    {        int s1, s2, s3;                  // strings        string a1 = "abc";        string a2 = "geeks";        string a3 = "gfg";          // Get hash code of the given string by        // using GetHashCode() method        s1 = a1.GetHashCode();        s2 = a2.GetHashCode();        s3 = a3.GetHashCode();          // display strings and their hash code        Console.WriteLine("Display strings");        Console.WriteLine("string 1: {0} and hashcode: {1}", a1, s1);        Console.WriteLine("string 2: {0} and hashcode: {1}", a2, s2);        Console.WriteLine("string 3: {0} and hashcode: {1}", a3, s3);    }}
Display strings
string 1: abc and hashcode: 1099313834
string 2: geeks and hashcode: -1893508949
string 3: gfg and hashcode: -870054572

Example 2:
// C# program to illustrate// the GetHashCode() methodusing System;  class GFG {          // main method    static public void Main()    {          // calling Hashcode method        Hashcode("Hello");        Hashcode("GFG");        Hashcode("Geeks");        Hashcode("Geeksforgeeks");        Hashcode("C#");        Hashcode("Tutorial");    }      // Hashcode method    public static void Hashcode(String value)    {        int result;          // get hash code of the entered strings        result = value.GetHashCode();        Console.WriteLine("String : {0} and HashCode: {1}", value, result);    }}
String : Hello and HashCode: -327378614
String : GFG and HashCode: 1999992308
String : Geeks and HashCode: -1893476149
String : Geeksforgeeks and HashCode: -2133923457
String : C# and HashCode: -1917577788
String : Tutorial and HashCode: 1463624248

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=netframework-4.7.2#definition
mayank5326
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
Plotly - Plotting Inline with Jupyter Notebook

In this chapter, we will study how to do inline plotting with the Jupyter Notebook.
In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows −
from plotly.offline import init_notebook_mode
init_notebook_mode(connected = True)

Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself.
import plotly
plotly.tools.set_credentials_file(username = 'lathkar', api_key = '************')
from plotly.offline import iplot, init_notebook_mode
init_notebook_mode(connected = True)

import plotly
import plotly.graph_objs as go
import numpy as np
import math #needed for definition of pi

xpoints = np.arange(0, math.pi*2, 0.05)
ypoints = np.sin(xpoints)
trace0 = go.Scatter(
   x = xpoints, y = ypoints
)
data = [trace0]
plotly.offline.iplot({ "data": data,"layout": go.Layout(title="Sine wave")})
Jupyter notebook output will be as shown below −
The plot output shows a tool bar at top right. It contains buttons for download as png, zoom in and out, box and lasso, select and hover.
How to set cell width and height in HTML?

To set the cell width and height, use the CSS style. The height and width attribute of the <td> cell isn’t supported in HTML5. Use the CSS property width and height to set the width and height of the cell respectively.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to set height and width to a table cell in HTML. We’re also using the <style> tag and the style attribute to style the table
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>
   
   <body>
      <h1>Tutorial</h1>
      <table>
         <tr>
            <th>Language</th>
            <th>Lessons</th>
         </tr>
         <tr>
            <td style="height:100px;width:100px">Java</td>
            <td style="height:100px;width:100px">50</td>
         </tr>
         <tr>
            <td>Ruby</td>
            <td>40</td>
         </tr>
      </table>
   </body>
</html>