code-rag-bench/online-tutorials huggingface dataset:
Connect your android phone camera to OpenCV – Python

17 Feb, 2021
Prerequisites: OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. 
Many a time, while doing Computer Vision or Image Processing using our PC’s webcam is not a very option. Maybe we want to increase the camera quality of our webcam, or we want to create some image processing applications which will use an android camera as the medium. 
This article uses Windows to do this. But the basics of the code will be same on other Operating systems too.
Download and install IP Webcam application on your mobile phone.
Then make sure your PC and Phone both are connected to the same network. Open your IP Webcam application on your both, click “Start Server” (usually found at the bottom). This will open a camera on your Phone.
A URL is being displayed on the Phone screen, type the same URL on your PC browser, and under “Video renderer” Section, click on “Javascript”.
You can see video captured on your phone, which starts showing up on your browser. Now, what we will be going to do is, taking image data from the URL using the request module and convert this to an image frame using NumPy, and finally, start using our Android camera as a webcam in Python.
In the code:Import moduleAdd URL displayed in your phoneContinuous fetch data from URLKeep displaying this data collectedClose window
Import module
Add URL displayed in your phone
Continuous fetch data from URL
Keep displaying this data collected
Close window
Program:
Python3
# Import essential librariesimport requestsimport cv2import numpy as npimport imutils  # Replace the below URL with your own. Make sure to add "/shot.jpg" at last.url = "http://192.168.0.103:8080/shot.jpg"  # While loop to continuously fetching data from the Urlwhile True:    img_resp = requests.get(url)    img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)    img = cv2.imdecode(img_arr, -1)    img = imutils.resize(img, width=1000, height=1800)    cv2.imshow("Android_cam", img)      # Press Esc key to exit    if cv2.waitKey(1) == 27:        break  cv2.destroyAllWindows()
Output:
Python-OpenCV
Python-projects
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Lambda Function to Check if value is in a List

04 Jan, 2022
Given a list, the task is to write a Python program to check if the value exists in the list or not using the lambda function.
Example:
Input  :  L = [1, 2, 3, 4, 5]
          element = 4
Output :  Element is Present in the list

Input  :  L = [1, 2, 3, 4, 5]
          element = 8
Output :  Element is NOT Present in the list
We can achieve the above functionality using the following two methods.
Define a list with integers. Define a lambda function such that it takes array and value as arguments and return the count of value in list.
lambda v:l.count(v)
If the count is zero then print the Element is not present else print element is NOT present.
Python3
arr = [1, 2, 3, 4]v = 3  def x(arr, v): return arr.count(v)    if(x(arr, v)):    print("Element is Present in the list")else:    print("Element is Not Present in the list")
Output:
Element is Present in the list
Explanation:  The arr and v are passed to the lambda function and it evaluates the count of v in the arr and here v = 3 and it is present 1 time in the array and the if condition is satisfied and prints the element Is present in the list.
Define a list with integers. Define a lambda function such that it takes array and value as arguments and check if value is present in array using in keyword
lambda v: True if v in l else False
If the lambda return True then print the Element is present else print element is NOT present.
Python3
arr=[1,2,3,4]v=8x=lambda arr,v: True if v in arr else False  if(x(arr,v)):  print("Element is Present in the list")else:  print("Element is Not Present in the list")
Output:
Element is Not Present in the list
Explanation:  The arr and v are passed to the lambda function and it checks if the value is present in an array using IN keyword and here v = 8 and it is NOT Present in the array and returns false so prints the element Is NOT present in the list.
Picked
python-lambda
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 | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to make image maps in HTML5 ?

26 Sep, 2021
The HTML <map> tag is used to define image maps in HTML. The areas inside the image which are clickable are defined by using the <area> tag.
Syntax:
<map name="map-name">
Attribute value:
name: It is used to associate the map with the image in which it is used.
Note: The name attribute in the map must have same value as image’s usemap attribute.
 
Example: In this example, the highlighted area is the mapped area, clicking on it will lead to the website.
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible"        content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    </head><body>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/array-2.png"        alt="gfgimage" usemap="#mapID">       <map name="mapID">        <area shape="rect"             coords="34, 44, 270, 350"href="https://www.geeksforgeeks.org/data-structures/?ref=shm">    </map></body></html>
Output:
HTML-Questions
HTML-Tags
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
How to return none from Python function?

