code-rag-bench/online-tutorials huggingface dataset:
Python | Convert list of nested dictionary into Pandas dataframe

14 May, 2020
Given a list of nested dictionary, write a Python program to create a Pandas dataframe using it. Let’s understand stepwise procedure to create Pandas Dataframe using list of nested dictionary.
Step #1: Creating a list of nested dictionary.
# importing pandasimport pandas as pd  # List of nested dictionary initializationlist = [        {        "Student": [{"Exam": 90, "Grade": "a"},                    {"Exam": 99, "Grade": "b"},                    {"Exam": 97, "Grade": "c"},                   ],        "Name": "Paras Jain"        },        {        "Student": [{"Exam": 89, "Grade": "a"},                    {"Exam": 80, "Grade": "b"}                   ],        "Name": "Chunky Pandey"        }       ]  #print(list)
Output: 
Step #2: Adding dict values to rows.
# rows list initializationrows = []  # appending rowsfor data in list:    data_row = data['Student']    time = data['Name']          for row in data_row:        row['Name']= time        rows.append(row)  # using data framedf = pd.DataFrame(rows)  # print(df)
Output: Step #3: Pivoting dataframe and assigning column names.
# using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'],                        values =['Exam']).reset_index()  # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry']  # print dataframeprint(df)
Output:
 Below is the complete code:
# Python program to convert list of nested # dictionary into Pandas dataframe  # importing pandasimport pandas as pd  # List of list of dictionary initializationlist = [        {        "Student": [{"Exam": 90, "Grade": "a"},                    {"Exam": 99, "Grade": "b"},                    {"Exam": 97, "Grade": "c"},                   ],        "Name": "Paras Jain"        },        {        "Student": [{"Exam": 89, "Grade": "a"},                    {"Exam": 80, "Grade": "b"}                  ],        "Name": "Chunky Pandey"        }       ]  # rows list initializationrows = []  # appending rowsfor data in list:    data_row = data['Student']    time = data['Name']          for row in data_row:        row['Name']= time        rows.append(row)  # using data framedf = pd.DataFrame(rows)  # using pivot_tabledf = df.pivot_table(index ='Name', columns =['Grade'],                        values =['Exam']).reset_index()  # Defining columnsdf.columns =['Name', 'Maths', 'Physics', 'Chemistry']  # print dataframeprint(df)
Output:
            Name  Maths  Physics  Chemistry
0  Chunky Pandey     89       80        NaN
1     Paras Jain     90       99         97
shubham_singh
pandas-dataframe-program
Python pandas-dataFrame
Python-nested-dictionary
Python-pandas
Python
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 ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
filepath.Clean() Function in Golang With Examples

10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Clean() function in Go language used to return the shortest path name equivalent to the specified path by purely lexical processing. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
This function applies the Below rules iteratively until no further processing can be done:
It Replaces multiple Separator elements with a single one.
If the specified path is an empty string, it returns the string “.”.
It eliminates each . path name element (the current directory).
It eliminates each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
It eliminates .. elements that begin a rooted path: that is, replace “/..” by “/” at the beginning of a path, assuming Separator is ‘/’.
Syntax:
func Clean(path string) string

Here, ‘path’ is the specified path.
Return Value: It returns the shortest path name equivalent to the specified path by purely lexical processing.
Example 1:
// Golang program to illustrate the usage of// filepath.Clean() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Clean() function    fmt.Println(filepath.Clean("/GFG/./../Geeks"))    fmt.Println(filepath.Clean("GFG/../Geeks"))    fmt.Println(filepath.Clean("..GFG/./../Geeks"))    fmt.Println(filepath.Clean("gfg/../../../Geek/GFG"))}
Output:
/Geeks
Geeks
Geeks
../../Geek/GFG

Example 2:
// Golang program to illustrate the usage of// filepath.Clean() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Clean() function    fmt.Println(filepath.Clean(""))    fmt.Println(filepath.Clean("."))    fmt.Println(filepath.Clean("///"))    fmt.Println(filepath.Clean("/.//"))    fmt.Println(filepath.Clean("/./"))    fmt.Println(filepath.Clean(":/"))}
Output:
.
.
/
/
/
:

Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
np.nanmax() in Python

