code-rag-bench/online-tutorials huggingface dataset:
Program to find the minimum (or maximum) element of an array in C++

In this problem, we are given an array arr[] of n integers. Our task is to
create a program to find the minimum and maximum element of an array in
C++.
Problem Description − Here, we have an array arr[]. The contains n integer values. We have to find the maximum value and minimum value out of all values of the array.
Let’s take an example to understand the problem,
arr[] = {2, 1, 6, 9, 4, 10, 15, 21}
max = 21 , min = 1
There can be multiple solutions to the problem,
One solution would be directly comparing elements of the array. This is done by checking if each element of the array and then find the max and min using comparison.
This can be done using two different approaches,
Iterative Approach
Recursive Approach
Iterative approach to solve the problem,
We will loop for the array, extract each element of the array, and compare it
with the max and min element of the array.
Program to illustrate that working of our solution,
 Live Demo
#include <iostream>
using namespace std;
void getMinMax(int arr[] , int N){
   int max = arr[0], min = arr[0];
   for(int i = 1; i < N; i++){
      if(max < arr[i])
         max = arr[i];
      if(min > arr[i])
         min = arr[i];
   }
   cout<<"Maximum Value = "<<max<<"\n";
   cout<<"Minimum Value = "<<min;
}
int main(){
   int arr[] = {2, 1, 6, 9, 4, 10, 15, 21};
   int N = 8;
   getMinMax(arr, N);
   return 0;
}
Maximum Value = 21
Minimum Value = 1
In this approach, we will solve the problem by finding the max and min of
all elements of the array by recursively calling the method again and again
for all elements of the array.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int CalcMinValue(int arr[], int n) {
   return (n == 1) ? arr[0] : min(arr[n - 1], CalcMinValue(arr, n - 1));
}
int CalcMaxValue(int arr[], int n) {
   return (n == 1) ? arr[0] : max(arr[n -1], CalcMinValue(arr, n - 1));
}
int main() {
   int arr[] = {2, 1, 6, 9, 4, 10, 15, 21};
   int N = 8;
   cout<<"Maximum Value = "<<CalcMaxValue(arr, N)<<endl;
   cout<<"Minimum Value = "<<CalcMinValue(arr, N);
   return 0;
}
Maximum Value = 21
Minimum Value = 1
This problem can also be solved using the inbuild functions that are
provided in the standard template library of the C++ programming language.
The methods to find the solution are min_element() and max_element() and
these methods are found in the bits/stdc++.h library in C++.
Program to illustrate the solution to the problem,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {2, 1, 6, 9, 4, 10, 15, 21};
   int N = 8;
   cout<<"Maximum Value = "<<(*max_element(arr, arr+N))<<endl;
   cout<<"Minimum Value = "<<(*min_element(arr, arr+N));
   return 0;
}
Maximum Value = 21
Minimum Value = 1
Python – seaborn.PairGrid() method

15 Jul, 2020
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are ?
Default Matplotlib parameters
Working with data frames
As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half way through Seaborn.
Subplot grid for plotting pairwise relationships in a dataset.
This class maps each variable in a dataset onto a column and row in a grid of multiple axes. Different axes-level plotting functions can be used to draw bivariate plots in the upper and lower triangles, and the the marginal distribution of each variable can be shown on the diagonal.
It can also represent an additional level of conditionalization with the hue parameter, which plots different subsets of data in different colors. This uses color to resolve elements on a third dimension, but only draws subsets on top of each other and will not tailor the hue parameter for the specific visualization the way that axes-level functions that accept hue will.
                    seaborn.PairGrid( data, \*\*kwargs)


Seaborn.PairGrid uses many arguments as input, main of which are described below in form of table:
Below is the implementation of above method:
Example 1:
Python3
# importing packagesimport seabornimport matplotlib.pyplot as plt  # loading datasetdf = seaborn.load_dataset('tips')  # PairGrid object with huegraph = seaborn.PairGrid(df, hue ='day')# type of graph for diagonalgraph = graph.map_diag(plt.hist)# type of graph for non-diagonalgraph = graph.map_offdiag(plt.scatter)# to add legendsgraph = graph.add_legend()# to showplt.show()# This code is contributed by Deepanshu Rusatgi.
Python3
# importing packagesimport seabornimport matplotlib.pyplot as plt  # loading datasetdf = seaborn.load_dataset('tips')  # PairGrid object with huegraph = seaborn.PairGrid(df)# type of graph for non-diagonal(upper part)graph = graph.map_upper(sns.scatterplot)# type of graph for non-diagonal(lower part)graph = graph.map_lower(sns.kdeplot)# type of graph for diagonalgraph = graph.map_diag(sns.kdeplot, lw = 2)# to showplt.show()# This code is contributed by Deepanshu Rusatgi.
Data Visualization
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to select all children of an element except the last child using CSS?

