code-rag-bench/online-tutorials huggingface dataset:
Python | Extract odd length words in String

22 Apr, 2020
Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we first split the string to words and then perform iteration to get the odd length words.
# Python3 code to demonstrate working of # Extract odd length words in String# Using loop  # initializing stringtest_str = "gfg is best of geeks"  # printing original stringprint("The original string is : " + test_str)  # Extract odd length words in String# Using loopres = []for ele in test_str.split():    if len(ele) % 2 :        res.append(ele)  # printing result print("The odd length strings are : " + str(res)) 
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']

 
Method #2 : Using list comprehensionThis task can also be performed using list comprehension. In this, we perform the task in similar way as above. Just the difference is that its a one-liner.
# Python3 code to demonstrate working of # Extract odd length words in String# Using list comprehension  # initializing stringtest_str = "gfg is best of geeks"  # printing original stringprint("The original string is : " + test_str)  # Extract odd length words in String# Using list comprehensionres = [ele for ele in test_str.split() if len(ele) % 2]  # printing result print("The odd length strings are : " + str(res)) 
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']

Python string-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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
How to preload an audio in HTML5 ?

15 Mar, 2021
In this article, we will preload audio in HTML. We use preload=”auto” attribute to preload the audio file. The HTML Audio Preload Attribute is used to specify how the author thinks the audio should be loaded when the page loads. The audio preload attribute allows the author to indicate to the browser how the user experience of a website should be implemented. n some instances, this attribute can be ignored.
You have to know about HTML <audio> preload Attribute
Note: If autoplay is present, then the preload attribute is ignored.
Below are the examples that illustrates the use of preload attribute.
Example-1: When preload =” auto” 
HTML
<!DOCTYPE html><html><body>  <h1>GFG</h1>  <p>Hit the button for audio</p>  <audio controls preload="auto">     <source src="gfg.ogg" type="audio/ogg">     <source src="gfg.mp3" type="audio/mpeg">  </audio></body>    </html>
Output:
Example 1
Example 2: When preload = “none” :
HTML
<!DOCTYPE html><html>    <body>  <h1>GFG</h1>  <p>Hit the button for audio</p>    <audio controls preload="none">     <source src="gfg.ogg" type="audio/ogg">     <source src="gfg.mp3" type="audio/mpeg">  </audio></body>    </html>
Output:
Example 2
HTML-Questions
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
numpy.round_() in Python

04 Dec, 2020
The numpy.round_() is a mathematical function that rounds an array to the given number of decimals.
Syntax : numpy.round_(arr, decimals = 0, out = None)Parameters :array : [array_like] Input array.decimal : [int, optional] Decimal places we want to round off.
Default = 0. In case of -ve decimal, it specifies the n0. of positions to the left of the decimal point.
out : [optional] Output resulted array
Return :
An array with all array elements being
rounded off, having same type as input. 
 Code #1 : Working