Functions without a return statement known as void functions return None from the function. To return a value other than None, you need to use a return statement in the functions; and such functions are called fruitful functions.
Values like None, True and False are not strings: they are special values and keywords in python and are part of the syntax.
If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None.
Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.
One sample code is given below that returns None.
def lyrics(): pass
a = lyrics()
print a
None
Trying to round a calculation to two decimal places in a new column with MySQL?

To round, use MySQL ROUND() function. Let us first create a table −
mysql> create table DemoTable1865
     (
     Value1 int,
     Value2 int
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1865 values(40,60);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1865 values(100,400);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1865 values(545,896);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1865;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     40 |     60 |
|    100 |    400 |
|    545 |    896 |
+--------+--------+
3 rows in set (0.00 sec)
Here is the query to round a calculation to 2 decimal places in a new column −
mysql> select round(Value1/Value2,2) as Result from DemoTable1865;
This will produce the following output −
+--------+
| Result |
+--------+
|   0.67 |
|   0.25 |
|   0.61 |
+--------+
3 rows in set (0.00 sec)
Checking schema creation in SAP HANA database

To check this detail, you should have access on “SYS” schema. Run the following SQL query and it will fetch the following columns −
SELECT * FROM "SYS"."SCHEMAS";
Schema_Name
Schema_Owner
HAS_PRIVILEGES
Create_Time
C library function - fflush()

The C library function int fflush(FILE *stream) flushes the output buffer of a stream.
Following is the declaration for fflush() function.
int fflush(FILE *stream)
stream − This is the pointer to a FILE object that specifies a buffered stream.
stream − This is the pointer to a FILE object that specifies a buffered stream.
This function returns a zero value on success. If an error occurs, EOF is returned and the error indicator is set (i.e. feof).
The following example shows the usage of fflush() function.
#include <stdio.h>
#include <string.h>

int main () {

   char buff[1024];
   
   memset( buff, '\0', sizeof( buff ));
   
   fprintf(stdout, "Going to set full buffering on\n");
   setvbuf(stdout, buff, _IOFBF, 1024);

   fprintf(stdout, "This is tutorialspoint.com\n");
   fprintf(stdout, "This output will go into buff\n");
   fflush( stdout );

   fprintf(stdout, "and this will appear when programm\n");
   fprintf(stdout, "will come after sleeping 5 seconds\n");
   
   sleep(5);
   
   return(0);
}
Let us compile and run the above program that will produce the following result. Here program keeps buffering into the output into buff until it faces first call to fflush(), after which it again starts buffering the output and finally sleeps for 5 seconds. It sends remaining output to the STDOUT before program comes out.
Going to set full buffering on
This is tutorialspoint.com
This output will go into buff
and this will appear when programm
will come after sleeping 5 seconds


    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
How to append a list as a row to a Pandas DataFrame in Python?

05 Oct, 2021
Prerequisite: Pandas DataFrame
In this article, We are going to see how to append a list as a row to a pandas dataframe in Python. It can be done in three ways:
Using loc[]
Using iloc[]
Using append()
Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
Let’s append the list with step-wise:
Step 1: Create a simple dataframe using the list.
Python3
import pandas as pd # ListPerson = [ ['Satyam', 21, 'Patna' , 'India' ],            ['Anurag', 23, 'Delhi' , 'India' ],            ['Shubham', 27, 'Coimbatore' , 'India' ]] #Create a DataFrame objectdf = pd.DataFrame(Person,                  columns = ['Name' , 'Age', 'City' , 'Country']) # displaydisplay(df)
 Output:
Step 2: Using loc to append the new list to a data frame. 
Python3
# New list for append into dflist = ["Saurabh", 23, "Delhi", "india"] # using loc methodsdf.loc[len(df)] = list # displaydisplay(df)
 Output:
Pandas DataFrame.iloc method access integer-location based indexing for selection by position. 
Example:
Python3
# import moduleimport pandas as pd # ListPerson = [ ['Satyam', 21, 'Patna' , 'India' ],            ['Anurag', 23, 'Delhi' , 'India' ],            ['Shubham', 27, 'Coimbatore' , 'India' ],            ["Saurabh", 23, "Delhi", "india"]] #Create a DataFrame objectdf = pd.DataFrame(Person,                  columns = ['Name' , 'Age', 'City' , 'Country']) # new list to append into dflist = ['Ujjawal', 22, 'Fathua', 'India'] # using ilocdf.iloc[2] = list # displaydisplay(df)
Output:
Note – It is used for location-based indexing so it works for only the existing index and replaces the row element.
Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object.
Example:
Python3
# import moduleimport pandas as pd # ListPerson = [ ['Satyam', 21, 'Patna' , 'India' ],            ['Anurag', 23, 'Delhi' , 'India' ],            ['Shubham', 27, 'Coimbatore' , 'India' ]] #Create a DataFrame objectdf = pd.DataFrame(Person,                  columns = ['Name' , 'Age', 'City' , 'Country']) # new list to append into dflist = [["Manjeet", 25, "Delhi", "india"]] # using appenddf = df.append(pd.DataFrame( list,               columns=[ 'Name', 'Age', 'City', 'Country']),               ignore_index = True) # display dfdisplay(df)
Output:
prachisoda1234
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Introduction To PYTHON
Create a Pandas DataFrame from Lists
Python OOPs Concepts
Python program maximum of three

01 Aug, 2020
Given three number a b and c, the task is that we have to find the greatest element in among in given numberExamples:
Input : a = 2, b = 4, c = 3
Output : 4 

Input : a = 4, b = 2, c = 6 
Output : 6

Method 1 (Simple)
# Python program to find the largest# number among the three numbers  def maximum(a, b, c):      if (a >= b) and (a >= c):        largest = a      elif (b >= a) and (b >= c):        largest = b    else:        largest = c              return largest    # Driven code a = 10b = 14c = 12print(maximum(a, b, c))
Output:
14

 
Method 2 (Using List). Initialize three number by n1, n2 and n3. Add three numbers into list lst = [n1, n2, n3].. Using max() function to find the greatest number max(lst).. And finally we will print maximum number
# Python program to find the largest number # among the  three numbers using library function   def maximum(a, b, c):    list = [a, b, c]    return max(list)  # Driven code a = 10b = 14c = 12print(maximum(a, b, c))
Output:
14

Method 3 (Using max function)
# Python program to find the largest number # among the  three numbers using library function   # Driven code a = 10b = 14c = 12print(max(a, b, c))
Output:
14

ljfects
Python
School Programming
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 Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Python | Split nested list into two lists

10 Apr, 2019
Given a nested 2D list, the task is to split the nested list into two lists such that first list contains first elements of each sublists and second list contains second element of each sublists.
Method #1: Using map, zip()
# Python code to demonstrate# splitting nested list# into 2 lists  # initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]  # printing initial listsprint ("initial list", str(ini_list))  # code to split it into 2 listsres1, res2 = map(list, zip(*ini_list))  # printing resultprint("final lists", res1, "\n", res2)
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [1, 4, 45, 223] 
 [2, 3, 65, 2]

 Method #2: Using list comprehension
# python code to demonstrate# splitting nested list# into 2 lists  # initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]  # printing initial listsprint ("initial list", str(ini_list))  # code to split it into 2 listsres1 = [i[1] for i in ini_list]res2 = [i[0] for i in ini_list]  # printing resultprint("final lists", str(res1), "\n", str(res2))
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [2, 3, 65, 2] 
 [1, 4, 45, 223]

 Method #3: Using operator.itemgetter()
# python code to demonstrate# splitting nested list# into 2 lists  from operator import itemgetter  # initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]  # printing initial listsprint ("initial list", str(ini_list))  # code to split it into 2 listsres1 = list(map(itemgetter(0), ini_list))res2 = list(map(itemgetter(1), ini_list))  # printing resultprint("final lists", str(res1), "\n", str(res2))
initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [1, 4, 45, 223] 
 [2, 3, 65, 2]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Flask â Redirect & Errors

Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code.
Prototype of redirect() function is as below −
Flask.redirect(location, statuscode, response)

In the above function −
location parameter is the URL where response should be redirected.
location parameter is the URL where response should be redirected.
statuscode sent to browser’s header, defaults to 302.
statuscode sent to browser’s header, defaults to 302.
response parameter is used to instantiate response.
response parameter is used to instantiate response.
The following status codes are standardized −
HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
The default status code is 302, which is for ‘found’.
In the following example, the redirect() function is used to display the login page again when a login attempt fails.
from flask import Flask, redirect, url_for, render_template, request
# Initialize the Flask application
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET']) 
def login(): 
   if request.method == 'POST' and request.form['username'] == 'admin' :
      return redirect(url_for('success'))
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'
	
if __name__ == '__main__':
   app.run(debug = True)
Flask class has abort() function with an error code.
Flask.abort(code)

The Code parameter takes one of following values −
400 − for Bad Request
400 − for Bad Request
401 − for Unauthenticated
401 − for Unauthenticated
403 − for Forbidden
403 − for Forbidden
404 − for Not Found
404 − for Not Found
406 − for Not Acceptable
406 − for Not Acceptable
415 − for Unsupported Media Type
415 − for Unsupported Media Type
429 − Too Many Requests
429 − Too Many Requests
Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthourized’ page is to be displayed, replace it with call to abort(401).
from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin' :
         return redirect(url_for('success'))
      else:
         abort(401)
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.run(debug = True)
Filter Pandas DataFrame by Time

24 Feb, 2021
In this article let’s see how to filter pandas data frame by date. So we can filter python pandas data frame by date using the logical operator and loc() method. In the below examples we have a data frame that contains two columns the first column is Name and another one is DOB.
Example 1: filter data that’s DOB is greater than 1999-02-5.
Python
import pandas as pd  # create data frameData = {'Name': ['Mukul', 'Rohan', 'Mayank',                          'Shubham', 'Aakash'],          'DOB': ['1997-04-24', '1998-05-25', '1999-04-11',                '2000-11-15', '1998-06-28']}  df = pd.DataFrame(Data)  # print original data frameprint(df)  # filter data frameNew_df = df.loc[df["DOB"] >= "1999-02-5"]  # print filtered data frameprint(New_df)
Output:
Example 2: filter data between two date. 
Python
import pandas as pd  # create data frameData = {'Name': ['Mukul', 'Rohan', 'Mayank',                          'Shubham', 'Aakash'],          'DOB': ['1997-04-24', '1998-05-25', '1999-04-11',                '2000-11-15', '1998-06-28']}df = pd.DataFrame(Data)  # print original data frameprint(df)  Date1 = df["DOB"] >= "1998-04-24"Date2 = df["DOB"] <= "1999-1-31"  # filter data between 1998-04-24 to 1999-01-31New_df = df.loc[Date1 & Date2]  # print the filtered data frameprint(New_df)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.maximum() in Python

28 Nov, 2018
numpy.maximum() function is used to find the element-wise maximum of array elements.
It compares two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned.
Syntax : numpy.maximum(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘maximum’)
Parameters :arr1 : [array_like] Input array.arr2 : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : [ndarray or scalar] Result.The maximum of arr1 and arr2, element-wise. This is a scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# maximum() function  import numpy as geekin_num1 = 10in_num2 = 21  print ("Input  number1 : ", in_num1)print ("Input  number2 : ", in_num2)     out_num = geek.maximum(in_num1, in_num2) print ("maximum of 10 and 21 : ", out_num) 
Output :
Input  number1 :  10
Input  number2 :  21
maximum of 10 and 21 :  21

 Code #2 :
# Python program explaining# maximum() function  import numpy as geek  in_arr1 = [2, 8, 125]in_arr2 = [3, 3, 15]   print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2)    out_arr = geek.maximum(in_arr1, in_arr2) print ("Output array after selecting maximum: ", out_arr) 
Output :
Input array1 :  [2, 8, 125]
Input array2 :  [3, 3, 15]
Output array after selecting maximum:  [  3   8 125]

 Code #3 :
# Python program explaining# maximum() function  import numpy as geek  in_arr1 = [geek.nan, 0, geek.nan]in_arr2 = [geek.nan, geek.nan, 0]   print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2)    out_arr = geek.maximum(in_arr1, in_arr2) print ("Output array after selecting maximum: ", out_arr) 
Output :
Input array1 :  [nan, 0, nan]
Input array2 :  [nan, nan, 0]
Output array after selecting maximum:  [ nan  nan  nan]

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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
MS SQL Server - Select Database

Select your database based on your action before going ahead with any of the following methods.
To run a query to select backup history on database called ‘msdb’, select the msdb database as shown in the following snapshot.
Use <your database name>

To run your query to select backup history on database called ‘msdb’, select the msdb database by executing the following query.
Exec use msdb

The query will open msdb database. You can execute the following query to select backup history.
Select * from backupset


    32 Lectures 
     2.5 hours 

 Pavan Lalwani

    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    102 Lectures 
     10 hours 

 Pavan Lalwani

    52 Lectures 
     4 hours 

 Pavan Lalwani

    239 Lectures 
     33 hours 

 Gowthami Swarna

    53 Lectures 
     5 hours 

 Akshay Magre
 Print
 Add Notes
 Bookmark this page
C++ nested switch statements

It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
C++ specifies that at least 256 levels of nesting be allowed for switch statements.
The syntax for a nested switch  statement is as follows −
switch(ch1) {
   case 'A': 
      cout << "This A is part of outer switch";
      switch(ch2) {
         case 'A':
            cout << "This A is part of inner switch";
            break;
         case 'B': // ...
      }
      break;
   case 'B': // ...
}

#include <iostream>
using namespace std;
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   switch(a) {
      case 100: 
         cout << "This is part of outer switch" << endl;
         switch(b) {
            case 200:
               cout << "This is part of inner switch" << endl;
         }
   }
   cout << "Exact value of a is : " << a << endl;
   cout << "Exact value of b is : " << b << endl;
 
   return 0;
}
This would produce the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Python | Pandas Series.rename() - GeeksforGeeks