29 Nov, 2018
numpy.nanmax()function is used to returns maximum value of an array or along any specific mentioned axis of the array, ignoring any Nan value.
Syntax : numpy.nanmax(arr, axis=None, out=None, keepdims = no value)
Parameters :arr : Input array.axis : Axis along which we want the max value. Otherwise, it will consider arr to be flattened(works on all the axis)axis = 0 means along the columnand axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output.keepdims : If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.
Return :maximum array value(a scalar value if axis is none)or array with maximum value along specified axis.
Code #1 : Working
# Python Program illustrating # numpy.nanmax() method     import numpy as np    # 1D array arr = [1, 2, 7, 0, np.nan]print("arr : ", arr) print("max of arr : ", np.amax(arr))  # nanmax ignores NaN values. print("nanmax of arr : ", np.nanmax(arr))  
Output :
arr :  [1, 2, 7, 0, nan]
max of arr :  nan
nanmax of arr :  7.0

 Code #2 :
import numpy as np  # 2D array arr = [[np.nan, 17, 12, 33, 44],         [15, 6, 27, 8, 19]] print("\narr : \n", arr)      # maximum of the flattened array print("\nmax of arr, axis = None : ", np.nanmax(arr))      # maximum along the first axis # axis 0 means vertical print("max of arr, axis = 0 : ", np.nanmax(arr, axis = 0))      # maximum along the second axis # axis 1 means horizontal print("max of arr, axis = 1 : ", np.nanmax(arr, axis = 1)) 
Output :
arr : 
 [[nan, 17, 12, 33, 44], [15, 6, 27, 8, 19]]

max of arr, axis = None :  44.0
max of arr, axis = 0 :  [15. 17. 27. 33. 44.]
max of arr, axis = 1 :  [44. 27.]

 Code #3 :
import numpy as np  arr1 = np.arange(5) print("Initial arr1 : ", arr1)   # using out parameternp.nanmax(arr, axis = 0, out = arr1)   print("Changed arr1(having results) : ", arr1)  
Output :
Initial arr1 :  [0 1 2 3 4]
Changed arr1(having results) :  [15 17 27 33 44]

Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reading contents of a Text File in R Programming – read.table() Function

19 Jun, 2020
read.table() function in R Language is used to read data from a text file. It returns the data in the form of a table.
Syntax:read.table(filename, header = FALSE, sep = “”)
Parameters:header: represents if the file contains header row or notsep: represents the delimiter value used in file
Example 1: Reading data from same directory
# R program to read a text file  # Get content into a data frame data <- read.table("TextFileExample.txt",                      header = FALSE, sep = " ")     # Printing content of Text File print(data) 
Output:
   V1 V2 V3
1 100  A  a
2 200  B  b
3 300  C  c
4 400  D  d
5 500  E  e
6 600  F  f

Example 2: Reading data from different directory
# R program to read a text file  # Reading data from another directory x<-read.table("D://Data//myfile.txt", header = FALSE)     # print x print(x) 
Output:
   V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3

R-FileHandling
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
jQuery - siblings( [selector] ) Method

The siblings( [selector] ) method gets a set of elements containing all of the unique siblings of each of the matched set of elements.
Here is the simple syntax to use this method −
selector.siblings( [selector] )