# Python program explaining# round_() functionimport numpy as np  in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array)  round_off_values = np.round_(in_array)print ("\nRounded values : \n", round_off_values)    in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array)  round_off_values = np.round_(in_array)print ("\nRounded values : \n", round_off_values)  in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array)  round_off_values = np.round_(in_array, decimals = 3)print ("\nRounded values : \n", round_off_values)
Output :
Input array : 
 [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values : 
 [  0.   2.   2.   4.   4.  10.]

Input array : 
 [0.53, 1.54, 0.71]

Rounded values : 
 [ 1.  2.  1.]

Input array : 
 [0.5538, 1.33354, 0.71445]

Rounded values : 
 [ 0.554  1.334  0.714]
 Code #2 : Working
# Python program explaining# round_() functionimport numpy as np  in_array = [1, 4, 7, 9, 12]print ("Input array : \n", in_array)  round_off_values = np.round_(in_array)print ("\nRounded values : \n", round_off_values)    in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array)  round_off_values = np.round_(in_array, decimals = -2)print ("\nRounded values upto 2: \n", round_off_values)  in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array)  round_off_values = np.round_(in_array, decimals = -3)print ("\nRounded values upto 3: \n", round_off_values)
Output :
Input array : 
 [1, 4, 7, 9, 12]

Rounded values : 
 [ 1  4  7  9 12]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 2: 
 [100 300 400 400   0]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 3: 
 [0 0 0 0 0]
 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.round_.html#numpy.round_.
Python numpy-Mathematical Function
Python-numpy
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
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
Count the number of rows and columns of Pandas dataframe

01 Aug, 2020
In this article, we’ll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let’s see all these methods with the help of examples.
Example 1: We can use the dataframe.shape to get the count of rows and columns. dataframe.shape[0] and dataframe.shape[1] gives count of rows and columns respectively.
# importing the moduleimport pandas as pd  # creating a DataFramedict = {'Name' : ['Martha', 'Tim', 'Rob', 'Georgia'],        'Marks' : [87, 91, 97, 95]}df = pd.DataFrame(dict)  # displaying the DataFramedisplay(df)  # fetching the number of rows and columnsrows = df.shape[0]cols = df.shape[1]  # displaying the number of rows and columnsprint("Rows: " + str(rows))print("Columns: " + str(cols))
Output :
Example 2 : We can use the len() method to get the count of rows and columns. dataframe.axes[0] represents rows and dataframe.axes[1] represents columns. So, dataframe.axes[0] and dataframe.axes[1] gives the count of rows and columns respectively.
# importing the moduleimport pandas as pd  # creating a DataFramedict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'],        'Marks':[87, 91, 97, 95]}df = pd.DataFrame(dict)  # displaying the DataFramedisplay(df)  # fetching the number of rows and columnsrows = len(df.axes[0])cols = len(df.axes[1])  # displaying the number of rows and columnsprint("Rows: " + str(rows))print("Columns: " + str(cols))
Output :
Example 3 : Similar to the example 2, dataframe.index represents rows and dataframe.columns represents columns. So, len(dataframe.index) and len(dataframe.columns) gives count of rows and columns respectively.
# importing the moduleimport pandas as pd  # creating a DataFramedict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'],        'Marks':[87, 91, 97, 95]}df = pd.DataFrame(dict)  # displaying the DataFramedisplay(df)  # fetching the number of rows and columnsrows = len(df.index)cols = len(df.columns)  # displaying the number of rows and columnsprint("Rows: " + str(rows))print("Columns: " + str(cols))
Output :
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GroupBy() Method in C#

The GroupBy() is an extension method that returns a group of elements from the given collection based on some key value.
The following is our array −
int[] arr = { 2, 30, 45, 60, 70 };
Now, we will use GroupBy() to group the elements smaller than 50 −
arr.GroupBy(b => chkSmaller(b));
The above chkSmaller() finds the elements smaller than 50.
Let us see the complete code −
 Live Demo
using System;
using System.Linq;

class Demo {
   static void Main() {
      int[] arr = { 2, 30, 45, 60, 70 };
      var check = arr.GroupBy(b => chkSmaller(b));

      foreach (var val in check) {
         Console.WriteLine(val.Key);
         foreach (var res in val) {
            Console.WriteLine(res);
         }
      }
   }
   static bool chkSmaller(int a) {
      return a <= 50;
   }
}
True
2
30
45
False
60
70
SAP ABAP - If Statement

‘IF’ is a control statement used to specify one or more conditions. You may also nest the IF control structures in an ABAP program.
The following syntax is used for the IF statement.
IF<condition_1>.
  
<Statements...>.
  
ENDIF.

If the expression evaluates to true, then the IF block of code will be executed.
Report YH_SEP_15.  
Data Title_1(20) TYPE C.
Title_1 = 'Tutorials'.  
IF Title_1 = 'Tutorials'.  
write 'This is IF statement'.  
ENDIF.
The above code produces the following output −
This is IF statement.


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to access the private methods of a class from outside of the class in Java?

You can access the private methods of a class using java reflection package.
Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.
import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod() {
      System.out.println("hello");
   }
}

public class SampleTest {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}
Python OpenCV – cv2.flip() method - GeeksforGeeks