14 Oct, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.rename() function is used to alter Series index labels or name for the given Series object.
Syntax: Series.rename(index=None, **kwargs)
Parameter :index : dict-like or functions are transformations to apply to the indexcopy : Also copy underlying datainplace : Whether to return a new Series. If True then value of copy is ignored.level : In case of a MultiIndex, only rename labels in the specified level.
Returns : Series, DataFrame, or None
Example #1: Use Series.rename() function to rename the name of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.rename() function to rename the name of the given series object.
# rename the seriesresult = sr.rename('Beverages')  # Print the resultprint(result)
Output :
As we can see in the output, the Series.rename() function has successfully renamed the given series object.
Example #2: Use Series.rename() function to rename the MultiIndex axis of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])  # Create the MultiIndexindex_ = pd.MultiIndex.from_product([['Names'], ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']],                                                                      names =['Level 1', 'Level 2'])  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.rename() function to rename the 0th level of the given series object.
# rename the 0th levelresult = sr.rename(level = 0, index = 'Row_axis')  # Print the resultprint(result)
Output :
As we can see in the output, the Series.rename() function has successfully renamed the 0th level of the given series object.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
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
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Count of elements matching particular condition in Python

In this article we will see how to get some selected elements out of a Python list. So we need to design some condition and only the elements satisfying that condition should be picked and their count to be printed.
In this approach we use in condition to pick the elements and use some to get their count. 1 is used if the element is present else 0 is used for the result of in condition.
 Live Demo
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\n", Alist)
cnt = sum(1 for i in Alist if i in('Mon','Wed'))
print("Number of times the condition is satisfied in the list:\n",cnt)
Running the above code gives us the following result −
Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3
Here also used in condition but also use lambda and map functions. Final we apply the sum function to get the count.
 Live Demo
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\n", Alist)
cnt=sum(map(lambda i: i in('Mon','Wed'), Alist))
print("Number of times the condition is satisfied in the list:\n",cnt)
Running the above code gives us the following result −
Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3
The reduce function applies a particular function to all the elements in a list supplied to it as an argument. We use it along with a in condition finally producing the count of the elements matching the condition.
 Live Demo