29 Mar, 2019
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
Syntax:
element:not(:last-child) { 
    // CSS Style
}

Example 1: This example creates a navigation menu separated by right border except the last element.
<!DOCTYPE html><html>      <head>    <title>        Example to select all children        except the last    </title>          <!-- CSS style to create nav bar -->    <style>        nav {            margin: 30px;        }        nav a {            text-transform: capitalize;            text-decoration: none;            color: rgba(60, 60, 60);            font-family: sans-serif;            padding: 10px 10px;            margin-top: 30px;            width: 150px;            text-align: center;            display: inline-block;        }        nav a:not(:last-child) {            border-right: 5px solid greenyellow;        }    </style></head>  <body>    <nav>        <a href="#">Home</a>        <a href="#">About</a>        <a href="#">Blog</a>        <a href="#">Geeksforgeeks</a>        <a href="#">Articles</a>        <a href="#">Contact Me</a>    </nav></body>  </html>                    
Output:
Example 2: This example creates a navigation menu and uses some CSS property except the last element.
<!DOCTYPE html><html>      <head>    <title>        Example to select all children        except the last    </title>          <!-- CSS style to create nav bar -->    <style>        nav {            margin: 30px;        }        nav a {            text-transform: capitalize;            text-decoration: none;            color: rgba(60, 60, 60);            font-family: sans-serif;            padding: 10px 10px;            margin-top: 30px;            width: 150px;            text-align: center;            display: inline-block;            border: 2px solid black;            border-radius: 5px;        }        nav a:not(:last-child) {            background-color:greenyellow;        }    </style></head>  <body>    <nav>        <a href="#">Home</a>        <a href="#">About</a>        <a href="#">Blog</a>        <a href="#">Geeksforgeeks</a>        <a href="#">Articles</a>        <a href="#">Contact Me</a>    </nav></body></html>                    
Output:
CSS-Selectors
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Shift last element to first position in list

26 Feb, 2019
The cyclic rotations have been discussed in the earlier articles. But sometimes, we just require a specific task, a part of rotation i.e shift last element to first element in list. This has the application in day-day programming in certain utilities. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list slicing and “+” operatorThe combination of these functions can be used to perform the task of a single shift in list. The last element is added to the rest of the list to achieve this task using slicing.
# Python3 code to demonstrate# shift last element to first # using list slicing and "+" operator  # initializing list test_list = [1, 4, 5, 6, 7, 8, 9, 12]  # printing the original listprint ("The original list is : " + str(test_list))  # using list slicing and "+" operator# shift last element to firsttest_list = test_list[-1:] + test_list[:-1]   # printing resultprint ("The list after shift is : " + str(test_list))
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]

 
Method #2 : Using insert() + pop()This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop(). The pop function returns the last element and that is inserted at front using the insert function.
# Python3 code to demonstrate# shift last element to first # using insert() + pop()  # initializing list test_list = [1, 4, 5, 6, 7, 8, 9, 12]  # printing the original listprint ("The original list is : " + str(test_list))  # using insert() + pop()# shift last element to firsttest_list.insert(0, test_list.pop())  # printing resultprint ("The list after shift is : " + str(test_list))
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]

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

04 Jan, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python to write your first program with Selenium to Search Google Using Python Selenium.
If you have not installed Selenium and its components yet, install them from here – Selenium Python Introduction and Installation.
Google search has a URL where you can append your keywords and it will search the keyword for you. For example – “https://google.co.in/search?q=gfg”, this will search gfg on google.co.in.In the same manner we arbitrarily provide the keyword we want to search or take input from user. This is an example program to understand how Selenium works.
After you have installed Selenium, create a file called run.py as –Program –
# Python program to demonstrate# selenium  # import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # enter keyword to searchkeyword = "geeksforgeeks"  # get google.co.indriver.get("https://google.co.in / search?q ="+keyword)
Output-
Python Selenium-Exercises
Python-selenium
selenium
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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
PostgreSQL – DATE_PART Function