08 Jul, 2020
OpenCV-Python is a library of programming functions mainly aimed at real-time computer vision. cv2.flip() method is used to flip a 2D array. The function cv::flip flips a 2D array around vertical, horizontal, or both axes.
Syntax: cv2.cv.flip(src, flipCode[, dst] )
Parameters:src: Input array.dst: Output array of the same size and type as src.flip code: A flag to specify how to flip the array; 0 means flipping around the x-axis and positive value (for example, 1) means flipping around y-axis. Negative value (for example, -1) means flipping around both axes.
Return Value: It returns an image.
Image used for all the below examples:
Example:
# Python program to explain cv2.flip() method  # importing cv2import cv2  # pathpath = r'C:\Users\user\Desktop\geeks14.png'  # Reading an image in default modesrc = cv2.imread(path)  # Window name in which image is displayedwindow_name = 'Image'  # Using cv2.flip() method# Use Flip code 0 to flip verticallyimage = cv2.flip(src, 0)  # Displaying the imagecv2.imshow(window_name, image)cv2.waitKey(0)
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python | os.cpu_count() method - GeeksforGeeks

11 Oct, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.cpu_count() method in Python is used to get the number of CPUs in the system. This method returns None if number of CPUs in the system is undetermined.
Syntax: os.cpu_count()
Parameter: No parameter is required.
Return Type: This method returns an integer value which denotes the number of CPUs in the system. None is returned if the number of CPUs is undetermined.
# Python program to explain os.cpu_count() method    # importing os module import os    # Get the number of CPUs# in the system using# os.cpu_count() methodcpuCount = os.cpu_count()  # Print the number of# CPUs in the systemprint("Number of CPUs in the system:", cpuCount)
Number of CPUs in the system: 4

gabaa406
python-os-module
Python
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
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
How To Parse Data Using Python and Selenium | by Mahbub Zaman | Towards Data Science

Previously I talked about Selenium and how to use it with Ruby. Today, I’ll show you how we can use Selenium with Python. Have a look at the following post if you want to go through the basics of Selenium. In that post, I’ve briefly covered what Selenium is and when we can use it.
towardsdatascience.com
From this post, you’ll learn how to parse some data using Python, Selenium, and ChromeDriver.
For this setup, we need to install a Python package and ChromeDriver. Also, make sure you have Python installed on your machine. I’m using macOS. You can quickly check which version of Python you’re running by using the following command.
python --version
In my case, I’m running Python version 3.8.8. Now, run the following command in your terminal. Here we are using pip (package installer for Python) to install the package.
pip install selenium
After installing Selenium, we need to install the ChromeDriver. I’m using Homebrew to install the driver.
brew install chromedriver
Here are some basic troubleshooting steps for macOS if you’re facing any problems with the driver.
Chromedriver cannot be opened because the developer cannot be verified.
Chromedriver cannot be opened because the developer cannot be verified.
open /opt/homebrew/Caskroom/chromedriver
First, open the chromedriver folder in the finder. After that, right-click on the chromedriver file and select open. It should fix the problem.
2. This version of ChromeDriver only supports Chrome version # Current browser version is # with binary path.
We need to make sure the version of ChromeDriver and Chrome browser are the same.
brew upgrade --cask chromedriver
Brilliant, we are done with the initial setup. Now you can download the Python script from GitHub. Let’s break down the individual ingredients of the web_scraper.py file.
First, we added a headless option. Then we initialize a Chrome webdirver with the option. Now, we navigate the URL along with the page number. After that, we extract all the elements from the page using the find_elements_by_class_name method, and finally, we loop through all the elements and extract a single element using the find_element_by_class_name method. Now, we can increment the page number by one and repeat the same process until no data is left to parse. You can read all the available WebDriver API from here.
If you don’t provide the headless option, it will open a chrome browser and run the rest of the code. If that’s your desired behavior, remove lines 23, 24, and modify line 25 like below.
driver = webdriver.Chrome()
I hope this post will help you to get started with Python, Selenium, and ChromeDriver. If you visit the toscrape website, you can find different ways you can navigate data. For example, rather than navigating pages using pagination, we can use the infinite scroll pagination. If you’re interested to learn about Python, then check out my Python cheatsheet on GitHub. Happy coding!
How to handle windows file upload using Selenium WebDriver?