from functools import reduce
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\n", Alist)
cnt = reduce(lambda count, i: count + (i in('Mon','Wed')), Alist, 0)
print("Number of times the condition is satisfied in the list:\n",cnt)
Running the above code gives us the following result −
Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3
How to convert NaN values to NA in an R data frame?

To convert NaN values to NA, we would need to detect the NaN values in the data frame and the set them to NA. For example, if we have a data frame called df that contains a column x which has some NaN values then we can convert those NaN to NA by using the command dfx[is.nan(dfx)]<-NA
Consider the below data frame −
Live Demo
> x1<-sample(c(1,NaN),20,replace=TRUE)
> x2<-rnorm(20)
> df1<-data.frame(x1,x2)
> df1
x1 x2
1 NaN -0.44923302
2 NaN -0.12670027
3 1 0.59120380
4 1 -0.18782341
5 NaN -0.28730385
6 1 0.57412261
7 NaN -0.33620181
8 1 1.37168545
9 NaN -2.24121448
10 NaN 1.05990104
11 1 1.95544957
12 NaN -2.19544854
13 1 -0.94131203
14 1 -0.37307028
15 NaN 1.21659101
16 1 -0.03788952
17 1 -0.16122552
18 1 0.90254474
19 1 -0.73196835
20 NaN -0.28462669
Converting NaN in x1 to NA −
> df1$x1[is.nan(df1$x1)]<-NA
> df1
x1 x2
1 NA -0.44923302
2 NA -0.12670027
3 1 0.59120380
4 1 -0.18782341
5 NA -0.28730385
6 1 0.57412261
7 NA -0.33620181
8 1 1.37168545
9 NA -2.24121448
10 NA 1.05990104
11 1 1.95544957
12 NA -2.19544854
13 1 -0.94131203
14 1 -0.37307028
15 NA 1.21659101
16 1 -0.03788952
17 1 -0.16122552
18 1 0.90254474
19 1 -0.73196835
20 NA -0.28462669
Live Demo
> y1<-sample(c(5,NaN),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2
y1 y2
1 NaN 7
2 NaN 5
3 NaN 3
4 5 4
5 5 4
6 5 4
7 5 4
8 NaN 4
9 5 5
10 NaN 5
11 5 5
12 5 2
13 5 9
14 5 3
15 NaN 6
16 NaN 8
17 5 5
18 5 7
19 NaN 4
20 NaN 8
Converting NaN in y1 to NA −
> df2$y1[is.nan(df2$y1)]<-NA
> df2
y1 y2
1 NA 7
2 NA 5
3 NA 3
4 5 4
5 5 4
6 5 4
7 5 4
8 NA 4
9 5 5
10 NA 5
11 5 5
12 5 2
13 5 9
14 5 3
15 NA 6
16 NA 8
17 5 5
18 5 7
19 NA 4
20 NA 8
What is the Lexical Analysis?

Lexical Analysis is the first step of the compiler which reads the source code one character at a time and transforms it into an array of tokens.
Token − The token is a meaningful collection of characters in a program. These tokens can be keywords including do, if, while etc. and identifiers including x, num, count, etc. and operator symbols including >,>=, +, etc., and punctuation symbols including parenthesis or commas. The output of the lexical analyzer phase passes to the next phase called syntax analyzer or parser.
Example − A statement a = b + 5 will have the tokens.
The main function of lexical analysis are as follows −
It can separate tokens from the program and return those tokens to the parser as requested by it.
It can separate tokens from the program and return those tokens to the parser as requested by it.
It can eliminate comments, whitespaces, newline characters, etc. from the string.
It can eliminate comments, whitespaces, newline characters, etc. from the string.
It can inserts the token into the symbol table.
It can inserts the token into the symbol table.
Lexical Analysis will return an integer number for each token to the parser.
Lexical Analysis will return an integer number for each token to the parser.
The correlating error messages that are produced by the compiler during lexical analyzer with the source program.
The correlating error messages that are produced by the compiler during lexical analyzer with the source program.
It can implement the expansion of macros, in the case of macro pre-processors are used in the source code.
It can implement the expansion of macros, in the case of macro pre-processors are used in the source code.
Example1 − What will be operations performed by the lexical analysis phase on input string a = b + 5.
Solution
Find out tokens and their types.
Find out tokens and their types.
Put information about Tokens into Symbol Table.
Put information about Tokens into Symbol Table.
After finding out tokens and storing them into the symbol table, a token stream is generated as follows −
After finding out tokens and storing them into the symbol table, a token stream is generated as follows −
[i= id, 330] = [id, 332] + [const, 360]
where each pair is of the form [token – type, index]
token-type − It tells whether it is a constant, identifier, label, etc.
index − It tells about the address of the token in the symbol table.
Example2 − What will be the operation performed by lexical analysis on the statement. If (A=10) then GOTO 200.
Solution
Tokens will be
Tokens will be
Symbol Table
Symbol Table
Token Stream will be
Token Stream will be
If ([id, 236] = [constant, 238]) then GOTO [label, 288]
How to get all table names from a database using JDBC?

You can get the list of tables in the current database in MySQL using the SHOW TABLES query.
Show tables;
Following JDBC program retrieves the list of tables in the database by executing the show tables query.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ListingTables {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("Show tables");
      System.out.println("Tables in the current database: ");
      while(rs.next()) {
         System.out.print(rs.getString(1));
         System.out.println();
      }
   }
}
Connection established......
cricketers_data
customers
dispatches_data
employee_data
myplayers
sales
test
tutorials_data
Or, You can use the getTables() method of the DatabaseMetaData interface.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RS_getTables {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      String[] types = {"TABLE"};
      //Retrieving the columns in the database
      ResultSet tables = metaData.getTables(null, null, "%", types);
      while (tables.next()) {
         System.out.println(tables.getString("TABLE_NAME"));
      }
   }
}
Connection established......
cricketers_data
customers
dispatches_data
employee_data
myplayers
sales
test
tutorials_data
Angular Material 7 - Environment Setup

