code-rag-bench/online-tutorials huggingface dataset:
Python | Summation of dictionary list values

28 Aug, 2019
Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the count of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + list comprehensionThis task can be performed using sum function which can be used to get the summation and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary.
# Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + list comprehension  # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Summation of dictionary list values# using sum() + list comprehensionres = sum(len(sub) for sub in test_dict.values())  # printing resultprint("Summation of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}
Summation of dictionary list values are : 8

 
Method #2 : Using sum() + map()This task can also be performed using map function in place of list comprehension to extend the logic of finding the length, rest all the functionality remaining same as the above method.
# Python3 code to demonstrate working of# Summation of dictionary list values# using sum() + map()  # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Summation of dictionary list values# using sum() + map()res = sum(map(len, test_dict.values()))  # printing resultprint("Summation of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}
Summation of dictionary list values are : 8

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Client side validation with HTML and without JavaScript

To display HTML5 client-side validation error bubbles, use the required attribute.
You do not need to have javascript for client side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value:
<!DOCTYPE HTML>
<html>
   <body>
      <form action = "/cgi-bin/html5.cgi" method = "get">
         Enter email : <input type="text" name = "newinput" required/>
         <p>Try to submit using Submit button</p>
         <input type = "submit" value = "submit" />
      </form>
   </body>
</html>
SAP ABAP - Case Control Statement

The CASE control statement is used when you need to compare two or more fields.
The syntax for CASE control statement is as follows −
CASE <field>. 
 
WHEN <abc>. 
   <statement block>.
   
WHEN <def>. 
   <tatement block>.
   
WHEN <pqr>. 
   <statement block>. 
...... 
...... 
......  
WHEN <xyz>. 
   <statement block>. 
  
WHEN OTHERS. 
   <statement block>.  
ENDCASE.

The following rules apply to a CASE statement −
No logical expressions can be used for the <field> field.
No logical expressions can be used for the <field> field.
The field strings used in the CASE statement are treated as type C variables.
The field strings used in the CASE statement are treated as type C variables.
The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>.
The statement block following a WHEN clause is executed if the content of the fields shown in the <field> is similar to one of the fields <abc>, <def>, <ghi> up to <xyz>.
After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement.
After executing all the conditions specified in the WHEN statement, the program continues to process the remaining statements after the ENDCASE statement.
The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause.
The WHEN OTHERS clause is executed in a program when the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause.
If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement.
If the WHEN OTHERS clause is omitted and the value of the <field> does not match with any value specified in the <abc> up to <xyz> fields of the WHEN clause, the program continues to process the remaining statements after the ENDCASE statement.
Report YH_SEP_15.
  
Data: Title_1(10) TYPE C,  
   Title_2(15) TYPE C.  
	
Title_1 = 'ABAP'.
Title_2 = 'Programming'.  

CASE Title_2.
  
WHEN 'ABAP'. 
   Write 'This is not the title'.  
	
WHEN 'Tutorials'.
   Write 'This is not the title'.  
	
WHEN 'Limited'.
   Write 'This is not the title'.
	
WHEN 'Programming'.
   Write 'Yes, this is the title'.
	
WHEN OTHERS.
   Write 'Sorry, Mismatch'.
	 
ENDCASE. 
The above code produces the following output −
Yes, this is the title.


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
Python program to cyclically rotate an array by one

Given a user input array. Our task is to rotate cyclically means clockwise rotate the value.
Input: A=[1,2,3,4,5]
Output=[5,1,2,3,4]

Step 1: input array element.
Step 2: Store the last element in a variable say x.
Step 3: Shift all elements one position ahead.
Step 4: Replace first element of array with x.

# Python program to cyclically rotate
#an array by one
# Method for rotation
def rotate(A, n):
   x = A[n - 1]
   for i in range(n - 1, 0, -1):
      A[i] = A[i - 1];
   A[0] = x;
# Driver function
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element of  List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
print ("The array is ::>")
for i in range(0, n):
   print (A[i], end = ' ')
rotate(A, n)
print ("\nRotated array is")
for i in range(0, n):
   print (A[i], end = ' ')