We can handle windows file upload with Selenium webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded].
This is only applied to an element having a type attribute set to file as value along with the element tagname as input. The below html code shows the element with type = file value set.
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class WndsFileUpl{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm");
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//input[@type='file']"));
      // windows file upload with file path
      m.sendKeys("C:\\Users\\Pictures\\Logo.jpg");
      driver.close();
   }
}
Optimized Link State Routing Protocol - GeeksforGeeks

11 Aug, 2020
OLSR stands for Optimized Link State Routing Protocol. In this, each node periodically floods status of its links. Each node re-broadcasts link state information received from its neighbors. Each node keeps track of link state information received from other nodes. Each node uses above information to determine next hope to each destination. It is proactive and table-driven.
Link State Routing :
Each node expands a spanning tree.
Each node can obtain the whole network topology.
Example :
TC(6) = <4, 5, 7>
Node 6 generates a TC message advertising nodes in MS(6) = {4, 5, 7}.
Node 4 forwards TC(6) from Node 6 and Node 3 forwards TC(6) from Node 4.
After nodes 3, 4 and 6 have generated TC messages, all nodes have link-state information to route to any node.
It utilizes a technique to reduce message flooding – MultiPoint Relaying (MPR).
In this, each node N in the network selects a set of neighbor nodes as multipoint relays, MPR(N), that retransmit control packets from N- Neighbors not in MPR(N) process control packets from N, but they do not forward the packets. MPR(N) is selected such that all two-hops neighbors of N are covered by (one-hop neighbors) of MPR(N).
Advantages of OLSR :
OLSR has less average end-to-end delay therefore it is used for applications which needs minimum delay.
The OLSR implementation is more user friendly and worked with fewer headaches than other protocols.
It is also a flat routing protocol.
It does not need a central administrative system to handle its routing process.
It increases protocol’s suitability for an ad hoc network with the rapid changes of the source and destination pairs.
It does not require the link which is reliable in controlling messages, since the messages are sent periodically and the delivery does not have to be sequential.
Disadvantages of OLSR :
It maintains routing table for all the possible routes.
When the number of mobile hosts increases, then the overhead from the control messages also increases.
It needs considerable time to re-discover a broken link.
It requires more processing power than other protocols when discovering an alternate route.
Computer Networks-Network Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Active and Passive attacks in Information Security
Cryptography and its Types
Multiple Access Protocols in Computer Network
Architecture of Internet of Things (IoT)
Intrusion Detection System (IDS)
Bluetooth
GSM in Wireless Communication
Congestion Control in Computer Networks
TCP Congestion Control
Program to create one triangle stair by using stars in Python

Suppose we have a number n, we have to find a string of stairs with n steps. Here each line in the string is separated by a newline separator.
So, if the input is like n = 5, then the output will be
         *
        **
       ***
      ****
     *****
To solve this, we will follow these steps −
s := blank string
for i in range 0 to n-1, dos := s concatenate (n-i-1) number of blank space concatenate (i+1) number of starsif i < n-1, thens := add one new line after s
s := s concatenate (n-i-1) number of blank space concatenate (i+1) number of stars
if i < n-1, thens := add one new line after s
s := add one new line after s
return s
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n):
      s ="" for i in range(n):
      s+= " "*(n-i-1)+"*"*(i+1)
      if(i<n-1):
         s+="\n"
      return s
ob = Solution()
print(ob.solve(5))
5
*
**
***
****
*****
Role of super Keyword in Java Inheritance

Parent class objects can be referred to using the super keyword in Java. It is usually used in the context of inheritance. A program that demonstrates the super keyword in Java is given as follows:
 Live Demo