01 Feb, 2021
In PostgreSQL, the DATE_PART() function is used to query for subfields from a date or time value. 
Syntax: DATE_PART(field, source)
In the above syntax the field is an identifier that is used to set the field to extract the data from the source. The permitted field values mentioned below:
century
decade
year
month
day
hour
minute
second
microseconds
milliseconds
dow
doy
epoch
isodow
isoyear
timezone
timezone_hour
timezone_minute
The DATE_PART() function returns a double precision type value.
Example 1:
The below query extracts the data regarding the century from a timestamp:
SELECT date_part('century', TIMESTAMP '2020-01-01');
Output:
Example 2:
In this example we will extract the hour, minute, second from a time stamp type value, by passing the corresponding value hour, minute and second to the DATE_PART() function:
SELECT date_part('hour', TIMESTAMP '2020-03-18 10:20:30') h,
       date_part('minute', TIMESTAMP '2020-03-18 10:20:30') m,
       date_part('second', TIMESTAMP '2020-03-18 10:20:30') s;
Output:
Example 3:
Here we will query for the day of week and or day of the year from a timestamp, through the use of the following statement:
SELECT date_part('dow', TIMESTAMP '2020-03-18 10:20:30') dow,
       date_part('doy', TIMESTAMP '2020-03-18 10:20:30') doy;
Output:
PostgreSQL-Date-function
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - SELECT
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
PHP | parse_url() Function

08 Mar, 2019
The parse_url() function is an inbuilt functionin PHP which is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components.
Syntax:
parse_url( $url, $component = -1 )
Parameters: This function accepts two parameters as mentioned above and described below:
url: This parameter holds the URL to be parsed. The invalid characters are replaced by _ (underscore).
component: This parameter specifies any of the component ( PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT ) to retrieve a specific URL in the form of string.
Return Values:
It return an associative array if the component parameter is omitted.
It return a string if the component parameter is specified.
It return false, if the parameter is malformed URL.
Below examples illustrate the use of parse_url() function in PHP:
Example 1:
<?php  // Declare a variable and initialize it with URL$url = 'http://geeksforgeeks.org/php/#basics';  // Use parse_url() function to parse the URLvar_dump(parse_url($url));var_dump(parse_url($url, PHP_URL_SCHEME));  ?>
array(4) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(17) "geeksforgeeks.org"
  ["path"]=>
  string(5) "/php/"
  ["fragment"]=>
  string(6) "basics"
}
string(4) "http"

Example 2:
<?php  // Declare a variable and initialize it with URL$url = '//www.geeksforgeeks.org/path?php=PHP';  // Use parse_url() function to// parse the URLvar_dump(parse_url($url));  ?>
array(3) {
  ["host"]=>
  string(21) "www.geeksforgeeks.org"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(7) "php=PHP"
}

Reference: http://php.net/manual/en/function.parse-url.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Difference between TDM and FDM

28 May, 2019
Prerequisite – Frequency division and Time division multiplexingTime Division Multiplexing (TDM):TDM is the multiplexing technique. TDM works with digital signals likewise as analog signals. In TDM, synchronization pulse is important. TDM share the timescale for the various signals. It have two types:
1. Synchronous TDM
2. Asynchronous TDM 
Frequency Division Multiplexing (FDM):FDM is the multiplexing technique which is used in analog system. In FDM, Guard band is required and the spectral efficiency of FDM is low. In FDM, Bandwidth(B) is committed to the different sources.
Let’s see that the difference between TDM and FDM:
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
GSM in Wireless Communication
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Factorial of a number in PL/SQL

10 May, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements.In declare part, we declare variables and between begin and end part, we perform the operations.
Here, first, we take three variables num, fact, and temp and assign the value in num variable (i.e which number factorial we want).And then after we assign fact variable to 1.
Examples:
Input : 4
Output : 24

Input : 6
Output : 720

Below is the required implementation:
declare   -- declare variable num , fact-- and temp of datatype number num number := 6;              fact number := 1;             temp number;           begin   temp :=num;  -- here we check condition -- with the help of while loopwhile( temp>0 )             loopfact := fact*temp;temp := temp-1;  end loop;  dbms_output.put_line('factorial of '|| num || ' is ' || fact);   end;                            -- Program End
Output :
factorial of 6 is 720.

