code-rag-bench/online-tutorials huggingface dataset:
Nested Lambda Function in Python - GeeksforGeeks

08 Jun, 2020
Prerequisites: Python lambda
In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then it is called Nested Lambda Function.
Example 1:
# Python program to demonstrate# nested lambda functions    f = lambda a = 2, b = 3:lambda c: a+b+c  o = f()print(o(4))
Output:
9
Here, when the object o with parameter 4 is called, the control shift to f() which is caller object of the whole lambda function. Then the following execution takes place-
The nested lambda function takes the value of a and b from the first lambda function as a=2 and b=3.
It takes the value of c from its caller object o which passes c = 4.
Finally we get the output which is the summation of a, b and c that is 9.
Example 2:
# Python program to demonstrate# nested lambda functions    square = lambda x: x**2product = lambda f, n: lambda x: f(x)*n  ans = product(square, 2)(10)print(ans)
Output:
200
In the above example, when the product function is called square function gets bound to f and 2 gets bound to n which then returns a function which is bound to the product which when called with 10, x is assigned this and square is called, which returns 100 and this, in turn, is multiplied with n which is 2. So it’ll finally return 200.
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
GATE | GATE-CS-2014-(Set-3) | Question 21 - GeeksforGeeks

28 Jun, 2021
The minimum number of arithmetic operations required to evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given value of X using only one temporary variable.(A) 6(B) 7(C) 8(D) 9Answer: (B)Explanation:
P(X) = x5 + 4x3 + 6x + 5

     =x ( x4 + 4x2 + 6 ) +5

     =x ( x ( x3 + 4x ) + 6 ) + 5

     =x ( x ( x ( x2 + 4 ) ) + 6 ) + 5

     =x ( x ( x (x (x) + 4 ) ) + 6 ) + 5

Let T be a temporary variable to store intermediate results.

1. T = (x) * (x)
2. T = T + 4
3. T = (x) * (T)
4. T = (x) * (T)
5. T = T + 6
6. T = (x) * T
7. T = T + 5

Thus, we need 7 operations if we are to use only one temporary variable.
Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
not Keyword in Ruby - GeeksforGeeks

27 Jul, 2020
The keyword “not” is different from the others. The “not” keyword gets an expression and inverts its boolean value – so given a true condition it will return false. It works like “!” operator in Ruby, the only difference between “and” keyword and “!” operator is  “!” has the highest precedence of all operators, and “not” one of the lowest.
Syntax:
not expression


Example 1:
Ruby
# Ruby program to illustrate not keyworduname = "geeks"  # Using not keywordif not(uname == "Geeks" )puts "Incorrect username!"else  puts "Welcome, GeeksforGeeks!"end
 
Output:
Incorrect username!


Example 2: 
 
Ruby
# Ruby program to illustrate not keyworduname = "Geek"password = "Wel123"number = 123if not(uname == "Geek" &&        password == "Wel123" &&       number == 123)puts "Hey, Incorrect Credentials"else  puts "Welcome to GeeksforGeeks"  end
 
Output:
Welcome to GeeksforGeeks


Ruby Keyword
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
hostname command in Linux with examples - GeeksforGeeks

21 May, 2019
hostname command in Linux is used to obtain the DNS(Domain Name System) name and set the system’s hostname or NIS(Network Information System) domain name. A hostname is a name which is given to a computer and it attached to the network. Its main purpose is to uniquely identify over a network.
Syntax :
hostname -[option] [file]

Example: We obtain the system hostname by just typing hostname without any attributes.
Options:
-a : This option is used to get alias name of the host system(if any). It will return an empty line if no alias name is set. This option enumerates all configured addresses on all network interfaces.Syntax:hostname -a
Example:
Syntax:
hostname -a

Example:
-A : This option is used to get all FQDNs(Fully Qualified Domain Name) of the host system. It enumerates all configured addresses on all network interfaces. An output may display same entries repetitively.Syntax :hostname -A
Example:
Syntax :
hostname -A

Example:
-b : Used to always set a hostname. Default name is used if none specified.Syntax :hostname -b
Example:
Syntax :
hostname -b

Example:
-d : This option is used to get the Domain if local domains are set. It will not return anything(not even a blank line) if no local domain is set.Syntax :hostname -d
Example :
Syntax :
hostname -d

Example :
-f : This option is used to get the Fully Qualified Domain Name(FQDN). It contains short hostname and DNS domain name.Syntax:hostname -f
Example:
Syntax:
hostname -f