class A {
   int a;
   A(int x) {
      a = x;
   }
}
class B extends A {
   int b;
   B(int x, int y) {
      super(x);
      b = y;
   }
   void print() {
      System.out.println("Value of a: " + a);
      System.out.println("Value of b: " + b);
   }
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B(7, 3);
      obj.print();
   }
}
Value of a: 7
Value of b: 3
Now let us understand the above program.
The class A contains a data member a and constructor A(). The class B uses the extends keyword to derive from class A. It also contains a data member b and constructor B(). The method print() prints the values of a and b. A code snippet which demonstrates this is as follows:
class A {
   int a;
   A(int x) {
      a = x;
   }
}
class B extends A {
   int b;
   B(int x, int y) {
      super(x);
      b = y;
   }
   void print() {
      System.out.println("Value of a: " + a);
      System.out.println("Value of b: " + b);
   }
}
In the main() method in class Demo, an object obj of class B is created. Then the method print() is called. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String args[]) {
      B obj = new B(7, 3);
      obj.print();
   }
}
Creating an array of objects based on another array of objects JavaScript

Suppose, we have an array of objects containing data about likes of some users like this −
const arr = [
   {"user":"dan","liked":"yes","age":"22"},
   {"user":"sarah","liked":"no","age":"21"},
   {"user":"john","liked":"yes","age":"23"},
 ];
We are required to write a JavaScript function that takes in one such array. The function should construct another array based on this array like this −
const output = [
   {"dan":"yes"},
   {"sarah":"no"},
   {"john":"yes"},
];
const arr = [
   {"user":"dan","liked":"yes","age":"22"},
   {"user":"sarah","liked":"no","age":"21"},
    {"user":"john","liked":"yes","age":"23"},
];
const mapToPair = (arr = []) => {
   const result = arr.map(obj => {
      const res = {};
      res[obj['user']] = obj['liked'];
      return res;
   });
   return result;
};
console.log(mapToPair(arr));
And the output in the console will be −
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]
How to make multipartite graphs using networkx and Matplotlib?

To make multipartite graph in networkx, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a list of subset sizes and colors.
Create a list of subset sizes and colors.
Define a method for multilayered graph that could return a multilayered graph object.
Define a method for multilayered graph that could return a multilayered graph object.
Set the color of the nodes.
Set the color of the nodes.
Position the nodes in layers of straight lines.
Position the nodes in layers of straight lines.
Draw the graph G with Matplotlib.
Draw the graph G with Matplotlib.
Set equal axis properties.
Set equal axis properties.
To display the figure, use show() method.
To display the figure, use show() method.
import itertools
import matplotlib.pyplot as plt
import networkx as nx

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

subset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]
subset_color = [
   "gold",
   "violet",
   "violet",
   "violet",
   "violet",
   "limegreen",
   "limegreen",
   "darkorange",
]

def multilayered_graph(*subset_sizes):
   extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))
   layers = [range(start, end) for start, end in extents]
   G = nx.Graph()
   for (i, layer) in enumerate(layers):
      G.add_nodes_from(layer, layer=i)
   for layer1, layer2 in nx.utils.pairwise(layers):
      G.add_edges_from(itertools.product(layer1, layer2))
   return G

G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
pos = nx.multipartite_layout(G, subset_key="layer")
nx.draw(G, pos, node_color=color, with_labels=False)

plt.axis("equal")

plt.show()
Python | Addition of tuples

11 Nov, 2019
Sometimes, while working with records, we might have a common problem of adding contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + lambdaCombination of above functionalities can solve the problem for us. In this, we compute the summation using lambda functions and extend the logic to keys using map().
# Python3 code to demonstrate working of# Addition of tuples# using map() + lambda  # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18)  # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Addition of tuples# using map() + lambdares = tuple(map(lambda i, j: i + j, test_tup1, test_tup2))  # printing resultprint("Resultant tuple after addition : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after addition : (12, 9, 23)

 
Method #2 : Using map() + zip() + sum()The combination of above functions can also be used to achieve this particular task. In this, we add inbuilt sum() to perform summation and zip the like indices using zip() and extend logic to both tuples using map().
# Python3 code to demonstrate working of# Addition of tuples# using map() + zip() + sum()  # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18)  # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Addition of tuples# using map() + zip() + sum()res = tuple(map(sum, zip(test_tup1, test_tup2)))  # printing resultprint("Resultant tuple after addition : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after addition : (12, 9, 23)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy matrix.round()