Enter the size of the  List ::5
Enter the Element of  List ::
8
7
90
67
56
The array is ::>
8 7 90 67 56 
Rotated array is
56 8 7 90 67
jQuery | focus() with Examples - GeeksforGeeks

03 Aug, 2021
The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button.Syntax:
$(selector).focus(function)

Here selector is the selected element.Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.Return Value: It returns the selected element which get focused.
<html>  <head>    <style>        span {            display: none;        }                  body {            width: 35%;            height: 50px;            border: 2px solid green;            padding: 35px;            margin: 10px;        }    </style>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script></head>  <body>    <!-- this paragraph element get focused -->    <p>        <input type="text"> <span>focused</span></p>      <!-- jQuery cdee to show working of this method -->    <script>        $("input").focus(function() {            $(this).next("span").css("display", "inline");        });    </script>  </body>  </html>
Output:Before the mouse clicking inside of the input field-
After the mouse clicking inside of the input field with text “GeeksforGeeks”-
Code #2:In the below code, no parameter is passed to this method.
<html>  <head>    <style>        span {            display: none;        }                  body {            width: 30%;            height: 50px;            border: 2px solid green;            padding: 35px;            margin: 10px;        }    </style>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script></head>  <body>    <!-- this paragraph element get focused -->    <p>        <input type="text"> <span>focused</span></p>      <!-- jQuery code to show working of this method -->    <script>        $("input").focus();    </script>  </body>  </html>
Output:Before the mouse is clicked inside of the input field-
After the mouse is clicked inside of the input field with text “GeeksforGeeks”-
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
OpenCV Java example to scale an image.

The resize() method of the Imgproc class resizes the specified image. This method accepts −
Two Mat objects representing the source and destination images.
Two Mat objects representing the source and destination images.
A Size object representing the size of the output image.
A Size object representing the size of the output image.
A double variable representing the scale factor along the horizontal axis.
A double variable representing the scale factor along the horizontal axis.
A double variable representing the scale factor along the vertical axis.
A double variable representing the scale factor along the vertical axis.
An integer variable representing the interpolation method to be used in the
operation.
An integer variable representing the interpolation method to be used in the
operation.
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ScalingAnImage extends Application {
   public void start(Stage stage) throws IOException {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading image data
      String file ="D:\\Images\\elephant.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating destination matrix
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      //Creating the Size object
      Size size = new Size(src.rows()*0.5, src.rows()*0.5);
      //Scaling the Image
      Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);
      Imgcodecs.imwrite("D:\\Images\\scaling_example.jpg", dst);
      //Converting matrix to JavaFX writable image
      Image img = HighGui.toBufferedImage(dst);
      WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
      //Setting the image view
      ImageView imageView = new ImageView(writableImage);
      imageView.setX(10);
      imageView.setY(10);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 400);
      stage.setTitle("Scaling Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}
On executing, the above program generates the following output −
DSA using C - Recursion

Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method.
A recursive function must posses the following two characteristics.
Base Case(s)
Base Case(s)
Set of rules which leads to base case after reducing the cases.
Set of rules which leads to base case after reducing the cases.
Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions.
0! = 1
0! = 1
1! = 1
1! = 1
n! = n * n-1!
n! = n * n-1!
Factorial is represented by "!". Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules.
As an example, 3! = 3 x 2 x 1 = 6
int factorial(int n){
   //base case
   if(n == 0){
      return 1;
   } else {
      return n * factorial(n-1);
   }
}
Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions.
F0 = 0
F0 = 0
F1 = 1
F1 = 1
Fn = Fn-1 + Fn-2
Fn = Fn-1 + Fn-2
Fibonacci is represented by "F". Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules.
As an example, F5 = 0 1 1 2 3
#include <stdio.h>

int factorial(int n){
   //base case
   if(n == 0){
      return 1;
   } else {
      return n * factorial(n-1);
   }
}
int fibbonacci(int n){
   if(n ==0){
      return 0;
   }
   else if(n==1){
      return 1;
   } else {
      return (fibbonacci(n-1) + fibbonacci(n-2));
   }
}
main(){
   int n = 5;
   int i;
   printf("Factorial of %d: %d\n" , n , factorial(n));
   printf("Fibbonacci of %d: " , n);
   for(i=0;i<n;i++){
      printf("%d ",fibbonacci(i));            
   }
}
If we compile and run the above program then it would produce following output −
Factorial of 5: 120
Fibbonacci of 5: 0 1 1 2 3

 Print
 Add Notes
 Bookmark this page
How to convert InputStream to byte array in Java?

The InputStream class in Java provides read() method. This method accepts a byte array and it reads the contents of the input stream to the given byte array.
 Live Demo
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamToByteArray {
   public static void main(String args[]) throws IOException {
      InputStream is = new BufferedInputStream(System.in);
      byte [] byteArray = new byte[1024];
      System.out.println("Enter some data");
      is.read(byteArray);
      String s = new String(byteArray);
      System.out.println("Contents of the byte stream are :: "+ s);
   }
}
Enter some data
hello how are you
Contents of the byte stream are :: hello how are you
How to remove underline from a link in HTML?

To remove underline from a link in HTML, use the CSS property text-decoration. Use it with the style attribute. The style attribute specifies an inline style for an element.
Use the style attribute with the CSS property text-decoration to remove underline from a link in HTML. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try the following code to remove underline from a link in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
   <title>HTML Text Decoration</title>
</head>

<body>
   <h2>About</h2>
   <p>
      Our <a href="/about/about_team.htm" style="text-decoration: none;">Team</a>
      comprises of programmers, writers, and analysts.
   </p>
</body>
</html>
Python string | strip() - GeeksforGeeks

11 Aug, 2021
strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Syntax: 
string.strip([chars])
Parameter: 
There is only one optional parameter in it:
1)chars - a string specifying 
the set of characters to be removed. 