Example:
-F : This option is used to set the hostname specified in a file. Can be performed by the superuser(root) only.Syntax:sudo hostname -F filename
Example:
Syntax:
sudo hostname -F filename

Example:
-i option:This option is used to get the IP(network) addresses. This option works only if the hostname is resolvable.Syntax:hostname -i
Example:
Syntax:
hostname -i

Example:
-I : This option is used to get all IP(network) addresses. The option doesn’t depend on resolvability of hostname.hostname -I
Example:
hostname -I

Example:
-s : This option is used to get the hostname in short. The short hostname is the section of hostname before the first period/dot(.). If the hostname has no period, the full hostname is displayed.Syntax :hostname -s
Example:
Syntax :
hostname -s

Example:
-V : Gives version number as output.Syntax:hostname -V
Example:
Syntax:
hostname -V

Example:
Note: To set the hostname we can use the command given below:
sudo hostname NEW_HOSTNAME

Here, NEW_HOSTNAME is the new hostname the user wants to give.
Example:
linux-command
Linux-networking-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
echo command in Linux with Examples
Python - Convert key-values list to flat dictionary - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed.
Method : zip() + dict()The combination of above functions can be used to achieve the required task. In this, we perform the pairing using zip() and dict() is used to convert tuple data returned by zip() to dictionary format.
# Python3 code to demonstrate working of # Convert key-values list to flat dictionary# Using dict() + zip()from itertools import product  # initializing dictionarytest_dict = {'month' : [1, 2, 3],             'name' : ['Jan', 'Feb', 'March']}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert key-values list to flat dictionary# Using dict() + zip()res = dict(zip(test_dict['month'], test_dict['name']))  # printing result print("Flattened dictionary : " + str(res)) 
The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’: [1, 2, 3]}Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Switch Case in Dart - GeeksforGeeks

10 May, 2020
In Dart, switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java.
Syntax:
switch ( expression ) { 
   case value1: { 
      // Body of value1
   } break; 
   case value2: { 
      //Body of value2 
   } break; 
   .
   .
   .
   default: { 
      //Body of default case  
   } break; 
} 
The default case is the case whose body is executed if none of the above cases matches the condition.
Rules to follow in switch case:
There can be any number of cases. But values should not be repeated.The case statements can include only constants. It should not be a variable or an expression.There should be a flow control i.e break within cases. If it is omitted than it will show error.The default case is optional.Nested switch is also there thus you can have switch inside switch.
There can be any number of cases. But values should not be repeated.
The case statements can include only constants. It should not be a variable or an expression.
There should be a flow control i.e break within cases. If it is omitted than it will show error.
The default case is optional.
Nested switch is also there thus you can have switch inside switch.
Example 1: Normal switch-case statement
void main(){    int gfg = 1;    switch (gfg) {    case 1: {        print("GeeksforGeeks number 1");    } break;    case 2: {        print("GeeksforGeeks number 2");    } break;    case 3: {        print("GeeksforGeeks number 3");    } break;    default: {        print("This is default case");    } break;    }}
Output:
GeeksforGeeks number 1
Example 2: Nested switch-case statement
void main(){    int gfg1 = 1;    String gfg2 = "Geek";    switch (gfg1) {    case 1: {        switch (gfg2) {        case 'Geek': {            print("Welcome to GeeksforGeeks");        }        }    } break;    case 2: {        print("GeeksforGeeks number 2");    } break;    default: {        print("This is default case");    } break;    }}
Output:
Welcome to GeeksforGeeks
Dart-basics
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Container class in Flutter
Flutter - Stack Widget
Operators in Dart
Java Examples - Interrupt a Thread

How to interrupt a running Thread?
Following example demonstrates how to interrupt a running thread interrupt() method of thread and check if a thread is interrupted using isInterrupted() method.
public class GeneralInterrupt extends Object implements Runnable {
   public void run() {
      try {
         System.out.println("in run() - about to work2()");
         work2();
         System.out.println("in run() - back from work2()");
      } catch (InterruptedException x) {
         System.out.println("in run() - interrupted in work2()");
         return;
      }
      System.out.println("in run() - doing stuff after nap");
      System.out.println("in run() - leaving normally");
   }
   public void work2() throws InterruptedException {
      while (true) {
         if (Thread.currentThread().isInterrupted()) {
            System.out.println("C isInterrupted()="+ Thread.currentThread().isInterrupted());
            Thread.sleep(2000);
            System.out.println("D isInterrupted()="+ Thread.currentThread().isInterrupted());
         }
      }
   }
   public void work() throws InterruptedException {
      while (true) {
         for (int i = 0; i < 100000; i++) {
            int j = i * 2;
         }
         System.out.println("A isInterrupted()="+ Thread.currentThread().isInterrupted());
         if (Thread.interrupted()) {
            System.out.println("B isInterrupted()="+ Thread.currentThread().isInterrupted());
            throw new InterruptedException();
         }
      }
   }
   public static void main(String[] args) {
      GeneralInterrupt si = new GeneralInterrupt();
      Thread t = new Thread(si);
      t.start();
      try {
         Thread.sleep(2000);
      } catch (InterruptedException x) { }
		
      System.out.println("in main() - interrupting other thread");
      t.interrupt();
      System.out.println("in main() - leaving");
   }
}
The above code sample will produce the following result.
in run() - about to work2()
in main() - interrupting other thread
in main() - leaving
C isInterrupted() = true
in run() - interrupted in work2()

 Print
 Add Notes
 Bookmark this page