23 Apr, 2019
With the help of Numpy matrix.round() method, we are able to round off the values of the given matrix.
Syntax : matrix.round()
Return : Return rounded values in matrix
Example #1 :
In the given example we are able to round off the given matrix by using matrix.round() method.
# import the important module in pythonimport numpy as np           # make matrix with numpygfg = np.matrix('[6.4, 1.3; 12.7, 32.3]')           # applying matrix.round() methodgeeks = gfg.round()     print(geeks)
[[  6.   1.]
 [ 13.  32.]]

 Example #2 :
# import the important module in pythonimport numpy as np           # make a matrix with numpygfg = np.matrix('[1.2, 2.3; 4.7, 5.5; 7.2, 8.9]')           # applying matrix.round() methodgeeks = gfg.round()     print(geeks)
[[ 1.  2.]
 [ 5.  6.]
 [ 7.  9.]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
matplotlib.axes.Axes.step() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.errorbar() function in axes module of matplotlib library is used to make a step plot..
Syntax:
Axes.step(self, x, y, *args, where='pre', data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the horizontal and vertical coordinates of the data points.
fmt: This parameter is an optional parameter and it contains the string value.
data: This parameter is also an optional parameter. And it is the object with labelled data.
where: This parameter is also an optional parameter. And it is used to define where the steps should be placed. The values are {‘pre’, ‘post’, ‘mid’}. pre is the default value
Returns: This returns the following:
lines:This returns the list of Line2D objects representing the plotted data.
Below examples illustrate the matplotlib.axes.Axes.step() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib function      import numpy as npimport matplotlib.pyplot as plt  x = np.arange(16)y = np.sin(x / 3)  fig, ax = plt.subplots()  ax.step(x, y + 2, color ='green')ax.plot(x, y + 2, 'o--', color ='black', alpha = 0.3)  ax.set_title('matplotlib.axes.Axes.step Example1')plt.show()
Output:
Example-2:
# Implementation of matplotlib function      import numpy as npimport matplotlib.pyplot as plt  x = np.arange(16)y = np.sin(x / 3)  fig, ax = plt.subplots()  ax.step(x, y + 2, label ='pre (default)')ax.plot(x, y + 2, 'o--', color ='black', alpha = 0.3)  ax.step(x, y + 1, where ='mid', label ='mid')ax.plot(x, y + 1, 'o--', color ='black', alpha = 0.3)  ax.step(x, y, where ='post', label ='post')ax.plot(x, y, 'o--', color ='black', alpha = 0.3)  ax.grid(axis ='x', color ='0.95')ax.legend(title ='Parameter where:')ax.set_title('matplotlib.axes.Axes.step Example2')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js path.resolve() Method

13 Oct, 2021
The path.resolve() method is used to resolve a sequence of path-segments to an absolute path. It works by processing the sequence of paths from right to left, prepending each of the paths until the absolute path is created. The resulting path is normalized and trailing slashes are removed as required.If no path segments are given as parameters, then the absolute path of the current working directory is used.Syntax: 
path.resolve( [...paths] )

Parameters: This function accepts one parameter as mentioned above and described below: 
paths: It is a series of file paths that would be resolved together to form an absolute path. It throws a TypeError if this parameter is not a string value.
Return Value: It returns a string with absolute path. 
Below programs illustrate the path.resolve() method in Node.js: 
Example 1: 
Node.js
// Node.js program to demonstrate the   // path.resolve() Method    // Import the path moduleconst path = require('path');   console.log("Current directory:", __dirname);   // Resolving 2 path-segments// with the current directorypath1 = path.resolve("users/admin", "readme.md");console.log(path1)   // Resolving 3 path-segments// with the current directorypath2 = path.resolve("users", "admin", "readme.md");console.log(path2)   // Treating of the first segment// as root, ignoring the current directorypath3 = path.resolve("/users/admin", "readme.md");console.log(path3)
Output: 
Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\users\admin\readme.md

Example 2: 
Node.js
// Node.js program to demonstrate the   // path.resolve() Method    // Import the path moduleconst path = require('path');   console.log("Current directory:", __dirname);   // Normalization of the absolute pathspath1 = path.resolve("users", "..", "readme.md");console.log(path1)   path2 = path.resolve("users", "admin",             "..", "files", "readme.md");console.log(path2)   path3 = path.resolve("users", "admin",            "..", "files", "..", "readme.md");console.log(path3)
Output: 
Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\readme.md
G:\tutorials\nodejs-path-resolve\users\files\readme.md
G:\tutorials\nodejs-path-resolve\users\readme.md

Reference: https://nodejs.org/api/path.html#path_path_resolve_paths
Node.js-path-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.noop() Method

14 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. 
The Lodash _.noop() method is used to return “undefined” irrespective of the arguments passed to it.
Syntax: 
_.noop()

Parameters: This method can take optional parameters of any type.
Returns: This method returns undefined.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");                // Use of _.noop() method let val = undefined; let val2 = _.noop();   if (val == val2)     console.log("val and val2 are equal"); else    console.log(`val and val2 are not equal`);
Output:
val and val2 are equal

Example 2:
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.noop() method let obj = new Object(_.noop()) console.log(`Object is ${obj.Object}`)     // Use of _.noop() method  let arr = new Array(_.noop()) console.log(`Array is ${arr[0]}`)
Output :
Object is undefined
Array is undefined

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to close a dialog box in windows?

17 May, 2020
The dialog box is a graphical control element in the form of a small window that communicates information to the user and prompts them for a response.
There are two types of dialog boxes:
Modal:These dialog boxes block the interaction with the software that initiated the dialog.These are used when the user input is required before going ahead with the processing.
These dialog boxes block the interaction with the software that initiated the dialog.
These are used when the user input is required before going ahead with the processing.
Modeless:These do not block the interaction with software that initiated the dialog.These are used when the requested information is not essential to continue, and so the window can be left open while work continues elsewhere.
These do not block the interaction with software that initiated the dialog.
These are used when the requested information is not essential to continue, and so the window can be left open while work continues elsewhere.
These dialog boxes interrupt our flow while working and the following steps can be followed to close them.
Usually the dialog box contains information for the user to read and few options according to the information.
Via GUI:You can choose one of the options or directly click on the “X” symbol on the top-right corner of the dialog box.
Via Keys:If you are used to command-line and are not comfortable with using a mouse, you can press “Esc” key to cancel the dialog box. If you prefer to select the options given, use the “tab/arrow” key(s) to navigate between the options and press enter when the chosen option is highlighted.Note: The user input would directly close the dialog box.
Note: The user input would directly close the dialog box.
Sometimes the dialog box gets struck and we will not be able to go ahead. In such cases, save the current work and close the entire application to start again.
Using the task bar:Right-click the icon referring to the dialog box from the Windows taskbar and click “Close”.
Using the Task Manager:Open the Task Manager using the search bar(“ctrl + alt + del”), right-click on the application that you want to close and click on “End task”.
Either restart the system or shut down and start again.
Picked
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are pointers in C#?

Pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location.
The syntax of a pointer is −
type *var-name;
The following is how you can declare a pointer type −
double *z; /* pointer to a double */
C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.
The following is our module showing how to declare and use a pointer variable. We have used unsafe modifier here −
static unsafe void Main(string[] args) {
   int val = 50;
   int* x = &val;

   Console.WriteLine("Data: {0} ", val);
   Console.WriteLine("Address: {0}", (int)x);
   Console.ReadKey();
}
PyQt5 QDockWidget – Setting Layout - GeeksforGeeks

31 Jan, 2022
In this article we will see how we can set the layout to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Layout specifies how the internal component will be arranged. 
In order to do this we will use setLayout method with the dock widget object.Syntax : dock.setLayout(layout)Argument : It takes QLayout object as argumentReturn : It returns None  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating dock widget        dock = QDockWidget(self)         # setting title to the dock widget        dock.setWindowTitle("GfG Dock")          # push button        push = QPushButton("Press", self)         # setting widget to the dock        dock.setWidget(push)         # creating a label        label = QLabel("GeeksforGeeks", self)         # setting geometry to the label        label.setGeometry(100, 200, 300, 80)         # making label multi line        label.setWordWrap(True)         # setting geometry tot he dock widget        dock.setGeometry(100, 0, 200, 30)         # creating a vertical layout        layout = QVBoxLayout(self)         # setting layout to the dock        dock.setLayout(layout)        # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
sweetyty
Python PyQt-QDockWidget
Python-gui
Python-PyQt
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
What is the difference between re.match(), re.search() and re.findall() methods in Python?

re.match(), re.search() and re.findall() are methods of the Python module re.
The re.match() method finds match if it occurs at start of the string. For example, calling match() on the string ‘TP Tutorials Point TP’ and looking for a pattern ‘TP’ will match.  
import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print result.group(0)
TP
The re.search() method is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. 
import re
result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print result.group(0)
Tutorials
The re.findall() helps to get a list of all matching patterns. It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both.
import re
result = re.search(r'TP', 'TP Tutorials Point TP')
print result.group()
TP
How to show the index of the selected option in a dropdown list with JavaScript?

To show the index of the selected option in a drop-down list, use the selectedIndex property in JavaScript.
You can try to run the following code to display the index of the selected option −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <form id="myForm">
         <select id="selectNow">
            <option>One</option>
            <option>Two</option>
            <option>Three</option>
          </select>
          <input type="button" onclick="display()" value="Click">
      </form>
      <p>Select and click the button to get the index of the selected option.</p>
      <script>
         function display() {
            var index = document.getElementById("selectNow").selectedIndex;
            document.write(index);
         }
      </script>
   </body>
</html>
Role of CSS Grid Container

Grid Container in CSS has grid items. These items are placed inside rows and columns. Let us create a
CSS Grid container and set the number of columns in a Grid:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .container {
            display: grid;
            background-color: blue;
            grid-template-columns: auto auto;
            padding: 20px;
            grid-gap: 20px;
         }
         .container > div {
            background-color: orange;
            border: 2px solid gray;
            padding: 35px;
            font-size: 30px;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <h1>Game Board</h1>
      <div class = "container">
         <div class = "ele1">1</div>
         <div class = "ele2">2</div>
         <div class = "ele3">3</div>
         <div class = "ele4">4</div>
         <div class = "ele5">5</div>
         <div class = "ele6">6</div>
      </div>
   </body>
</html>
How to determine the version of the C++ standard used by the compiler?

Sometimes we need to know that, what is the current C++ standard. To get this kind of information, we can use the macro called __cplusplus. For different standards, the value of this will be like below.
#include<iostream>
int main() {
   if (__cplusplus == 201703L)
      std::cout << "C++17" << endl;
   else if (__cplusplus == 201402L)
      std::cout << "C++14" << endl;
   else if (__cplusplus == 201103L)
      std::cout << "C++11" << endl;
   else if (__cplusplus == 199711L)
      std::cout << "C++98" << endl;
   else
      std::cout << "pre-standard C++" << endl;
}
C++98
Fade In Down Animation Effect with CSS

To implement Fade In Down Big Animation Effect on an image with CSS, you can try to run the following code −
Live Demo
<html>
   <head>
      <style>
         .animated {
            background-image: url(/css/images/logo.png);
            background-repeat: no-repeat;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;
            animation-duration: 10s;
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
         }

         @-webkit-keyframes fadeInDown {
            0% {
               opacity: 0;
               -webkit-transform: translateY(-20px);
            }
            100% {
               opacity: 1;
               -webkit-transform: translateY(0);
            }
         }

         @keyframes fadeInDown {
            0% {
               opacity: 0;
               transform: translateY(-20px);
            }
            100% {
               opacity: 1;
               transform: translateY(0);
            }
         }

         .fadeInDown {
            -webkit-animation-name: fadeInDown;
            animation-name: fadeInDown;
         }
      </style>
   </head>

   <body>
      <div id="animated-example" class="animated fadeInDown"></div>
      <button onclick="myFunction()">Reload page</button>

      <script>
         function myFunction() {
            location.reload();
         }
      </script>

   </body>
</html>
Tryit Editor v3.7

Tryit: Using the animation-iteration-count property