This tutorial will guide you on how to prepare a development environment to start your work with Angular Framework and Angular Material. In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following −
Nodejs
Npm
Angular CLI
IDE for writing your code
Nodejs has to be greater than 8.11 and npm has to be greater than 5.6.
To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system.
C:\>node -v
v8.11.3

If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS.
The homepage of nodejs will look like the following −
Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm.
C:\>npm -v
5.6.0

Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command.
Type npm install -g @angular/cli, to install angular cli on your system.
You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc.
Run the following command to install Angular Material module and its related components in the project created.
materialApp>npm install --save @angular/material @angular/cdk @angular/animations hammerjs

+ @angular/animations@6.1.10
+ @angular/cdk@7.0.3
+ @angular/material@7.0.3
+ hammerjs@2.0.8
added 4 packages and updated 1 package in 39.699s

Add the following entry in app.module.ts file
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

imports: [
    ...
   FormsModule,
   ReactiveFormsModule,
   BrowserAnimationsModule
],
Add the following entry in styles.css file to get a theme.
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
Add the following entry in index.htm file to get a material icons support.
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Reverse a Number in PL/SQL

PL/SQL is a block-structured language that combines SQL's functionality with procedural commands. In this article, we will discuss a program in PL/SQL to reverse a given number for example −
Input : 98765
Output : 56789
Explanation : reverse number of 98765 is 56789.