jQuery Get Content and Attributes

jQuery contains powerful methods for changing and manipulating HTML elements and attributes.
One very important part of jQuery is the possibility to manipulate the DOM.
jQuery comes with a bunch of DOM related methods that make it easy to 
access and manipulate elements and attributes.
DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral 
interface that allows programs and scripts to dynamically access and update the 
content, structure, and style of a document."
Three simple, but useful, jQuery methods for DOM manipulation are:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
The following example demonstrates how to get content with the jQuery text() and html() methods:
The following example demonstrates how to get the value of an input field with the jQuery val() method:
The jQuery attr() method is used to get attribute values.
The following example demonstrates how to get the value of the href attribute 
in a link:
The next chapter explains how to set (change) content and attribute values.
Use a jQuery method to return the text content of a <div> element.
$("div").();

Start the Exercise
For a complete overview of all jQuery HTML methods, please go to our
jQuery HTML/CSS Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to display the background color of an element in HTML?

Use the bgcolor attribute in HTML to display the background color of an element. It is used to control the background of an HTML element, specifically page body and table backgrounds.
Note − This attribute is not supported in HTML5.
You can try to run the following code to learn how to implement bgcolor attribute in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Background Colors</title>
   </head>
   <body>
      <!-- Format 1 - Use color name -->
      <table bgcolor = "yellow" width = "100%">
         <tr>
            <td>
               This background is yellow
            </td>
         </tr>
      </table>

      <!-- Format 2 - Use hex value -->
      <table bgcolor = "#6666FF" width = "100%">
         <tr>
            <td>
               This background is sky blue
            </td>
         </tr>
      </table>

      <!-- Format 3 - Use color value in RGB terms -->
      <table bgcolor = "rgb(255,0,255)" width = "100%">
         <tr>
            <td>
               This background is green
            </td>
         </tr>
      </table>
   </body>
</html>
How to Install Pillow on Linux? - GeeksforGeeks

30 Sep, 2021
In this article, we will look into the various methods of installing the PIL package on a Linux machine. Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. 
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (Depending upon the user preference)
If you want the installation to be done through conda, you can use the below command:
conda install -c anaconda pillow
Type in “y” for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Use the below command to verify if the above package has successfully installed:
conda list pillow
You will get a similar message as shown below if the installation has been successful:
Users who prefer to use pip can use the below command to install the package:
pip install pillow
You will get a similar message once the installation is complete:
It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment:
python3 -m venv my-env
Activate the virtual environment (ie, my-env) using the below command:
source my-env/bin/activate
Use the below command to check if the package has been successfully installed:
python3 -m pip show pillow
You will get a similar message as shown below if the installation is successful:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
CREATE SCHEMA in SQL Server - GeeksforGeeks

02 Sep, 2020
A schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. Database may have one or more schema.
SQL Server have some built-in schema, for example: dbo, guest, sys, and INFORMATION_SCHEMA.
dbo is default schema for a new database, owned by dbo user. While creating a new user with CREATE USER command, user will take dbo as its default schema.
CREATE SCHEMA statement used to create a new schema in current database.
Syntax :
CREATE SCHEMA schemaname
   [AUTHORIZATION ownername]
GO
Example –
CREATE SCHEMA geeks_sch;
GO 
To select SQL Server SCHEMA :To list all schema in the current database, use query as shown below :
SELECT  *
FROM sys.schemas 
Result –
Create objects for the schema :To create a new table named Geektab in the geeks_sch schema :
Syntax :
CREATE TABLE schemaname.tablename(
 values... );
Example –
CREATE TABLE geeks_sch.Geektab(
G_id INT PRIMARY KEY IDENTITY, 
Name VARCHAR(200), 
DOJ DATETIME2 NOT NULL
); 
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between DDL and DML in DBMS
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL - ORDER BY
C++ Conditional ? : Operator

Exp1 ? Exp2 : Exp3;

where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form −
if(condition) {
   var = X;
} else {
   var = Y;
}

For example, consider the following code −
if(y < 10) { 
   var = 30;
} else {
   var = 40;
}

Above code can be rewritten like this −
var = (y < 10) ? 30 : 40;

Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not. You can the try following example −
#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int x, y = 10;

   x = (y < 10) ? 30 : 40;
   cout << "value of x: " << x << endl;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of x: 40


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Python program to count total set bits in all number from 1 to n.

Given a positive integer n, then we change to its binary representation and count the total number of set bits.
Input : n=3
Output : 4
Step 1: Input a positive integer data.
Step 2: then convert it to binary form.
Step 3: initialize the variable s = 0.
Step 4: traverse every element and add.
Step 5: display sum.
# Python program to count set bits
# in all numbers from 1 to n.
def countbits(n):
   # initialize the counter
   c = 0
   for i in range(1, n + 1):
   c += bitsetcount(i)
   return c
   def bitsetcount(x):
      if (x <= 0):
      return 0
      return (0 if int(x % 2) == 0 else 1) + bitsetcount(int(x / 2))
      # Driver program
      n = int(input("Enter the value of n"))
print("Total set bit count is", countbits(n))
Enter the value of n10
Total set bit count is 17
Dangling, Void, Null and Wild Pointers in C/C++

Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted). There are different ways where Pointer acts as dangling pointer
The pointer pointing to local variable becomes dangling when local variable is not static.
int *show(void) {
   int n = 76; /* ... */ return &n;
}
Output of this program will be garbage address.
#include <stdlib.h> #include <stdio.h> int main() {
   float *p = (float *)malloc(sizeof(float));
   //dynamic memory allocation. free(p);
   //after calling free() p becomes a dangling pointer p = NULL;
   //now p no more a dangling pointer.
}
int main() {
   int *p //some code// {
      int c; p=&c;
   }
   //some code//
   //p is dangling pointer here.
}
Void pointer in C is a pointer which is not associate with any data types. It points to some data location in storage means points to the address of variables. It is also called general purpose pointer.
It has some limitations
Pointer arithmetic is not possible of void pointer due to its concrete size.
It can’t be used as dereferenced.
Here is a simple example
#include<stdlib.h>
int main() {
   int a = 7;
   float b = 7.6;
   void *p;
   p = &a;
      printf("Integer variable is = %d", *( (int*) p) );
   p = &b;
   printf("\nFloat variable is = %f", *( (float*) p) );
   return 0;
}
Integer variable is = 7
Float variable is = 7.600000
Begin
   Initialize a variable a with integer value and variable b with float value.
   Declare a void pointer p.
   (int*)p = type casting of void.
   p = &b mean void pointer p is now float.
   (float*)p = type casting of void.
   Print the value.
End.
Null pointer is a pointer which points nothing.
Some uses of null pointer are:
To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
To pass a null pointer to a function argument if we don’t want to pass any valid memory address.
To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
 Live Demo
#include<iostream>
#include <stdio.h>
int main() {
   int *p= NULL;//initialize the pointer as null.
   printf("The value of pointer is %u",p);
   return 0;
}
The value of pointer is 0.
Wild pointers are pointers those are point to some arbitrary memory location. (not even NULL)
int main() {
   int *ptr; //wild pointer
   *ptr = 5;
}
How to Generate MS Word Tables With Python | by Dardan Xhymshiti | Towards Data Science

Whenever automation is discussed, Python is often mentioned. The easy to use syntax, huge number of libraries and the script oriented language construction make Python excel on automation compared to other programming languages.
Small and big companies generate reports daily with Microsoft Office tools such as Word and Excel. In this article, I’ll provide an end-to-end explanation on generating tables of data in MS Word through Python.
I will consider a scenario where we have a number of news articles and we need to generate a Word document with tables containing stats extracted from these articles. Some of these stats are: number of words, number of sentences and average word length.
For this example, I’ve used Python 3.7. The only dependency you need to install is python-docx. You can install this dependency by submitting the following command in your machine’s terminal.
pip install python-docx
For this example, I’ve randomly picked up two sport articles from CNN. For extracting stats, I’ve written the below describe_text(text) function. This function takes a string parameter (article, review, ...) and returns a dictionary of stats such as Number of characters, Number of words, Number of sentences and others.
First of you need to instantiate a document object through Document class. For every article, extract stats by invoking describe_text(text) function and create a table through add_table(row, columns) function. For every stat in a dictionary, create a row through add_row() function and add the corresponding stats. Finally add a page break at the end by calling add_page_break()function in order to present each table in a new page.
For more text stats with pure Python functions check my other article below.
towardsdatascience.com
Generating word documents with Python is easy. All that you need is the python-docx library. This library offers possibilities to accomplish most of the things (but not all) that you can accomplish in MS Word.
In my experience, I have generated thousands of Word documents with double-digits number of pages in a matter of seconds. I’ve done this to organise logs data in a more readable format or present written findings in after analysing product review text data.
JSON.simple - Using JSONValue

JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonDemo {
   public static void main(String[] args) {
      String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
      Object obj = JSONValue.parse(s);
      JSONArray array = (JSONArray)obj;

      System.out.println("The 2nd element of array");
      System.out.println(array.get(1));
      System.out.println();

      JSONObject obj2 = (JSONObject)array.get(1);
      System.out.println("Field \"1\"");
      System.out.println(obj2.get("1"));    

      s = "{}";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,]";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,,2]";
      obj = JSONValue.parse(s);
      System.out.println(obj);
   }
}
The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]


    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
\tfrac - Tex Command

\tfrac - Used to create textstyle fraction.
{ \tfrac}
\tfrac command draws textstyle fraction.

\tfrac ab \frac ab

abab



\tfrac ab \frac ab

abab


\tfrac ab \frac ab

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Output of Python Programs | Set 18 (List and Tuples)

30 Nov, 2021
1) What is the output of the following program? 
PYTHON
L = list('123456')L[0] = L[5] = 0L[3] = L[-2]print(L)
a) [0, ‘2’, ‘3’, ‘4’, ‘5’, 0] b) [‘6’, ‘2’, ‘3’, ‘5’, ‘5’, ‘6’] c) [‘0’, ‘2’, ‘3’, ‘5’, ‘5’, ‘0’] d) [0, ‘2’, ‘3’, ‘5’, ‘5’, 0] Ans. (d) Explanation: L[0] is ‘1’ and L[5] is ‘6’, both of these elements will be replaced by 0 in the List. L[3], which is 4 will be replaced L[-2] i.e. 5.2) What is the output of the following program? 
PYTHON3
T = 'geeks'a, b, c, d, e = Tb = c = '*'T = (a, b, c, d, e)print(T)
a) (‘g’, ‘*’, ‘*’, ‘k’, ‘s’) b) (‘g’, ‘e’, ‘e’, ‘k’, ‘s’) c) (‘geeks’, ‘*’, ‘*’) d) KeyError Ans. (a) Explanation: A tuple is created as T = (‘g’, ‘e’, ‘e’, ‘k’, ‘s’), then it is unpacked into a, b, c, d and e, mapping from ‘g’ to a and ‘s’ to e. b and c which are both ‘e’ are equal to ‘*’ and then the existing tuple is replaced by packing a, b, c, d and e into a tuple T.3) What is the value of L at the end of execution of the following program? 
PYTHON3
L = [2e-04, 'a', False, 87]T = (6.22, 'boy', True, 554)for i in range(len(L)):    if L[i]:        L[i] = L[i] + T[i]    else:        T[i] = L[i] + T[i]        break
a) [6.222e-04, ‘aboy’, True, 641] b) [6.2202, ‘aboy’, 1, 641] c) TypeError d) [6.2202, ‘aboy’, False, 87] Ans. (c) Explanation: The for loop will run for i = 0 to i = 3, i.e. 4 times(len(L) = 4). 2e-04 is same as 0.0002, thus L[i] = 6.22 + 0.0002 = 6.2202. String addition will result in concatenation, ‘a’ + ‘boy’ = ‘aboy’. False + True is True, it’ll return the integer value of 1. As tuples are immutable, the code will end with TypeError, but elements of L will be updated.4) What is the output of the following program? 
PYTHON
T = (2e-04, True, False, 8, 1.001, True)val = 0for x in T:    val += int(x)print(val)
a) 12 b) 11 c) 11.001199999999999 d) TypeError Ans. (b) Explanation: Integer value of 2e-04(0.0002) is 0, True holds a value 1 and False a 0, integer value of 1.001 is 1. Thus total 0 + 1 + 0 + 8 + 1 + 1 = 11.5) Which of the options below could possibly be the output of the following program? 
PYTHON
L = [3, 1, 2, 4]T = ('A', 'b', 'c', 'd')L.sort()counter = 0for x in T:    L[counter] += int(x)    counter += 1    breakprint(L)
a) [66, 97, 99, 101] b) [66, 68, 70, 72] c) [66, 67, 68, 69] d) ValueError Ans. (d) Explanation: After sort(L), L will be = [1, 2, 3, 4]. Counter = 0, L[0] i.e. 1, x = ‘A’, but Type Conversion of char ‘A’ to integer will throw error and the value cannot be stored in L[0], thus a ValueError.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
simmytarika5
python-list
Python-Output
python-tuple
Program Output
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL queries on FILM Database