Here is the description of all the parameters used by this method −
selector − This is optional selector to filter the sibling Elements with.
selector − This is optional selector to filter the sibling Elements with.
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function(){
            $("p").siblings('.selected').addClass("hilight");
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>
   </head>
	
   <body>
      <div><span>Hello</span></div>
      <p class = "selected">Hello Again</p>
      <p>And Again</p>
   </body>
</html>
This will produce following result −
Hello Again
And Again
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function(){
            $("p").siblings('.selected').addClass("hilight");
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>
   </head>
	
   <body>
      <div><span>Hello</span></div>
      <p class = "hilight">Hello Again</p>
      <p>And Again</p>
   </body>
</html>
This will produce following result −
Hello Again
And Again

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Converting a 10 digit phone number to US format using Regex in Python - GeeksforGeeks

29 Dec, 2020
Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have been developed in different programming languages in order to ease these text processing tasks.
To implement Regular Expression, the python re package can be used and to be used it can be easily imported like any other inbuilt python module.
Steps for converting a 10-digit phone number to its corresponding US number format:
Import the python re package.
Write a function that takes the phone number to be formatted as argument and processes it. 
Now simply call the function and pass the value. 
Example:
Python3
import re   def convert_phone_number(phone):    # actual pattern which only change this line  num = re.sub(r'(?<!\S)(\d{3})-', r'(\1) ', phone)   return num  # Driver code print(convert_phone_number("Call geek 321-963-0612"))
Output:
Call geek (321) 963-0612
Python Regex-programs
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
Apache NiFi - API

NiFi offers a large number of API, which helps developers to make changes and get information of NiFi from any other tool or custom developed applications. In this tutorial, we will use postman app in google chrome to explain some examples.
To add postmantoyour Google Chrome, go to the below mentioned URL and click add to chrome button. You will now see a new app added toyour Google Chrome.
chrome web store
The current version of NiFi rest API is 1.8.0 and the documentation is present in the below mentioned URL.
https://nifi.apache.org/docs/nifi-docs/rest-api/index.html
Following are the most used NiFi rest API Modules −
http://<nifi url>:<nifi port>/nifi-api/<api-path>
http://<nifi url>:<nifi port>/nifi-api/<api-path>
In case HTTPS is enabled
https://<nifi url>:<nifi port>/nifi-api/<api-path>
In case HTTPS is enabled
https://<nifi url>:<nifi port>/nifi-api/<api-path>
Let us now consider an example and run on postman to get the details about the running NiFi instance.
GET http://localhost:8080/nifi-api/flow/about

{
   "about": {
      "title": "NiFi",
      "version": "1.7.1",
      "uri": "http://localhost:8080/nifi-api/",
      "contentViewerUrl": "../nifi-content-viewer/",
      "timezone": "SGT",
      "buildTag": "nifi-1.7.1-RC1",
      "buildTimestamp": "07/12/2018 12:54:43 SGT"
   }
}


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Aggregate by country, state and city in a MongoDB collection with multiple documents

Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result.
To aggregate in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9a8de96c954c74be91e6a1")
}
> db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9a8e336c954c74be91e6a3")
}
> db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9a8e636c954c74be91e6a4")
}
Display all documents from a collection with the help of find() method −
> db.demo620.find();
This will produce the following output −
{ "_id" : ObjectId("5e9a8de96c954c74be91e6a1"), "Country" : "IND", "City" : "Delhi", "state" : "Delhi" }
{ "_id" : ObjectId("5e9a8e336c954c74be91e6a3"), "Country" : "IND", "City" : "Bangalore", "state" : "Karnataka" }
{ "_id" : ObjectId("5e9a8e636c954c74be91e6a4"), "Country" : "IND", "City" : "Mumbai", "state" : "Maharashtra" }
Following is the query to aggregate by country, state and city −
> db.demo620.aggregate([
...    { "$group": {
...       "_id": {
...          "Country": "$Country",
...          "state": "$state"
...       },
...       "City": {
...          "$addToSet": {
...             "City": "$City"
...          }
...       }
...    }},
...    { "$group": {
...       "_id": "$_id.Country",
...       "states": {
...          "$addToSet": {
...             "state": "$_id.state",
...             "City": "$City"
...          }
...       }
...    }}
... ]).pretty();
This will produce the following output −
{
   "_id" : "IND",
   "states" : [
      {
         "state" : "Delhi",
         "City" : [
            {
               "City" : "Delhi"
            }
         ]
      },
      {
         "state" : "Maharashtra",
         "City" : [
            {
                  "City" : "Mumbai"
            }
         ]
      },
      {
         "state" : "Karnataka",
         "City" : [
            {
               "City" : "Bangalore"
            }
         ]
      }
   ]
}
How to repeat a random sample in R?