SQL-PL/SQL
DBMS
School Programming
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert Text to Speech in Python using win32com.client - GeeksforGeeks

22 Oct, 2017
There are several APIs available to convert text to speech in python. One of such APIs available in the python library commonly known as win32com library. It provides a bunch of methods to get excited about and one of them is the Dispatch method of the library. Dispatch method when passed with the argument of SAPI.SpVoice It interacts with the Microsoft Speech SDK to speak what you type in from the keyboard.Examples:
Input : Hello World
Output : 
Audio Playerhttps://media.geeksforgeeks.org/wp-content/uploads/hello-world.m4a00:0000:0000:00Use Up/Down Arrow keys to increase or decrease volume.

Input : 121
Output : Audio Playerhttps://media.geeksforgeeks.org/wp-content/uploads/121.m4a00:0000:0000:00Use Up/Down Arrow keys to increase or decrease volume.

InstallationTo install the win32com.client module , open terminal and write
pip install pypiwin32

This works on Windows platform. Now we are all set to write a sample program that converts text to speech.
# Python program to convert# text to speech  # import the required module from text to speech conversionimport win32com.client  # Calling the Disptach method of the module which # interact with Microsoft Speech SDK to speak# the given input from the keyboard  speaker = win32com.client.Dispatch("SAPI.SpVoice")  while 1:    print("Enter the word you want to speak it out by computer")    s = input()    speaker.Speak(s)  # To stop the program press# CTRL + Z
Input:
 Welcome to geeks for geeks
Output:
Audio Playerhttps://media.geeksforgeeks.org/wp-content/uploads/audio.m4a00:0000:0000:00Use Up/Down Arrow keys to increase or decrease volume.

This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
python-utility
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
Top 10 Programming Languages to Learn in 2022
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Redis - Sorted Sets

Redis Sorted Sets are similar to Redis Sets with the unique feature of values stored in a set. The difference is, every member of a Sorted Set is associated with a score, that is used in order to take the sorted set ordered, from the smallest to the greatest score.
In Redis sorted set, add, remove, and test for the existence of members in O(1) (constant time regardless of the number of elements contained inside the set). Maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per set).
redis 127.0.0.1:6379> ZADD tutorials 1 redis 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 2 mongodb 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 3 mysql 
(integer) 1 
redis 127.0.0.1:6379> ZADD tutorials 3 mysql 
(integer) 0 
redis 127.0.0.1:6379> ZADD tutorials 4 mysql 
(integer) 0 
redis 127.0.0.1:6379> ZRANGE tutorials 0 10 WITHSCORES  
1) "redis" 
2) "1" 
3) "mongodb" 
4) "2" 
5) "mysql" 
6) "4" 

In the above example, three values are inserted with its score in Redis sorted set named ‘tutorials’ by the command ZADD.
Following table lists some basic commands related to sorted sets.
Adds one or more members to a sorted set, or updates its score, if it already exists
Gets the number of members in a sorted set
Counts the members in a sorted set with scores within the given values
Increments the score of a member in a sorted set
Intersects multiple sorted sets and stores the resulting sorted set in a new key
Counts the number of members in a sorted set between a given lexicographical range
Returns a range of members in a sorted set, by index
Returns a range of members in a sorted set, by lexicographical range
Returns a range of members in a sorted set, by score
Determines the index of a member in a sorted set
Removes one or more members from a sorted set
Removes all members in a sorted set between the given lexicographical range
Removes all members in a sorted set within the given indexes
Removes all members in a sorted set within the given scores
Returns a range of members in a sorted set, by index, with scores ordered from high to low
Returns a range of members in a sorted set, by score, with scores ordered from high to low
Determines the index of a member in a sorted set, with scores ordered from high to low
Gets the score associated with the given member in a sorted set
Adds multiple sorted sets and stores the resulting sorted set in a new key
Incrementally iterates sorted sets elements and associated scores

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How do I detect if a table exist in MySQL?