If the optional chars parameter is not given, all leading 
and trailing whitespaces are removed from the string.
Return Value:
Returns a copy of the string with both leading and trailing characters removed.
Python3
# Python3 program to demonstrate the use of# strip() method  string = """    geeks for geeks    """ # prints the string without strippingprint(string) # prints the string by removing leading and trailing whitespacesprint(string.strip())   # prints the string by removing geeksprint(string.strip(' geeks'))
    geeks for geeks     
geeks for geeks
for
 
Python3
# Python Program to demonstrate use of strip() method str1 = 'geeks for geeks'# Print the string without stripping.print(str1) # String whose set of characters are to be# remove from original string at both its ends.str2 = 'ekgs' # Print string after stripping str2 from str1 at both its end.print(str1.strip(str2))
geeks for geeks
 for
 
Working of above code : We first construct a string str1 = ‘geeks for geeks’ Now we call strip method over str1 and pass str2 = ‘ekgs’ as argument. Now python interpreter trace str1 from left.It remove the character of str1 if it is present in str2. Otherwise it stops tracing. Now python interpreter trace str1 from right. It remove the character of str1 if it is present in str2. Otherwise it stop tracing. Now at last it returns the resultant string.When we call strip() without argument, it removes leading and trailing spaces.  
Python3
# Python Program to demonstrate use of strip() method without any argumentstr1 = """    geeks for geeks    """ # Print the string without stripping.print(str1) # Print string after removing all leading# and trailing whitespaces.print(str1.strip())
    geeks for geeks     
 
Output: 
geeks for geeks
Practical application: Given a string remove occurrence of word “the” from the beginning and the end.  
Python
# Python3 program to demonstrate the practical application# strip()  string = " the King has the largest army in the entire world the" # prints the string after removing the from beginning and endprint(string.strip(" the"))
the King has the largest army in the entire world the
 
Output: 
King has the largest army in the entire world
 
Vishalmast
akkucoder123
preetishneema312
simranarora5sos
gabaa406
python-string
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
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
jQuery UI Datepicker minDate Option - GeeksforGeeks