The random sample can be repeated by using replicate function in R. For example, if we have a vector that contains 1, 2, 3, 4, 5 and we want to repeat this random sample five times then replicate(5,x) can be used and the output will be matrix of the below form:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
[4,] 4 4 4 4 4
[5,] 5 5 5 5 5
Live Demo
> x1<-sample(0:1,10,replace=TRUE)
> x1
[1] 1 0 1 0 1 1 1 0 0 1
> replicate(2,x1)
[,1] [,2]
[1,] 1 1
[2,] 0 0
[3,] 1 1
[4,] 0 0
[5,] 1 1
[6,] 1 1
[7,] 1 1
[8,] 0 0
[9,] 0 0
[10,] 1 1
Live Demo
> x2<-rnorm(20,5,0.43)
> x2
[1] 4.946766 4.930826 4.845512 4.940984 5.091849 5.437576 5.438818 4.319041
[9] 5.294105 4.941349 5.895272 5.161996 4.541355 5.065261 5.065255 4.770162
[17] 4.575399 4.466801 4.814925 5.568215
> replicate(4,x2)
[,1] [,2] [,3] [,4]
[1,] 4.946766 4.946766 4.946766 4.946766
[2,] 4.930826 4.930826 4.930826 4.930826
[3,] 4.845512 4.845512 4.845512 4.845512
[4,] 4.940984 4.940984 4.940984 4.940984
[5,] 5.091849 5.091849 5.091849 5.091849
[6,] 5.437576 5.437576 5.437576 5.437576
[7,] 5.438818 5.438818 5.438818 5.438818
[8,] 4.319041 4.319041 4.319041 4.319041
[9,] 5.294105 5.294105 5.294105 5.294105
[10,] 4.941349 4.941349 4.941349 4.941349
[11,] 5.895272 5.895272 5.895272 5.895272
[12,] 5.161996 5.161996 5.161996 5.161996
[13,] 4.541355 4.541355 4.541355 4.541355
[14,] 5.065261 5.065261 5.065261 5.065261
[15,] 5.065255 5.065255 5.065255 5.065255
[16,] 4.770162 4.770162 4.770162 4.770162
[17,] 4.575399 4.575399 4.575399 4.575399
[18,] 4.466801 4.466801 4.466801 4.466801
[19,] 4.814925 4.814925 4.814925 4.814925
[20,] 5.568215 5.568215 5.568215 5.568215
Live Demo
> x3<-rpois(20,5)
> x3
[1] 8 4 5 3 4 3 4 3 8 3 2 6 5 6 4 7 6 2 2 2
> replicate(8,x3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 8 8 8 8 8 8 8 8
[2,] 4 4 4 4 4 4 4 4
[3,] 5 5 5 5 5 5 5 5
[4,] 3 3 3 3 3 3 3 3
[5,] 4 4 4 4 4 4 4 4
[6,] 3 3 3 3 3 3 3 3
[7,] 4 4 4 4 4 4 4 4
[8,] 3 3 3 3 3 3 3 3
[9,] 8 8 8 8 8 8 8 8
[10,] 3 3 3 3 3 3 3 3
[11,] 2 2 2 2 2 2 2 2
[12,] 6 6 6 6 6 6 6 6
[13,] 5 5 5 5 5 5 5 5
[14,] 6 6 6 6 6 6 6 6
[15,] 4 4 4 4 4 4 4 4
[16,] 7 7 7 7 7 7 7 7
[17,] 6 6 6 6 6 6 6 6
[18,] 2 2 2 2 2 2 2 2
[19,] 2 2 2 2 2 2 2 2
[20,] 2 2 2 2 2 2 2 2
Live Demo
> x4<-sample(c("A","B","c","d"),10,replace=TRUE)
> x4
[1] "B" "A" "B" "A" "c" "B" "d" "A" "d" "d"
> replicate(5,x4)
[,1] [,2] [,3] [,4] [,5]
[1,] "B" "B" "B" "B" "B"
[2,] "A" "A" "A" "A" "A"
[3,] "B" "B" "B" "B" "B"
[4,] "A" "A" "A" "A" "A"
[5,] "c" "c" "c" "c" "c"
[6,] "B" "B" "B" "B" "B"
[7,] "d" "d" "d" "d" "d"
[8,] "A" "A" "A" "A" "A"
[9,] "d" "d" "d" "d" "d"
[10,] "d" "d" "d" "d" "d"
Tower Of Hanoi Problem


Tower of Hanoi is a puzzle problem. Where we have three stands and n discs. Initially, Discs are placed in the first stand. We have to place discs into the third or destination stand, the second or auxiliary stand can be used as a helping stand.
But there are some rules to follow.
 We can transfer only one disc for each movement.
Only the topmost disc can be picked up from a stand.
No bigger disc will be placed at the top of the smaller disc.
This problem can be solved easily by recursion. At first, using recursion the top (n-1) discs are placed from source to auxiliary stand, then place the last disc from source to destination, then again place (n-1) disc from auxiliary stand to destination stand by recursion.
Input:
Number of discs: 3
Output:
1. Move disk 1 from A to C
2. Move disk 2 from A to B
3. Move disk 1 from C to B
4. Move disk 3 from A to C
5. Move disk 1 from B to A
6. Move disk 2 from B to C
7. Move disk 1 from A to C
toh(n, s, a, d)
Input: Number of discs, source, auxiliary, destination.
Output: Steps to move discs from source to destination maintaining proper rules.
Begin
   if n = 1, then
      display move disc from s to d
   toh(n-1, s, d, a)

   display move disc from s to d
   toh(n-1, a, s, d)
End
#include<iostream>
using namespace std;

void TOH(int n, char s, char a, char d) {
   static int count = 0;          //store number of counts
   if(n == 1) {
      count++;
      cout << count<< ". Move disk " << n << " from "<<s <<" to "<<d<<endl;
      return;      //base case, when only one disk
   }

   TOH(n-1, s, d, a);               //recursive call the function
   count++;
   cout << count<< ". Move disk " << n << " from "<<s <<" to"<<d<<endl;
   TOH(n-1, a, s, d);
}

int main() {
   int n;
   cout << "Enter the number of disks: ";
   cin >> n;
   TOH(n, 'A','B','C');
}
Enter the number of disks: 3
1. Move disk 1 from A to C
2. Move disk 2 from A to B
3. Move disk 1 from C to B
4. Move disk 3 from A to C
5. Move disk 1 from B to A
6. Move disk 2 from B to C
7. Move disk 1 from A to C
Operations on struct variables in C

Here we will see what type of operations can be performed on struct variables. Here basically one operation can be performed for struct. The operation is assignment operation. Some other operations like equality check or other are not available for stack.
#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = {8, 6};
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
}
Complex numbers are:
(5 + 2i)
(8 + 6i)
This works fine as we have assigned some values into struct. Now if we want to compare two struct objects, let us see the difference.
#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = c1;
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
   if(c1 == c2){
      printf("Complex numbers are same.");
   } else {
      printf("Complex numbers are not same.");
   }
}
[Error] invalid operands to binary == (have 'complex' and 'complex')
How can we modify an existing module in Java 9?