29 May, 2020
Consider the following tables in Film Database:
ARTIST (Art_id, Art_Name, Art_Gender) 
PRODUCER (Prod_id, Prod_Name, Prod_Phone)
FILMS (Film_id, Film_Title, Film_Year, Film_Lang, Prod_id) 
CASTING (Art_id, Film_id, Part) 
REVIEW (Film_id, Stars) 
The data content of these five tables are shown below:
SELECT * FROM ARTIST;
SELECT * FROM PRODUCER;
SELECT * FROM FILMS;
SELECT * FROM CASTING;
SELECT * FROM REVIEW;
Query-1:Find the name of all the Films whose producer is “NIRAJ”.
First we will find the Producer ID for the Producer Named “NIRAJ” and for this we use the PRODUCER table.
SELECT PROD_ID 
FROM PRODUCER 
WHERE PROD_NAME = ‘NIRAJ’
The above query will return the Prod_id “203”. Now we will find the title of films whose pros_id is “203”. For doing this we use the table FILMS and use the above query as a sub query.
SELECT FILM_TITLE 
FROM FILMS 
WHERE PROD_ID IN (SELECT PROD_ID 
FROM PRODUCER 
WHERE PROD_NAME = ‘NIRAJ’);
Output:
Query-2:Display all artists who acted in a film between 2016 and 2018.
For finding this we need to use the ARTIST_NAME field of ARTIST table as well as the FILM_YEAR field of FILMS table. For joining these two tables we use a third table CASTING using Art_id and Film_id.After joining we use the BETWEEN operator for checking the FILM_YEAR in between 2016 and 2018.
SELECT A.ART_NAME,  F.FILM_TITLE, F.FILM_YEAR 
FROM ARTIST A, CASTING C, FILMS F
WHERE A.ART_ID=C.ART_ID 
AND C.FILM_ID=F.FILM_ID 
AND F.FILM_YEAR  BETWEEN 2016 AND 2018;
Output:
Query-3:Display the names of films with the stars received and sort the result on the basis of stars.
For this we need FILM_TITLE field of FILMS table as well as STARS field of REVIEW table. For joining these two tables we will use the common field which is the FILM_ID. And after joining we display the result in the order of increasing STARS by using ORDER BY clause.
SELECT F.FILM_TITLE, R_STARS
FROM FILMS F, REVIEW R
WHERE F.FILM_ID=R.FILM_ID
ORDER BY R.STARS DESC
Output:
Query-4:Update the stars of all films whose producer is ‘NIRAJ’ to 5.
First we find the PRODUCER ID of the PRODUCER named “NIRAJ” by using this query:
SELECT PROD_ID 
FROM PRODUCER 
WHERE PROD_NAME = ‘NIRAJ’
Then find the FILM_ID from the FILMS table using this PROD_ID.
SELECT FILM_ID FROM FILMS 
WHERE PROD_ID IN (SELECT PROD_ID 
FROM PRODUCER 
WHERE PROD_NAME = ‘NIRAJ’)
And then this FILM_ID helps in Updating the value of STARS in REVIEW table using UPDATE command.
UPDATE REVIEW 
SET STARS=5 
WHERE FILM_ID IN (SELECT FILM_ID FROM FILMS 
WHERE PROD_ID IN (SELECT PROD_ID 
FROM PRODUCER 
WHERE PROD_NAME = ‘NIRAJ’));
Output:
1 row updated.
To observe the changes we can use SELECT * command in REVIEW table.
SELECT * FROM REVIEW;
DBMS-SQL
DBMS
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to copy a map to another map in Golang?

10 May, 2020
Maps in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Map, you can copy a map to another map using the for loop provided by the Go language. In for loop, we fetch the index value 1 by 1 with the element and assign it to another map.
Syntax:
for key, value := range originalMap{
}