19 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Datepicker minDate option is used to set the minimum selectable date. If we set it to null, there is no minimum date.
Syntax:
$( ".selector" ).datepicker({
  minDate: new Date(2007, 1 - 1, 1)
});
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8" />    <link href=    "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"        rel="stylesheet" />    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script>    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>      <!-- Javascript -->    <script>        $(function () {            $("#gfg").datepicker({                minDate: new Date(2021, 1 - 1, 1)            });        });    </script></head>  <body>    <h1>GeeksforGeeks</h1>    <h3>jQuery UI Datepicker minDate Option</h3>      <div>Enter Date: <input type="text" id="gfg" /></div></body>  </html>
Output:
minDate option
Reference: https://api.jqueryui.com/datepicker/#option-minDate
HTML-Tags
jQuery-Methods
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to use AvatarGroup Component in ReactJS? - GeeksforGeeks

05 Mar, 2021
AvatarGroup Component is used to group multiples of Avatars together. It renders its children as a stack. Material UI for React has this component available for us, and it is very easy to integrate. We can use the AvatarGroup Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import AvatarGroup from "@material-ui/lab/AvatarGroup";import Avatar from "@material-ui/core/Avatar";  export default function App() {  return (    <div style={{ display: "block" }}>      <h4>How to use AvatarGroup Component in ReactJS?</h4>      <AvatarGroup max={4}>        <Avatar alt="Geeksforgeeks" src="YourPicturePath" />        <Avatar alt="Random Name" src="YourPicturePath" />        <Avatar alt="Unknow" src="YourPicturePath" />        <Avatar alt="Gourav" src="YourPicturePath" />        <Avatar alt="Harrier" src="YourPicturePath" />      </AvatarGroup>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/avatars/#grouped
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python | Pandas DataFrame.ix[ ] - GeeksforGeeks

28 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DataFrame.ix[ ] is both Label and Integer based slicing technique. Besides pure label based and integer based, Pandas provides a hybrid method for selections and subsetting the object using the ix[] operator. ix[] is the most general indexer and will support any of the inputs in loc[] and iloc[].
Syntax: DataFrame.ix[ ]
Parameters:Index Position: Index position of rows in integer or list of integer.Index label: String or list of string of index label of rows
Returns: Data frame or Series depending on parameters
# importing pandas package import pandas as geek    # making data frame from csv filedata = geek.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")      # Integer slicingprint("Slicing only rows(till index 4):")x1 = data.ix[:4, ]print(x1, "\n")   print("Slicing rows and columns(rows=4, col 1-4, excluding 4):")x2 = data.ix[:4, 1:4]print(x2)
Output : Code #2:
# importing pandas package import pandas as geek    # making data frame from csv filedata = geek.read_csv("nba.csv")      # Index slicing on Height columnprint("After index slicing:")x1 = data.ix[10:20, 'Height']print(x1, "\n")  # Index slicing on Salary columnx2 = data.ix[10:20, 'Salary']print(x2)
Output:
 
Code #3:
# importing pandas and numpyimport pandas as pdimport numpy as np   df = pd.DataFrame(np.random.randn(10, 4),          columns = ['A', 'B', 'C', 'D'])  print("Original DataFrame: \n" , df)   # Integer slicingprint("\n Slicing only rows:")print("--------------------------")x1 = df.ix[:4, ]print(x1)   print("\n Slicing rows and columns:")print("----------------------------")x2 = df.ix[:4, 1:3]print(x2)
Output : Code #4:
# importing pandas and numpyimport pandas as pdimport numpy as np   df = pd.DataFrame(np.random.randn(10, 4),          columns = ['A', 'B', 'C', 'D'])  print("Original DataFrame: \n" , df)   # Integer slicing (printing all the rows of column 'A')print("\n After index slicing (On 'A'):")print("--------------------------")x = df.ix[:, 'A']  print(x)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Python | Ways to split strings on Uppercase characters - GeeksforGeeks

20 Aug, 2020
Given a string, write a Python program to split strings on Uppercase characters. Let’s discuss a few methods to solve the problem.Method #1: Using re.findall() method  
Python3
# Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCase using reres_list = []res_list = re.findall('[A-Z][^A-Z]*', ini_str) # Printing resultprint("Resultant prefix", str(res_list))
 
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']



 
 
Method #2: Using re.split()  
Python3
# Python code to demonstrate# to split strings# on uppercase letter import re # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCase using reres_list = [s for s in re.split("([A-Z][^A-Z]*)", ini_str) if s] # Printing resultprint("Resultant prefix", str(res_list))
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']



 
 
  Method #3: Using enumerate  
Python3
# Python code to demonstrate# to split strings# on uppercase letter # Initialising stringini_str = 'GeeksForGeeks' # Printing Initial stringprint ("Initial String", ini_str) # Splitting on UpperCaseres_pos = [i for i, e in enumerate(ini_str+'A') if e.isupper()]res_list = [ini_str[res_pos[j]:res_pos[j + 1]]            for j in range(len(res_pos)-1)] # Printing resultprint("Resultant prefix", str(res_list))
 
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']



 
 
nayeemulhkhan
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
p5.js | style() Function - GeeksforGeeks

21 Aug, 2019
The style() function is used to set the style property of an element with the given value. If this function contains single parameter then use .style() function to return the value of the given property.
Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file.
<script language=”javascript” type=”text/javascript” src=”path/to/p5.dom.js”></script>
Syntax:
style( property )
or
style( property, value )
Parameters:
property: This parameter holds the CSS property name.
value: This parameter holds the value of CSS property.
Return Value: This function returns the value of property.
Example 1:
function setup() {          // Create canvas of size 400*200     createCanvas(400, 200);          // Set background color    background('green');          // Create an input element    var input_val = createInput('');              // Set the attribute and its value        input_val.attribute('value', 'Welcome to GeeksforGeeks');          // Set the position of div element    input_val.position(60, 80);         // Set width of input field    input_val.style('width', '250px');        // Set font-size of input text    input_val.style('font-size', '20px');  } 
Output:
Example 2:
function setup() {          // Create canvas of size 400*200     createCanvas(400, 200);          // Set background color    background('green');          // Create an input element    var div_cont = createDiv('Welcome to GeeksforGeeks');          // Set the position of div element    div_cont.position(60, 80);         // Set the font color    div_cont.style('color', '#ffffff');          // Set width of input field    div_cont.style('width', '250px');        // Set font-size of input text    div_cont.style('font-size', '20px');  } 
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python | os.set_blocking() method - GeeksforGeeks

18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.set_blocking() method in Python is used to set the blocking mode of the specified file descriptor. This method modifies the os.O_NONBLOCK flag. It sets the os.O_NONBLOCK flag for non-blocking mode and clears the os.O_NONBLOCK flag for blocking mode.
A file descriptor in blocking mode means that I/O system calls like read, write, or connect can be blocked by the system.For example: If we call read system call on stdin then our program will get blocked (the kernel will put the process into the sleeping state) until data to be read is actually available on stdin.
Note: os.set_blocking() method is available on Unix platforms only.
Syntax: os.set_blocking(fd, blocking)
Parameter:fd: A file descriptor whose blocking mode is to be set.blocking: A Boolean value. True if the file descriptor is to be put into blocking mode and false if the file descriptor is to be put into non-blocking mode.
Return Type: This method does not return any value.
# Python program to explain os.set_blocking() method     # importing os module import os  # File path path = "/home/ihritik/Documents/file.txt"  # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR)    # Get the current blocking mode# of the file descriptor# using os.get_blocking() methodprint("Blocking Mode:", os.get_blocking(fd))     # Change the blocking modeblocking = Falseos.set_blocking(fd, blocking)print("Blocking mode changed")    # Get the blocking mode# of the file descriptor# using os.get_blocking() methodprint("Blocking Mode:", os.get_blocking(fd))     # close the file descriptoros.close(fd)    # A False value for blocking# mode denotes that the file# descriptor has been put into# Non-Blocking mode while True# denotes that file descriptor# is in blocking mode.
Blocking Mode: True
Blocking mode changed
Blocking Mode: False

Reference: https://docs.python.org/3/library/os.html#os.set_blocking
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Java - ByteArrayOutputStream

The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer.
Following is the list of the constructors to be provided by ByteArrayOutputStream class.
ByteArrayOutputStream()
This constructor creates a ByteArrayOutputStream having buffer of 32 byte.
ByteArrayOutputStream(int a)
This constructor creates a ByteArrayOutputStream having buffer of the given size.
Once you have ByteArrayOutputStream object in hand, then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
public void reset()
This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.
public byte[] toByteArray()
This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.
public String toString()
Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer's content.
public void write(int w)
Writes the specified array to the output stream.
public void write(byte []b, int of, int len)
Writes len number of bytes starting from offset off to the stream.
public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument.
Following is an example to demonstrate ByteArrayOutputStream and ByteArrayInputStream.
import java.io.*;
public class ByteStreamTest {

   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write("hello".getBytes());  
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      
      for(int x = 0; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");

      int c;
      ByteArrayInputStream bInput = new ByteArrayInputStream(b);
      System.out.println("Converting characters to Upper case " );
      
      for(int y = 0 ; y < 1; y++ ) {
         while(( c = bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}
Here is the sample run of the above program −
Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Send Message on Instagram Using Instabot module in Python - GeeksforGeeks

31 Oct, 2021
In this article, we are going to see how to send messages on Instagram using the Instabot module in Python.
Instagram is a nice platform for chatting but when it comes to sending the same message to all friends this is a really boring and time-consuming task especially if you have a large number of followers. To make this easy we make a bot using Python to send messages on Instagram. So without further delay, let’s jump right in.
Instabot library: It is a script of promotion and API Python wrapper for Instagram.
pip install instabot
Step 1: First we import the Bot from the Instabot library and make a variable bot.
Python3
# importing Bot form instabot library.from instabot import Bot bot = Bot()
Step 2: Now we need to login into our account using the bot.
Python3
# Login using botbot.login(username="Your_username",          password="Your_password")
Step 3: It’s time to make a list of friends/followers to whom messages will be sent. Don’t forget any name because everyone is important. 
Python3
# Make a list of followers/friendsurer_ids = ["username1", "username2", "....."]
Step 4:  Write a message
Python3
# Messagetext = "I like GFG"
Step 5: It’s time to send the message. To send messages to more person use the “send_messages” function and to send messages to a single person “send_message” function also can be used.
Python3
# Sending messages to one or more friendsbot.send_messages(text, urer_ids)
Below is the full implementation:
Python3
# Program to send message# on Instagram using Python. # importing Bot form instabot library.from instabot import Bot # Creating bot variable.bot = Bot() # Login using bot.bot.login(username="Your_username",          password="Your_password") # Make a list of followers/friendsurer_ids = ["username1", "username2", "....."] # Messagetext = "I like GFG" # Sending messagesbot.send_messages(text, urer_ids)
Output:
Note: Sometimes it’s difficult to rerun the program because of login errors to avoid this you need to delete a config folder that is auto-created after running the program once. 
anikakapoor
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
PHP | Check if a number is armstrong number - GeeksforGeeks

30 Apr, 2021
Given a number, we need to check whether it is an armstrong number or not in PHP. An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.Examples:  
Input : 407
Output : Yes
407 = (4*4*4) + (0*0*0) + (7*7*7)  
    = 64 + 0 + 343  
    = 407  

Input : 303
Output : No
 
Approach: For every digit r in input number x, compute r3. If sum of all such values is equal to n, then print “Yes”, else “No”. 
Php
<?php// PHP code to check whether a number is// armstrong number or not // function to check whether the number is// armstrong number or notfunction armstrongCheck($number){    $sum = 0;     $x = $number;     while($x != 0)     {         $rem = $x % 10;         $sum = $sum + $rem*$rem*$rem;         $x = $x / 10;     }          // if true then armstrong number    if ($number == $sum)        return 1;         // not an armstrong number       return 0;   } // Driver Code$number = 407;$flag = armstrongCheck($number);if ($flag == 1)    echo "Yes";else    echo "No"?>
Output:  
Yes
Time Complexity: O(num), where num is the number of digits in the given number. 
hritikbhatnagar2182
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
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
CURRENT_USER() Function in SQL Server - GeeksforGeeks

15 Feb, 2021
CURRENT_USER() function :This function in SQL Server is used to return the current user’s name in the database of SQL Server in use.
Features :
This function is used to find the current user’s name.
This function comes under Advanced Functions.
This function doesn’t accept any parameter.
Syntax :
CURRENT_USER
Parameter : This method does not accept any parameter.
Returns : It returns the current user’s name in the database of SQL Server which is in use.
Example-1 :Using CURRENT_USER () function and getting the current user’s name.
SELECT CURRENT_USER;
Output :
nidhi
Example-2 :Using CURRENT_USER as a default value in the below example and getting the output.
CREATE TABLE user01 (  
user_id int IDENTITY(100, 2) NOT NULL,
customer_id int NOT NULL,
user_name char(50) NOT NULL DEFAULT CURRENT_USER
); 
 Inserting values in the table –
INSERT user01(customer_id)  
VALUES (101), (102);
Displaying the contents of the table –
SELECT * 
FROM user01;  
Output :
Here, firstly you need to create a table then insert values into it then generate the required output using CURRENT_USER function as a default value.
Note: For running above code use SQL server compiler, you can also use an online compiler.
Example-3 :Using CURRENT_USER () function and impersonating user ‘Geek’.
SELECT CURRENT_USER;  
EXECUTE AS USER = 'Geek';  
SELECT CURRENT_USER;   
Output :
nidhi
Geek
Here, we are impersonating user as ‘Geek’, then calling CURRENT_USER function to get the current user’s name.
Example-4 :Using CURRENT_USER () function for impersonating user ‘Geek’ then again reverting the code to get the previous current user.
SELECT CURRENT_USER;  
EXECUTE AS USER = 'Geek';  
SELECT CURRENT_USER;   
REVERT;
SELECT CURRENT_USER;
Output :
nidhi
Geek
nidhi
Application :
This function is used to find the current user’s name in the database of the SQL server.
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
What is Temporary Table in SQL?
Conflict Serializability in DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
How to write the output to HTML file with Python BeautifulSoup? - GeeksforGeeks

08 Apr, 2021
In this article, we are going to write the output to an HTML file with Python BeautifulSoup.  BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file.
Modules needed and installation:
pip install bs4
Approach:
We will first import all the required libraries.
Make a get request to the desired URL and extract its page content.
Using the file data type of python write the output in a new file.
Steps to be followed:
Step 1: Import the required libraries.
Python3
# Import librariesfrom bs4 import BeautifulSoupimport requests
Step 2: We will perform a get request to the Google search engine home page and extract its page content and make a soup object out of it by passing it to beautiful soup, and we will set the markup as html.parser.
Note: if you are extracting a xml page set the markup as xml.parser
Python3
# set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL)  # load the page contenttext = page.content  # make a soup object by using beautiful# soup and set the markup as html parsersoup = BeautifulSoup(text, "html.parser")
Step 3: We use the file data type of python and write the soup object in the output file. We will set the encoding to UTF-8. We will use .prettify() function on soup object that will make it easier to read. We will convert the soup object to a string before writing it.
We will store the output file in the same directory with the name output.html
Python3
# open the file in w mode# set encoding to UTF-8with open("output.html", "w", encoding = 'utf-8') as file:        # prettify the soup object and convert it into a string      file.write(str(soup.prettify()))
Below is the full implementation:
Python3
# Import librariesfrom bs4 import BeautifulSoupimport requests  # set the url to perform the get requestURL = 'https://www.geeksforgeeks.org/how-to-scrape-all-pdf-files-in-a-website/'page = requests.get(URL)  # load the page contenttext = page.content  # make a soup object by using# beautiful soup and set the markup as html parsersoup = BeautifulSoup(text, "html.parser")  # open the file in w mode# set encoding to UTF-8with open("output.html", "w", encoding = 'utf-8') as file:        # prettify the soup object and convert it into a string    file.write(str(soup.prettify()))
Output:
Picked
Python BeautifulSoup
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()