To detect the existence of a table, use the concept of INFORMATION_SCHEMA.TABLES.
Following is the syntax −
select table_name from information_schema.tables
where table_schema=database()
and table_name=yourTableName;
To understand the above syntax, let us create a table −
mysql> create table DemoTable2032
   -> (
   -> ClientId int,
   -> ClientName varchar(20),
   -> ClientAge int,
   -> ClientCountryName varchar(20)
   -> );
Query OK, 0 rows affected (1.07 sec)
Here is the query to detect if a table exist in a database −
mysql> select table_name from information_schema.tables
   -> where table_schema=database()
   -> and table_name='DemoTable2032';
This will produce the following output −
+---------------+
| TABLE_NAME    |
+---------------+
| demotable2032 |
+---------------+
1 row in set (0.00 sec)
How can we write Callable as a lambda expression in Java?

A Callable interface defined in java.util.concurrent package. An object of Callable returns a computed result done by a thread in contrast to a Runnable interface that can only run the thread. The Callable object returns Future object that provides methods to monitor the progress of a task executed by a thread. An object of the Future used to check the status of a Callable interface and retrieves the result from Callable once the thread has done.
In the below example, we can write a Callable interface as a Lambda Expression.
import java.util.concurrent.*;

public class LambdaCallableTest {
   public static void main(String args[]) throws InterruptedException {
      ExecutorService executor = Executors.newSingleThreadExecutor();
      Callable c = () -> {   // Lambda Expression
         int n = 0;
         for(int i = 0; i < 100; i++) {
            n += i;
         }
         return n;
      };
      Future<Integer> future = executor.submit(c);
      try {
         Integer result = future.get(); //wait for a thread to complete
         System.out.println(result);
      } catch(ExecutionException e) {
         e.printStackTrace();
      }
      executor.shutdown();
   }
}
4950
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
123456789101112131415161718192021222324252627282930313233// Java program to demonstrate working of // interface.import java.io.*;// A simple interfaceinterface in1{    // public, static and final    final int a = 10;    // public and abstract     void display();}// A class that implements interface.class testClass implements in1{    // Implementing the capabilities of    // interface.    public void display()    {        System.out.println("Geek");    }    // Driver Code    public static void main (String[] args)    {        testClass t = new testClass();        t.display();        System.out.println(a);    }}ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
PyQt5 - QBoxLayout Class

QBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally). Following table shows the important methods of QBoxLayout class −
addWidget()
Add a widget to the BoxLayout
addStretch()
Creates empty stretchable box
addLayout()
Add another nested layout
Here two buttons are added in the vertical box layout. A stretchable empty space is added between them by addStretch() method. Therefore, if the top level window is resized, the position of buttons automatically gets relocated.
import sys
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
	
   b1 = QPushButton("Button1")
   b2 = QPushButton("Button2")
   
   vbox = QVBoxLayout()
   vbox.addWidget(b1)
   vbox.addStretch()
   vbox.addWidget(b2)
   win.setLayout(vbox)

   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()
The above code produces the following output −
This example uses horizontal box layout. addStretch() method inserts a stretchable empty space between the two button objects. Hence, as the window is resized, the size and position of the button changes dynamically.
import sys 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
   
   b1 = QPushButton("Button1")
   b2 = QPushButton("Button2")

   hbox = QHBoxLayout()
   hbox.addWidget(b1)
   hbox.addStretch()
   hbox.addWidget(b2)
   win.setLayout(hbox)
   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   window()
The above code produces the following output −
This example shows how the layouts can be nested. Here, two buttons are added to vertical box layout. Then, a horizontal box layout object with two buttons and a stretchable empty space is added to it. Finally, the vertical box layout object is applied to the top level window by the setLayout() method.
import sys 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()

   b1 = QPushButton("Button1")
   b2 = QPushButton("Button2")
	
   vbox = QVBoxLayout()
   vbox.addWidget(b1)
   vbox.addStretch()
   vbox.addWidget(b2)
   hbox = QHBoxLayout()
	
   b3 = QPushButton("Button3")
   b4 = QPushButton("Button4")
   hbox.addWidget(b3)
   hbox.addStretch()
   hbox.addWidget(b4)

   vbox.addStretch()
   vbox.addLayout(hbox)
   win.setLayout(vbox)

   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()
The above code produces the following output −
Tkinter – OptionMenu Widget