Input : 56784
Output : 48765
Explanation Reverse number of ‘56784’ is ‘48765’.
Take out the last digit from the number by finding the remainder of num/10.
Now add the last digit to another variable reversed_num.
Now check if num becomes 0 −If YES, then go to STEP1.If NO, then go to STEP4.
If YES, then go to STEP1.
If NO, then go to STEP4.
Finally, print the reversed_num.
DECLARE
num number;
reverse_num number:=0;

begin
num:=98765;
while num>0
loop
reverse_num:=(reverse_num*10) + mod(num,10);
num:=trunc(num/10);
end loop;

dbms_output.put_line(' Reversed number is : '|| reverse_num);


Reversed number is: 56789
In this article, we discuss the PL/SQL programming language, which is very simple to use; it feels like using ordinary English to command the system. We also discussed a problem of reversing a number in PL/SQL language. We hope you find this article helpful.
List.replaceAll(UnaryOperator<E> operator) method in Java

The replaceAll() method of the List interface accept an object of the UnaryOperator representing a particular operation, performs the specified operation on all the elements of the current list and replaces the existing values in the list with their respective results.
 Live Demo
import java.util.ArrayList;
import java.util.function.UnaryOperator;
class Op implements UnaryOperator<String> {
   public String apply(String str) {
      return str.toUpperCase();
   }
}
public class Test {
   public static void main(String[] args) throws CloneNotSupportedException {
      ArrayList<String> list = new ArrayList<>();
      list.add("Java");
      list.add("JavaScript");
      list.add("CoffeeScript");
      list.add("HBase");
      list.add("OpenNLP");
      System.out.println("Contents of the list: "+list);
      list.replaceAll(new Op());
      System.out.println("Contents of the list after replace operation: \n"+list);
   }
}
Contents of the list: [Java, JavaScript, CoffeeScript, HBase, OpenNLP]
Contents of the list after replace operation:[JAVA, JAVASCRIPT, COFFEESCRIPT, HBASE, OPENNLP]
Difference Between Array and Structure