Let us discuss this concept with the help of the examples:
Example 1:
// Go program to illustrate how to // copy a map to another map   package main     import "fmt"    func main() {         // Creating and initializing a map     // Using shorthand declaration and     // using map literals     originalMap := make(map[string]int)    originalMap["one"] = 1    originalMap["two"] = 2    originalMap["three"] = 3    originalMap["four"] = 4    originalMap["five"] = 5    originalMap["six"] = 6    originalMap["seven"] = 7    originalMap["eight"] = 8    originalMap["nine"] = 9                 // Creating empty map     CopiedMap:= make(map[string]int)          /* Copy Content from Map1 to Map2*/    for index, element  := range originalMap{                 CopiedMap[index] = element    }          for index, element  := range CopiedMap{         fmt.Println(index, "=>", element)      }}
Output:
seven => 7
eight => 8
two => 2
four => 4
three => 3
six => 6
nine => 9
one => 1
five => 5

Example 2:
// Go program to illustrate how to // copy a map to another map   package main     import "fmt"    func main() {         // Creating and initializing a map     // Using shorthand declaration and     // using map literals     map_1 := map[int]string{                     90: "Dog",             91: "Cat",             92: "Cow",             93: "Bird",             94: "Rabbit",     }            // Creating and initializing empty map     map2 := map[string]int{}           /* Copy Content from Map1 to Map2*/    for key, value := range map_1{                 map2[value] = key    }          fmt.Println("Copied Map :", map2) }
Output:
Copied Map : map[Bird:93 Rabbit:94 Dog:90 Cat:91 Cow:92]

Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert String to Character Array in C#

26 May, 2020
Given a string, the task is to convert this string into a character array in C#.
Examples:
Input:  string 
Output:  [s, t, r, i, n, g]
  
Input:  GeeksForGeeks
Output:  [G, e, e, k, s, F, o, r, G, e, e, k, s]  

Method 1: Naive Approach
Step 1: Get the string.
Step 2: Create a character array of the same length as of string.
Step 3: Traverse over the string to copy character at the i’th index of string to i’th index in the array.
Step 4: Return or perform the operation on the character array.
Below is the implementation of the above approach:
C#
// C# program to Convert a string // to a Character array // using Naive Approach     using System;  public class GFG{        static public void Main ()    {         string str = "GeeksForGeeks";             // Creating array of string length         char[] ch = new char[str.Length];             // Copy character by character into array         for (int i = 0; i < str.Length; i++) {             ch[i] = str[i];         }             // Printing content of array         foreach  (char c in ch) {             Console.WriteLine(c);         }     } }
Output:
G
e
e
k
s
F
o
r
G
e
e
k
s

Method 2: Using toCharArray() Method
Step 1: Get the string.
Step 2: Create a character array of same length as of string.
Step 3: Store the array return by toCharArray() method.
Step 4: Return or perform operation on character array.
C#
// C# program to Convert a string // to a Character array // using ToCharArray method     using System;  public class GFG{        static public void Main ()    {         string str = "GeeksForGeeks";             // Creating array of string length         // Copy character by character into array         char[] ch = str.ToCharArray();            // Printing content of array         foreach  (char c in ch) {             Console.WriteLine(c);         }     } }
Output:
G
e
e
k
s
F
o
r
G
e
e
k
s

CSharp-string
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2018 | Question 56

09 Mar, 2018
Let G be a graph with 100! vertices, with each vertex labelled by a distinct permutation of the numbers 1, 2, ..., 100. There is an edge between vertices u and v if and only if the label of u can be obtained by swapping two adjacent numbers in the label of v. Let y denote the degree of a vertex in G, and z denote the number of connected components in G. Then y + 10z = _______ .
Note –This was Numerical Type question.
(A) 109(B) 110(C) 119(D) None of theseAnswer: (A)Explanation: There is an edge between vertices u and v iff the label of u can be obtained by swapping two adjacent numbers in the label of v.Then the set of swapping numbers will be {(1, 2), (2, 3), ...........(9, 9)}There will be 99 such sets, i.e. number of edges = 99and each vertex will have 99 edges corresponding to it. 
Say graph with 3! vertices, then vertices will be like {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}...Let’s pick vertex {123}, degree will be 2 since it will be connected with two other vertices {213} and {132}.
We can conclude that for n, degree will be n-1.
SO, degree of each vertex = 99 (as said y)As the vertices are connected together, the number of connected components formed will be 1 (as said z).
 y+10z = 99+10(1) = 109
Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Check the OS Version in Linux?