15 Mar, 2021
Prerequisite: Python GUI -tkinter
One of the most popular Python modules to build GUI(Graphical User Interface) based applications is the Tkinter module. It comes with a lot of functionalities like buttons, text-boxes, labels to be used in the GUI application, these are called widgets. In this article, we are going to learn what is the OptionMenu Widget and when it is used.
OptionMenu is basically a dropdown or popup menu that displays a group of objects on a click or keyboard event and lets the user select one option at a time.
Approach:
Import the Tkinter module.Create the default windowCreate a list of options to be shown at the dropdown/popup.Create a variable using.StringVar() method to keep track of the option selected in OptionMenu. Set a default value to it.Create the OptionMenu widget and pass the options_list and variable created to it.
Import the Tkinter module.
Create the default window
Create a list of options to be shown at the dropdown/popup.
Create a variable using.StringVar() method to keep track of the option selected in OptionMenu. Set a default value to it.
Create the OptionMenu widget and pass the options_list and variable created to it.
Below is the implementation:
Python3
# Import the tkinter moduleimport tkinter  # Create the default windowroot = tkinter.Tk()root.title("Welcome to GeeksForGeeks")root.geometry('700x500')  # Create the list of optionsoptions_list = ["Option 1", "Option 2", "Option 3", "Option 4"]  # Variable to keep track of the option# selected in OptionMenuvalue_inside = tkinter.StringVar(root)  # Set the default value of the variablevalue_inside.set("Select an Option")  # Create the optionmenu widget and passing # the options_list and value_inside to it.question_menu = tkinter.OptionMenu(root, value_inside, *options_list)question_menu.pack()  # Function to print the submitted option-- testing purpose    def print_answers():    print("Selected Option: {}".format(value_inside.get()))    return None    # Submit button# Whenever we click the submit button, our submitted# option is printed ---Testing purposesubmit_button = tkinter.Button(root, text='Submit', command=print_answers)submit_button.pack()  root.mainloop()
Output:
Explanation: 
In the output GUI window, an OptionMenu widget is created it contains the default value of “Select an Option” as given. On click, it shows a dropdown containing the given options list.
Picked
Python-tkinter
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 OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | datetime.timedelta() function
Python – Dict of tuples to JSON

28 Nov, 2021
In this article, we will discuss how to convert a dictionary of tuples to JSON.
This will convert dictionary of tuples to json
Syntax: json.dumps(dictionary, indent)
Parameters:  
dictionary is the input dictionary.
indent specify the number of units of indentation
Example: Python dict of tuples to json conversion
Python3
# import json moduleimport json  # dictionary of employee datadata = {    "id": ("1", "2", "3"),    "name": ("bhanu", "sivanagulu"),    "department": ("HR", "IT")}  # convert into jsonfinal = json.dumps(data, indent=2)  # displayprint(final)
Output:
{
  "id": [
    "1",
    "2",
    "3"
  ],
  "name": [
    "bhanu",
    "sivanagulu"
  ],
  "department": [
    "HR",
    "IT"
  ]
}
This will write converted json data into file, which will be downloaded and saved on your computer.
Syntax: json.dump(dictionary,pointer)
Parameters:  
dictionary is the input dictionary.
pointer is the file pointer that is  opened in write or append mode.
Syntax:
with open("mydata.json", "w") as final:
    json.dump(data, final)
where, mydata is the new JSON file
Finally , we have to download the created JSON file
Syntax:
files.download('mydata.json')
Example: Python dict of tuples to json conversion
Python3
# import json modulefrom google.colab import filesimport json  # dictionary of employee datadata = {    "id": ("1", "2", "3"),    "name": ("bhanu", "sivanagulu"),    "department": ("HR", "IT")}  # convert into json# file name is mydatawith open("mydata.json", "w") as final:    json.dump(data, final)  # download the json filefiles.download('mydata.json')
Output:
Picked
Python-json
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
Python OOPs Concepts
Introduction To PYTHON
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
Python | datetime.timedelta() function
What is evaluation order of function parameters in C?