The module is a named, self-describing collection of code and data. The code has been organized as a set of packages containing types like Java classes and interfaces. The data includes resources and other kinds of static information. We need to declare a module then add module-info.java at the root of the source code.
Below is the template of the "module-info.java" file.
module <module-name> {
   requires <module-name1> ;
   requires <module-name2>;

   exports <package-name1>;
   exports <package-name2>;

   exports <package-name> to <module-name>
}
We can use certain command-line options that help us to modify existing modules and add dependencies to them, export additional packages.
Below are the few command-line commands that can be used to modify an existing module.
1) --add-reads <module>=<target-module>(,<target-module>)*
The above command can update <module> to read < target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to read all nameless modules.
2) --add-exports <module>/<package>=<target-module>(,<target-module>)*
The above command can update <module> to export <package> to <target-module>, regardless of the module declaration. <target-module> can be ALL-UNNAMED to export to all nameless modules.
3) --add-opens <module>/<package>=<target-module>(,<target-module>)*
The above command update <module> to open <package> to <target-module>, regardless of the module declaration.
4) --patch-module <module>=<file>(;<file>)*
The above command can replace or increase a module with classes and resources in jar files or directories.
Static class in C#

The C# static class cannot be instantiated and can only have only static members. The static class in C# is sealed and cannot contain instance constructors.
The following is an example with static class and static members −
 Live Demo
using System;

public static class Demo {
   public static float PI = 3.14f;
   public static int calc(int n){return n*n;}
}

class Program {

   public static void Main(string[] args) {
      Console.WriteLine("PI: "+Demo.PI);
      Console.WriteLine("Square: " + Demo.calc(3));
   }
}
PI: 3.14
Square: 9
Above, the static class is −
public static class Demo {
   public static float PI = 3.14f;
   public static int calc(int n){return n*n;}
}
Above we have the following static members −
public static float PI = 3.14f;
public static int calc(int n){return n*n;}
How can we use nested transactions in MySQL?

We can work with nested transactions in MySQL with the help of SAVEPOINT.
Firstly, create a table. After that, begin the transaction.
Now, insert records in the table created above. Use SAVEPOINT statement to set a named transaction savepoint with a name of identifier.
Here are all the steps shown in the form of query −
Create table
mysql> create table NestedTransactionDemo
   -> (
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (0.63 sec)
Start the transaction −
mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)
Now, insert a record in the table
mysql> insert into NestedTransactionDemo values('John');
Query OK, 1 row affected (0.04 sec)
Display the record added above −
mysql> select *from NestedTransactionDemo;
+------+
| Name |
+------+
| John |
+------+
1 row in set (0.00 sec)
Let us begin with working on transactions to create nested transactions −
mysql> savepoint transaction2;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into NestedTransactionDemo values('David');
Query OK, 1 row affected (0.00 sec)
mysql> select *from NestedTransactionDemo;
+-------+
| Name  |
+-------+
| John  |
| David |
+-------+
2 rows in set (0.00 sec)

mysql> rollback to transaction2;
Query OK, 0 rows affected (0.00 sec)

mysql> select *from NestedTransactionDemo;
+------+
| Name |
+------+
| John |
+------+
1 row in set (0.00 sec)

mysql> rollback to transaction2;
Query OK, 0 rows affected (0.00 sec)
reflect.MethodByName() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MethodByName() Function in Golang is used to get function value corresponding to the method of v with the given name. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) MethodByName(name string) Value

Parameters: This function does not accept any parameter.
Return Value: This function returns a function value corresponding to the method of v with the given name.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.MethodByName() Function     package main     import (    "fmt"    "reflect")   // Main functiontype T struct {}  func (t *T) GFG() {    fmt.Println("GeeksForGeeks")}  func main() {    var t T    reflect.ValueOf(&t).MethodByName("GFG").Call([]reflect.Value{})}
Output:
GeeksForGeeks

Example 2:
// Golang program to illustrate// reflect.MethodByName() Function     package main     import (    "fmt"    "reflect")   // Main function  type YourT2 struct {}func (y YourT2) MethodFoo(i int, oo string) {    fmt.Println(i)    fmt.Println(oo)}  func Invoke(any interface{}, name string, args... interface{}) {    inputs := make([]reflect.Value, len(args))    for i, _ := range args {        inputs[i] = reflect.ValueOf(args[i])    }    reflect.ValueOf(any).MethodByName(name).Call(inputs)}  func main() {     Invoke(YourT2{}, "MethodFoo", 10, "Geekforgeeks")}
Output:
10
Geekforgeeks

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Slices in Golang
Golang Maps
Interfaces in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Trim a String in Golang?
How to set and unset cookies using jQuery?

16 Jun, 2020
An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our on cookies in the browser according to our need.
Cookies can be set in the browser with the help of JavaScript or the jQuery. Here we will be seeing how to set cookies in the browser with the help of jQuery and how to remove them later on.
Here we are using CDN of jQuery cookies to insert a cookie in the browser .
Note: Please keep your internet connection on while using this code as it uses CDN services for jQuery.
Example 1: Setting cookies in the  browser after that we will remove that cookie.
HTML
<!DOCTYPE html><html lang="en">   <head>      <meta charset="UTF-8">      <meta name="viewport"            content="width=device-width, initial-scale=1.0">      <title>Cookie | Geeksforgeeks</title>      <script src="https://code.jquery.com/jquery-3.5.1.min.js"integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="         crossorigin= "anonymous"></script>      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>   </head>   <body>      <center>          <h1 style="color: green">GeeksforGeeks</h1>        <button onclick="addCookie()">        Add Cookie        </button>        <button onclick="removeCookie()">        remove Cookie        </button>          <p></p>          <script>            let addCookie=()=>{            $.cookie("geeksforgeeks",             "It is the data of the cookie");            $("p").text("cookie added");            }            let removeCookie=()=>{            $.removeCookie("geeksforgeeks",             "It is the data of the cookie");            $("p").text("cookie removed");            }        </script>      </center>   </body></html>
Output: You can clearly see there is a cookie named GeeksforGeeks with a value. We can also set the cookie Expiry date.
Before adding Cookie: 
After adding Cookies:
After removing Cookie:
jQuery-Basics
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to get the value in an input text box using jQuery ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | OpenCV BGR color palette with trackbars

13 Nov, 2018
OpenCV is a library of programming functions mainly aimed at real-time computer vision.In this article, Let’s create a window which will contain RGB color palette with track bars. By moving the trackbars the value of RGB Colors will change b/w 0 to 255. So using the same, we can find the color with its RGB values.
Libraries needed:
OpenCV
Numpy
Approach:Create a black window with three color channels with resolution 512 x 512. Then create three ‘B’ ‘G’ ‘R’ trackbars using predefined functions of OpenCV library. Set the values of channels from 0 to 255. Merging the black window with these color trackbars.
# Python program to create RGB color  # palette with trackbars   # importing librariesimport cv2import numpy as np   # empty function called when# any trackbar movesdef emptyFunction():    pass   def main():          # blackwindow having 3 color chanels    image = np.zeros((512, 512, 3), np.uint8)     windowName ="Open CV Color Palette"          # window name    cv2.namedWindow(windowName)            # there trackbars which have the name    # of trackbars min and max value     cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction)    cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction)    cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction)           # Used to open the window    # till press the ESC key    while(True):        cv2.imshow(windowName, image)                  if cv2.waitKey(1) == 27:            break                  # values of blue, green, red        blue = cv2.getTrackbarPos('Blue', windowName)        green = cv2.getTrackbarPos('Green', windowName)        red = cv2.getTrackbarPos('Red', windowName)                  # merge all three color chanels and        # make the image composites image from rgb           image[:] = [blue, green, red]        print(blue, green, red)               cv2.destroyAllWindows()  # Calling main()         if __name__=="__main__":    main()
Output:
Note: Above programs will not run on online IDE.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to filter object array based on attributes?

02 Nov, 2020
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array. The filter() function loops or iterate over each array element and pass each element to the callback function.
Syntax:
var newArray = array.filter(function(item)
 {
  return conditional_statement;
 });

Note: The filter() function does not change the original array.
Example 1: We create an array of “students” and call the filter() function on array to derive the elements from array that satisfy the given condition.
Javascript
<script>var obj = {    'Students': [{            "name": "Raj",             "Age":"15",            "RollNumber": "123",            "Marks": "99",                      }, {            "name": "Aman",             "Age":"14",            "RollNumber": "223",            "Marks": "69",           },           {            "name": "Vivek",             "Age":"13",            "RollNumber": "253",            "Marks": "89",           },        ]};  var newArray = obj.Students.filter(function (el){  return el.Age >=15 &&         el.RollNumber <= 200 &&         el.Marks >= 80 ;});console.log(newArray);</script>
Output: After apply filter function on array, we get the first element of array as output as it satisfy the given condition.
Example 2: The following example shows filtering invalid entries from array. We create an array of “id”s and call the filter() function on the array to derive the “id”s whose values are non-zero and numeric. 
Javascript
<script>let array = [  { id: 3 },  { id: -1 },  { id: 0 },  { id: 15 },  { id: 12.2 },  { },  { id: null },  { id: NaN },  { id: 'undefined' }]  let countInvalidEntries = 0  function filterById(obj) {  if (Number.isFinite(obj.id) && obj.id !== 0)   {    return true  }   countInvalidEntries++  return false;}  let arrayById = array.filter(filterById);  console.log('Filtered Array with non-zero and numeric id: \n',        arrayById);  console.log('Number of Invalid Entries = ', countInvalidEntries);  </script>
Output: After applying filter() function on the array of size 9, we get 4 valid (non-zero and numeric) id and 5 invalid id
JavaScript-Misc
How To
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Itertools.islice()

27 Feb, 2020
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is islice().
Note: For more information, refer to Python Itertools
This iterator selectively prints the values mentioned in its iterable container passed as an argument.
Syntax:
islice(iterable, start, stop, step)

Example 1:
# Python program to demonstrate# the working of islice  from itertools import islice    # Slicing the range functionfor i in islice(range(20), 5):     print(i)            li = [2, 4, 5, 7, 8, 10, 20]   # Slicing the listprint(list(itertools.islice(li, 1, 6, 2)))  
Output:
0
1
2
3
4
[4, 7, 10]

Example 2:
from itertools import islice    for i in islice(range(20), 1, 5):     print(i)
Output:
1
2
3
4

Here we have provide the three-parameter that is range(), 1 and 5. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value.
Example 3:
from itertools import islice    for i in islice(range(20), 1, 5, 2):    print(i)
Output:
1
3

Here we provide the four-parameter that is range() as iterable, 1, 5 and 2 as stop value. So the first parameter that is iterable as range and second parameter 1 will be considered as start value and 5 will be considered as stop value and 2 will be considered as step value of how many steps to skip while iterating values.
Python-itertools
Python
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 ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Hello World in Scala

11 Feb, 2019
The Hello World! the program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In Scala, a basic program consists of the following:
object
Main Method
Statements or Expressions
Example:
// Scala program to print Hello World! object Geeks {    // Main Method     def main(args: Array[String])     {        // prints Hello World        println("Hello World!")     }}
Output:
Hello World!
Explanation:
object Geeks: object is the keyword which is used to create the objects. Objects are the instance of a class. Here “Geeks” is the name of the object.
def main(args: Array[String]): def is the keyword in Scala which is used to define the function and “main” is the name of Main Method. args: Array[String] are used for the command line arguments.
println(“Hello World!”): println is a method in Scala which is used to display the Output on console.
To use an online Scala compiler: We can use various online IDE. which can be used to run Scala programs without installing.
Using Command-Line: Make sure we have the Java 8 JDK (also known as 1.8). run javac -version in the command line and make sure we see javac 1.8.___ If we don’t have version 1.8 or higher, Install the JDK Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (.scala) extension. open the command prompt follow step by step process on your system.// Scala program to print Hello World! 
object Geeks 
{
    // Main Method 
    def main(args: Array[String]) 
    {
        // prints Hello World
        println("Hello World!") 
    }
}Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result.
// Scala program to print Hello World! 
object Geeks 
{
    // Main Method 
    def main(args: Array[String]) 
    {
        // prints Hello World
        println("Hello World!") 
    }
}
Step 1: Compile above file using scalac Hello.Scala after compilation it will generate a Geeks.class file and class file name is same as Object name(Here Object name is Geeks).Step 2: Now open the command with object name scala Geeks. It will give the result.
Using Scala IDE: IDE like IntelliJ IDEA, ENSIME run scala program easily. write the code in the text editor and press to run it.
Scala
Scala-Basics
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting System and Process Information Using C Programming and Shell in Linux

17 May, 2020
Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named “status” which has all the details of the process. We can get those Process Information Through shell as follows:
cat /proc/1/status

As can be seen, it displays most of the information about the process.
Note:, In this case, the process id is 1, it may be changed as per need.
You can get the System Information through the shell. The basic system information is stored in a file named os-release in /etc/ folder.
cat /etc/os-release

You can also get the System Information using C programming. The below code is used to get the details of the system. In this code, utsname maintains a structure that has the details of the system like sysname nodename, release, version, etc.
#include<stdio.h>#include<stdlib.h>#include<errno.h>#include<sys/utsname.h>int main(){   struct utsname buf1;   errno =0;   if(uname(&buf1)!=0)   {      perror("uname doesn't return 0, so there is an error");      exit(EXIT_FAILURE);   }   printf("System Name = %s\n", buf1.sysname);   printf("Node Name = %s\n", buf1.nodename);   printf("Version = %s\n", buf1.version);   printf("Release = %s\n", buf1.release);   printf("Machine = %s\n", buf1.machine);}
On execution the above code will give the following output:
To get Process Information using C programming, use the below code. In this code, we execute the Linux command through a c program to get the details of the process.
#include<stdio.h>#include<stdlib.h>int main(){   int r=system("cat /proc/1/status");}
On execution the above code will give the following output:
C Language
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Node.js process.chdir() Method

10 Jun, 2022
The process.chdir() method is an inbuilt application programming interface of the process module which is used to change the current working directory. Syntax:
process.chdir( directory )
Parameters: This method accepts single parameter as mentioned above and described below:
directory: It is required parameter that specifies the path to the directory to which current working directory to be changed.
Return Value: This method does not return any value on success but throws an exception if fails to change directory specifying that “no such file or directory”. Below examples illustrate the use of process.chdir() method in Node.js: Example 1: 
javascript
// Node.js program to demonstrate the    // process.chdir() Method  // Include process moduleconst process = require('process'); try {   // Change the directory  process.chdir('../os');  console.log("directory has successfully been changed");} catch (err) {       // Printing error if occurs  console.error("error while changing directory");}
Output:
directory has successfully been changed
Example 2: 
javascript
// Node.js program to demonstrate the    // process.chdir() Method  // Include process moduleconst process = require('process'); // Printing current directoryconsole.log("current working directory: "          + process.cwd());try {       // Change the directory  process.chdir('../os');  console.log("working directory after "          + "changing: " + process.cwd());} catch (err) {     // Printing error if occurs  console.error("error occurred while "        + "changing directory: " + err);}
Output:
current working directory: C:\nodejs\g\process
working directory after changing: C:\nodejs\g\os
Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/process.html#process_process_chdir_directory
nikhatkhan11
Node.js-process-module
Node.js
Web Technologies
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
turtle.sety() function in Python

30 Jun, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set the turtle’s second coordinate to y, leaving the first coordinate unchanged. Here, whatever the position of the turtle is, it set the y coordinate to given input keeping the x coordinate unchanged.
Syntax : turtle.sety(y)  
Parameter: 
y: a number (integer or float), it is the only one required argument.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(30) # check the turtle positionprint(turtle.position()) # set the y coordinateturtle.sety(-50) # check the turtle positionprint(turtle.position())
 
 
Output :
 
(0.0, 0.0)
(0.0, 30.0)
(0.0, -50.0)
 
Example 2 :
 
Python3
# import packageimport turtle # loop for patternfor i in range(4):     # motion  turtle.forward(100)  turtle.right(90)  turtle.forward(20)  turtle.right(90)  turtle.forward(100)     # set the y coordinate  turtle.up()  turtle.sety(-40*(i+1))  turtle.down()     # change the direction  turtle.left(180)
 
 
Output :
 
 
as5853535
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
How do you empty an array in C#?

To empty an array in C#, use the Array Clear() method: The Array.Clear method in C# clears i.e.zeros out all elements.
In the below example, we have first considered an array with three elements −
int[] arr = new int[] {88, 45, 76};
Now we have used the Array.Clear method to zero out all the arrays −
Array.Clear(arr, 0, arr.Length);
Let us see an example of Array.Clear method in c# −
 Live Demo
using System;
class Program {
   static void Main() {
      int[] arr = new int[] {88, 45, 76};
      Console.WriteLine("Array (Old):");
      foreach (int val in arr) {
         Console.WriteLine(val);
      }

      Array.Clear(arr, 0, arr.Length);
      Console.WriteLine("Array (After using Clear):");
      foreach (int val in arr) {
         Console.WriteLine(val);
      }
   }
}
Array (Old):
88
45
76
Array (After using Clear):
0
0
0