15 Apr, 2021
When we want to install the software in our system, firstly we must know that whether our current Operating System is supporting this version of the software or not. In Windows, we can easily check it as Windows is totally based on a GUI-based Operating System.
But we prefer to use the Command line instead of the GUI in Operating System like Linus/Unix. In this article, we will learn how to check the details of the Operating System we are using in Linux.
We will use three simple methods to check the Linux OS version:
Using os-release file available in Linux’s etc directoryUsing lsb_release commandUsing version file available in Linux’s proc directory
Using os-release file available in Linux’s etc directory
Using lsb_release command
Using version file available in Linux’s proc directory
We can check the Linux Operating System (OS) info by running the below command
~$ cat /etc/os-release 
Output:
LSB Stands for Linux Standard Base, we can check the  Linux Operating System (OS) using lsb_release command
$ lsb_release -a
Output:
We can use the below command to check the Linux Operating System (OS)
~$ cat /proc/version
Output:
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Flutter on Visual Studio Code?
How to Install Jupyter Notebook on MacOS?
How to Install Z Shell(zsh) on Linux?
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
AWK command in Unix/Linux with examples
tar command in Linux with examples
TCP Server-Client implementation in C
memmove() in C/C++

10 Dec, 2021
memmove() is used to copy a block of memory from a location to another. It is declared in string.h
// Copies "numBytes" bytes from address "from" to address "to"
void * memmove(void *to, const void *from, size_t numBytes);

Below is a sample C program to show the working of memmove().
C
/* A C program to demonstrate working of memmove */#include <stdio.h>#include <string.h>  int main(){    char str1[] = "Geeks"; // Array of size 100    char str2[] = "Quiz"; // Array of size 5      puts("str1 before memmove ");    puts(str1);      /* Copies contents of str2 to sr1 */    memmove(str1, str2, sizeof(str2));      puts("\nstr1 after memmove ");    puts(str1);      return 0;}
str1 before memmove 
Geeks

str1 after memmove 
Quiz

How is it different from memcpy()? 
memcpy() simply copies data one by one from one location to another. On the other hand memmove() copies the data first to an intermediate buffer, then from the buffer to destination.memcpy() leads to problems when strings overlap. 
For example, consider below program. 
C
// Sample program to show that memcpy() can lose data.#include <stdio.h>#include <string.h>int main(){    char csrc[100] = "Geeksfor";    memcpy(csrc + 5, csrc, strlen(csrc) + 1);    printf("%s", csrc);    return 0;}
GeeksGeeksfor
Since the input addresses are overlapping, the above program overwrites the original string and causes data loss. 
Consider the below program for understanding the difference between the memcpy and memmove function in case of overlapping happens.
C
// Sample program to show that memmove() is better than// memcpy() when addresses overlap.#include <stdio.h>#include <string.h>int main(){    char str[100] = "Learningisfun";    char *first, *second;    first = str;    second = str;    printf("Original string :%s\n ", str);          // when overlap happens then it just ignore it    memcpy(first + 8, first, 10);    printf("memcpy overlap : %s\n ", str);      // when overlap it start from first position    memmove(second + 8, first, 10);    printf("memmove overlap : %s\n ", str);      return 0;}
Original string :Learningisfun
 memcpy overlap : LearningLearningis
 memmove overlap : LearningLearningLe
 
As you can see clearly with memmove function whenever overlap happens (i.e when the first pointer moves to the character ‘i’) then the first pointer will start to print from the beginning (output Le) but with memcpy function, it just ignores if there is an overlap and just keep moving forward.
Write your own memcpy() and memmove()?Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
vermashobhit1994
rkbhola5
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
HTML <html> Tag

17 Mar, 2022
The <html> tag in HTML is used to define the root of HTML and XHTML documents. The <html> tag tells the browser that it is an HTML document. It is the second outer container for everything that appears in an HTML document followed by the <!DOCTYPE> tag. The <html> tag requires a starting and end tag.Syntax:  
<html> HTML Contents... </html>
Attribute Value: The <html> tag contains single attribute xmlns whose attribute value is http://www.w3.org/1999/xhtml. It is used to define the namespace attributes.Below examples illustrate the <html> element in HTML:Example 1:  
HTML
<!DOCTYPE html><!-- html tag starts here --><html>         <body>                         <h1>GeeksforGeeks</h1>            <h2><html> Tag</h2>                     </body> </html>                   <!-- html tag ends here -->
Output:  
Example 2: Using the xmlns attribute inside the <html> tag.  
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <title>html Tag</title>        <style>            h1 {                color:green;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2><html> Tag</h2>    </body></html>                   
Output:  
Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type