28 May, 2017
It is compiler dependent in C. It is never safe to depend on the order of evaluation of side effects. For example, a function call like below may very well behave differently from one compiler to another:
void func (int, int);    int i = 2;func (i++, i++);
There is no guarantee (in either the C or the C++ standard language definitions) that the increments will be evaluated in any particular order. Either increment might happen first. func might get the arguments `2, 3′, or it might get `3, 2′, or even `2, 2′.
Source: http://gcc.gnu.org/onlinedocs/gcc/Non_002dbugs.html
C-Functions
C Language
GFacts
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Return values of printf() and scanf() in C/C++
What are the Operators that Can be and Cannot be Overloaded in C++?
How are variables scoped in C - Static or Dynamic?
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Difference between YOLO and SSD
p5.Image save() Method

15 Sep, 2020
The save() method of p5.Image in p5.js is used to save the image to a file by forcing the browser to download it. The file can be saved in two formats, ‘png’ and ‘jpg’. It can also be saved with a ‘gif’ extension if an animated GIF is used with the p5.Image.
Note: It is not recommended calling this function inside the draw() loop, as it will prompt a new save dialog every draw call.
Syntax:
save( filename, extension )



Parameters: This function accepts two parameters as mentioned above and described below. 
filename: It is a String that specifies the filename of the saved file.
extension: It is a String that specifies the extension of the saved file. It can be either of the value ‘png’ or ‘jpg’.
The examples below illustrate the save() method in p5.js:
Example 1:
javascript
function preload() {    img = loadImage("sample-image.png");} function setup() {    createCanvas(500, 300);    textSize(20);     // Apply filter to image    img.filter(GRAY);     text('Current Image', 20, 20);    image(img, 20, 40, 200, 100);} function keyTyped() {   // Pressing the "q" key to  // save the image  if (key === 'q') {    img.save('saved-image', 'png');  }}
Output:
Example 2:
javascript
function preload() {    img = loadImage("sample-gif.gif");} function setup() {    createCanvas(500, 300);    textSize(20);     text('Current GIF', 20, 20);    image(img, 20, 40, 200, 100);     btnSave = createButton("Save GIF");    btnSave.position(30, 160);    btnSave.mousePressed(saveImg);} function saveImg() {     // Save the GIF    img.save("new-gif");}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5.Image/save
JavaScript-p5.js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Roadmap to Learn JavaScript For Beginners
How To Make Scatter Plot with Regression Line using Seaborn in Python?

02 Dec, 2020
In this article, we will learn how to male scatter plots with regression lines using Seaborn in Python. Let’s discuss some concepts :
Seaborn : Seaborn is a tremendous visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the highest of matplotlib library and also closely integrated to the info structures from pandas.
Scatter Plot : Scatter plots are wont to observe the relationship between variables and uses dots to represent the connection between them. The scatter() method within the matplotlib library is employed to draw a scatter plot. Scatter plots are widely wont to represent relationships among variables and the way change in one affects the opposite.
Regression Plot : Two main functions in seaborn are wont to visualize a linear relationship as determined through regression. These functions, regplot() and lmplot() are closely related and share much of their core functionality.
Adding a regression curve to a scatterplot between two numerical variables is a good way to ascertain the linear trend. And we also will see an example of customizing the scatter plot with a regression curve.
Import Library (Seaborn)
Import or load or create data.
Plot the graph with the help of regplot() or lmplot() method.
Example 1: Using regplot() method
This method is used to plot data and a linear regression model fit. There are a number of mutually exclusive options for estimating the regression model.
Python3
# importing librariesimport seaborn as sb  # load datadf = sb.load_dataset('iris')  # use regplotsb.regplot(x = "sepal_length",            y = "petal_length",             ci = None,            data = df)
Output :
Example 2: Using lmplot() method
The lmplot is another most basic plot. It shows a line representing a linear regression model along with data points on the 2D-space and x and y can be set as the horizontal and vertical labels respectively.
Python3
# importing librariesimport seaborn as sb  # load datadf = sb.load_dataset('iris')  # use lmplotsb.lmplot(x = "sepal_length",            y = "petal_length",             ci = None,            data = df)
Output : 
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove the legend border in Matplotlib

29 May, 2021
In this article, we will learn how to Remove the legend border in Matplotlib. Let’s discuss some concepts :
A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes.
Approach:
Import Library (Matplotlib)Import / create data.Plot a chart.Add legend.Remove legend border.
Import Library (Matplotlib)
Import / create data.
Plot a chart.
Add legend.
Remove legend border.
Example: Here is an example with legends.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 10, 1000)y1 = np.sin(x)y2 = np.cos(x) # plot graphplt.plot(x, y1)plt.plot(x, y2) # add legendplt.legend(['Sine wave', 'Cos wave'])plt.show()
Output:
Method 1: (Using frameon = False)
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 10, 1000)y1 = np.sin(x)y2 = np.cos(x) # plot graphplt.plot(x, y1)plt.plot(x, y2) # add legend and remove frameplt.legend(['Sine wave', 'Cos wave'], frameon=False)plt.show()
Output :
Method 2: (Using legend.get_frame().set_alpha(0))
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 10, 1000)y1 = np.sin(x)y2 = np.cos(x) # plot graphplt.plot(x, y1)plt.plot(x, y2) # add legendleg = plt.legend(['Sine wave', 'Cos wave']) # set opacity equal to zero i.e; transparentleg.get_frame().set_alpha(0)plt.show()
Output :
sweetyty
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Read JSON file using Python
Python map() function
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Deque in Python
Taking input in Python
Arduino - delay () function

The way the delay() function works is pretty simple. It accepts a single integer (or number) argument. This number represents the time (measured in milliseconds). The program should wait until moving on to the next line of code when it encounters this function. However, the problem is, the delay() function is not a good way to make your program wait, because it is known as a “blocking” function.
delay (ms) ;

where, ms is the time in milliseconds to pause (unsigned long).
/* Flashing LED
   * ------------
   * Turns on and off a light emitting diode(LED) connected to a digital
   * pin, in intervals of 2 seconds. *
*/

int ledPin = 13; // LED connected to digital pin 13

void setup() {
   pinMode(ledPin, OUTPUT); // sets the digital pin as output
}

void loop() {
   digitalWrite(ledPin, HIGH); // sets the LED on
   delay(1000); // waits for a second
   digitalWrite(ledPin, LOW); // sets the LED off
   delay(1000); // waits for a second
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
C library function - strchr()

The C library function char *strchr(const char *str, int c) searches for the first occurrence of the character c (an unsigned char) in the string pointed to by the argument str.
Following is the declaration for strchr() function.
char *strchr(const char *str, int c)
str − This is the C string to be scanned.
str − This is the C string to be scanned.
c − This is the character to be searched in str.
c − This is the character to be searched in str.
This returns a pointer to the first occurrence of the character c in the string str, or NULL if the character is not found.
The following example shows the usage of strchr() function.
#include <stdio.h>
#include <string.h>

int main () {
   const char str[] = "http://www.tutorialspoint.com";
   const char ch = '.';
   char *ret;

   ret = strchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
String after |.| is - |.tutorialspoint.com|


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Docker - Managing Ports

In Docker, the containers themselves can have applications running on ports. When you run a container, if you want to access the application in the container via a port number, you need to map the port number of the container to the port number of the Docker host. Let’s look at an example of how this can be achieved.
In our example, we are going to download the Jenkins container from Docker Hub. We are then going to map the Jenkins port number to the port number on the Docker host.
Step 1 − First, you need to do a simple sign-up on Docker Hub.
Step 2 − Once you have signed up, you will be logged into Docker Hub.
Step 3 − Next, let’s browse and find the Jenkins image.
Step 4 − If you scroll down on the same page, you can see the Docker pull command. This will be used to download the Jenkins Image onto the local Ubuntu server.
Step 5 − Now go to the Ubuntu server and run the command −
sudo docker pull jenkins 

Step 6 − To understand what ports are exposed by the container, you should use the Docker inspect command to inspect the image.
Let’s now learn more about this inspect command.
This method allows one to return low-level information on the container or image.
docker inspect Container/Image 

Container/Image − The container or image to inspect
Container/Image − The container or image to inspect
The low-level information of the image or container in JSON format.
sudo docker inspect jenkins 
The output of the inspect command gives a JSON output. If we observe the output, we can see that there is a section of "ExposedPorts" and see that there are two ports mentioned. One is the data port of 8080 and the other is the control port of 50000.
To run Jenkins and map the ports, you need to change the Docker run command and add the ‘p’ option which specifies the port mapping. So, you need to run the following command −
sudo docker run -p 8080:8080 -p 50000:50000 jenkins 

The left-hand side of the port number mapping is the Docker host port to map to and the right-hand side is the Docker container port number.
When you open the browser and navigate to the Docker host on port 8080, you will see Jenkins up and running.

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page