In this post, we will understand the difference between array and structure.
It refers to a collection that consists of elements of homogenous/same data type.
It refers to a collection that consists of elements of homogenous/same data type.
It uses subscripts/ ‘[ ]’ (square brackets) to access the elements.
It uses subscripts/ ‘[ ]’ (square brackets) to access the elements.
It is a pointer that points to the first element of the collection.
It is a pointer that points to the first element of the collection.
The array objects can’t be instantiated.
The array objects can’t be instantiated.
The size of array is fixed based on the number of elements in the array.
The size of array is fixed based on the number of elements in the array.
This size is the product of number of elements and size of every element.
This size is the product of number of elements and size of every element.
Bit field is not possible in an array.
Bit field is not possible in an array.
It is considered as a primitive data type.
It is considered as a primitive data type.
Traversing through and searching for elements in an array is quick and easy.
Traversing through and searching for elements in an array is quick and easy.
It can be declared using the ‘[ ]’.
It can be declared using the ‘[ ]’.
Array size is fixed and is basically the number of elements multiplied by the size of an element.
Array size is fixed and is basically the number of elements multiplied by the size of an element.
It is stored in contiguous memory locations.
It is stored in contiguous memory locations.
data_type array_name[size];
It is a collection that consists of elements of heterogenous/dissimilar data types.
It is a collection that consists of elements of heterogenous/dissimilar data types.
It uses the ‘.’ (dot operator) to access the elements.
It uses the ‘.’ (dot operator) to access the elements.
It isn’t a pointer.
It isn’t a pointer.
It can be instantiated.
It can be instantiated.
The size is not fixed.
The size is not fixed.
This is because the elements in a structure can be of different data types and sizes.
This is because the elements in a structure can be of different data types and sizes.
Bit field is possible to create in a structure.
Bit field is possible to create in a structure.
It can be declared using the ‘struct’ keyword.
It can be declared using the ‘struct’ keyword.
It is a user-defined datatype.
It is a user-defined datatype.
Traversing and searching through a structure is slow and complex.
Traversing and searching through a structure is slow and complex.
They may or may not be stored in a contiguous memory location.
They may or may not be stored in a contiguous memory location.
struct sruct_name {
   data_type1 ele1;
   data_type2 ele2;
};
How to take input in Node.js ? - GeeksforGeeks

07 Oct, 2021
Nowadays the extension of JavaScript i.e Node.js is quite popular among programmers in the field of competitive programming. In this article, we will discuss how to take input from the user.
readline-sync: This is the third party module that is used for taking the input from the user synchronously. So, the execution of the programs is line by line.
Installing module:
npm install readline-sync
Project structure:
Filename- index.js: Taking input array from the user
Javascript
// Importing the moduleconst readline = require("readline-sync");  // Enter the numberlet a = Number(readline.question());let number = [];for (let i = 0; i < a; ++i) {  number.push(Number(readline.question()));}console.log(number);
Run index.js file using below command:
node index.js
Output: This will be in console output.
Filename- index.js: Finding the frequency of the numbers
Javascript
// Importing the moduleconst readline = require("readline-sync");  // Enter the numberlet a = Number(readline.question());let number = [];  // Creating maplet map = new Map();for (let i = 0; i < a; ++i) {  let number = Number(readline.question());  if (map.has(number)) {    map.set(number, map.get(number) + 1);  } else {    map.set(number, 1);  }}  console.log(map);
Run index.js file using below command:
node index.js
Output: This will be in console output.
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Express.js res.redirect() Function
Mongoose | findByIdAndUpdate() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript