code-rag-bench/online-tutorials huggingface dataset:
Using UPDATE Expression

The update() method on target table object constructs equivalent UPDATE SQL expression.
table.update().where(conditions).values(SET expressions)
The values() method on the resultant update object is used to specify the SET conditions of the UPDATE. If left as None, the SET conditions are determined from those parameters passed to the statement during the execution and/or compilation of the statement.
The where clause is an Optional expression describing the WHERE condition of the UPDATE statement.
Following code snippet changes value of ‘lastname’ column from ‘Khanna’ to ‘Kapoor’ in students table −
stmt = students.update().where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor')
The stmt object is an update object that translates to −
'UPDATE students SET lastname = :lastname WHERE students.lastname = :lastname_1'
The bound parameter lastname_1 will be substituted when execute() method is invoked. The complete update code is given below −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()

students = Table(
   'students', 
   meta, 
   Column('id', Integer, primary_key = True), 
   Column('name', String), 
   Column('lastname', String), 
)

conn = engine.connect()
stmt=students.update().where(students.c.lastname=='Khanna').values(lastname='Kapoor')
conn.execute(stmt)
s = students.select()
conn.execute(s).fetchall()
The above code displays following output with second row showing effect of update operation as in the screenshot given −
[
   (1, 'Ravi', 'Kapoor'),
   (2, 'Rajiv', 'Kapoor'),
   (3, 'Komal', 'Bhandari'),
   (4, 'Abdul', 'Sattar'),
   (5, 'Priya', 'Rajhans')
]

Note that similar functionality can also be achieved by using update() function in sqlalchemy.sql.expression module as shown below −
from sqlalchemy.sql.expression import update
stmt = update(students).where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor')

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Java Examples - Display line using GUI

How to draw a line using GUI?
Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument.
import java.awt.*; 
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.JApplet;
import javax.swing.JFrame;

public class Main extends JApplet {
   public void init() {
      setBackground(Color.white);
      setForeground(Color.white);
   }
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setPaint(Color.gray);
      int x = 5;
      int y = 7;
      g2.draw(new Line2D.Double(x, y, 200, 200));
      g2.drawString("Line", x, 250);
   }
   public static void main(String s[]) {
      JFrame f = new JFrame("Line");
      f.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      JApplet applet = new Main();
      f.getContentPane().add("Center", applet);
      applet.init();
      
      f.pack();
      f.setSize(new Dimension(300, 300));
      f.setVisible(true);
   }
}
The above code sample will produce the following result.
Line is displayed in a frame.

 Print
 Add Notes
 Bookmark this page
HTML5 - Fonts Reference

Fonts are specific to platform. If you are using different OS then you will have different look and feel of any web page. Here we are giving a list of fonts which are available to various operating systems.
HTML <FONT> tag is deprecated in version 4.0 onwards and now all fonts are set by using CSS. Here is the simple syntax of setting font of a body of web page.
body { font-family: "new century schoolbook"; }
or
<body style="font-family:new century schoolbook;" >
This will produce following result −
Change any of the style and try it.
You can have more information on Microsoft Fonts at http://www.microsoft.com/typography/fonts.
You can check example fonts here − Microsoft Fonts Examples
Following is the list of fonts supported by Macintosh System 7 and higher versions
You can check example fonts here − Mac Fonts Examples
Following is the list of fonts supported by most Unix System variants
You can check example fonts here − Unix Fonts Examples

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Difference between namespace in C# and packages in Java

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
Define a Package as −
package package_name;
Restrict the access of classes (or class members) to the classes within the same package, but in C# with namespaces you cannot achieve this.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
Define a Namespace as −
namespace namespace_name {
   // code declarations
}
In Java, the directory structure should match the package structure, but not required in C#.
In C#, add multiple namespaces in one file, whereas in Java, a file belongs to a package.
Buying Cars in Python

Suppose we have a list of prices of cars for sale, and we also have a budget k, we have to find the maximum number of cars we can buy.
So, if the input is like [80, 20, 10, 30, 80], k = 85, then the output will be 3 as we can buy three cars with prices 20, 10, 40
To solve this, we will follow these steps −
count := 0
count := 0
sort the list prices
sort the list prices
for i in range 0 to size of prices, doif prices[i] <=k, thenk := k-prices[i]count := count + 1otherwise,come out from the loop
for i in range 0 to size of prices, do
if prices[i] <=k, thenk := k-prices[i]count := count + 1
if prices[i] <=k, then
k := k-prices[i]
k := k-prices[i]
count := count + 1
count := count + 1
otherwise,come out from the loop
otherwise,
come out from the loop
come out from the loop
return count
return count
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, prices, k):
      count =0
      prices.sort()
      for i in range(len(prices)):
         if(prices[i]<=k):
            k = k-prices[i]
            count += 1
         else:
            break
      return count
ob = Solution()
p = [80, 20, 10, 30, 80]
print(ob.solve(p, 85))
[80, 20, 10, 30, 80], 85
3
How do we handle circular dependency between Python classes?

We have the following code which shows circular dependency between the python classes.
class P():
     q = Q().do_something();
     def do_something(self):
         pass
 class Q():
     p = P().do_something();
     def do_something(self):
         pass
In case of classes, unlike with functions, the body of a class is executed at definition time. To define class P, we need to actually call a Q method, which we can't do because class Q isn't defined yet.
To work around this, we can define the classes and then add the properties afterward −
class P(object):
   pass
class Q(object):
   pass
P.q = Q.do_something()
Q.p = P.do_something()
If each do_something call relies on the other call already having been executed, this won't work. We still need to perform more changes to fix the problem.
Classes have these problems because directives on the class level (q = Q.do_something()) are executed while defining the class, not when you create an instance of the class
We may complete the definition of a class later, after both classes are defined. This proves the point that Python is a dynamic language..
Find numbers whose sum of digits equals a value

There are a number n and a value. We have to find all n digit numbers, where the sum of all n digit the s is the same as the given value. Here 0 is noa t counted as a digit.
The number n must be in the range 1 to 100, and value must be in range 1 to 500.
Input:
This algorithm takes number of digits, and the sum value.
Let the digit count is 3. and sum is 15.
Output:
Display the number of different 3-digit numbers whose sum is 15.
The result is 69. (There are 69 different 3-digit numbers whose sum is 15)
count(digit, sum)
Input: Digit of numbers, given value.
Output: Count how many numbers.
Begin
   if digit = 0, then
      return true when sum = 0

   if memTable[digit, sum] is not vacant, then
      return memTable[digit, sum]
   answer := 0

   for i := 0 to 9 do
      if sum – i >= 0, then
         answer := answer + count(digit – 1, sum - i)
   done

   return memTable[digit, sum] := answer
End
numberCount(digit, sum)
Input: Digits of number, the given value.
Output: How many numbers of that type of number.
Begin
   define memTable and make all space vacant
   res := 0

   for i := 1 to 9, do
      if sum – i >= 0, then
         res := res + count(digit – 1, sum - i)
   done

   return result
End
#include<iostream>
#define ROW 101
#define COL 501
using namespace std;

unsigned long long int memTable[ROW][COL];

unsigned long long int count(int digit, int sum) {
   if (digit == 0)    //for 0 digit number check if the sum is 0 or not
      return sum == 0;

   if (memTable[digit][sum] != -1)    //when subproblem has found the result, return it
      return memTable[digit][sum];

   unsigned long long int ans = 0;    //set the answer to 0 for first time

   for (int i=0; i<10; i++)    //count for each digit and find numbers starting with it
      if (sum-i >= 0)
         ans += count(digit-1, sum-i);
   return memTable[digit][sum] = ans;
}

unsigned long long int numberCount(int digit, int sum) {
   for(int i = 0; i<ROW; i++)    //initially all entries of memorization table is -1
      for(int j = 0; j<ROW; j++)
         memTable[i][j] = -1;
               
   unsigned long long int result = 0;
   for (int i = 1; i <= 9; i++)    //count for each digit and find numbers starting with it
      if (sum-i >= 0)
         result += count(digit-1, sum-i);
   return result;
}

int main() {
   int digit, sum;
   cout << "Enter digit count: "; cin >> digit;
   cout << "Enter Sum: "; cin >> sum;
   cout << "Number of values: " << numberCount(digit, sum);
}
Enter digit count: 3
Enter Sum: 15
Number of values: 69
Interface in C#

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
Let us see how to declare interface in C# with interface members −
public interface ITransactions {
   // interface members
   void showTransaction();
   double getAmount();
}
The following is an example showing how to use Interface in C# −
 Live Demo
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace Demo {

   public interface ITransactions {
      // interface members
      void showTransaction();
   }

   public class Transaction : ITransactions {
      private string tCode;
      private string date;

      public Transaction() {
         tCode = " ";
         date = " ";
      }
      public Transaction(string c, string d) {
         tCode = c;
         date = d;
      }

      public void showTransaction() {
         Console.WriteLine("Transaction ID: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
      }
   }

   class Tester {

      static void Main(string[] args) {
         Transaction t1 = new Transaction("8877", "6/25/2018");
         Transaction t2 = new Transaction("5656", "7/25/2018");

         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}
Transaction ID: 8877
Date: 6/25/2018
Transaction ID: 5656
Date: 7/25/2018
JavaScript TypeError - Cannot use 'in' operator to search for 'X' in 'Y' - GeeksforGeeks

19 Aug, 2020
This JavaScript exception Cannot use ‘in’ operator to search for ‘X’ in ‘Y’ occurs if in operator is used to search in strings, numbers, or other primitive types. It can not be used other than type-checking.
Message:
TypeError: Invalid operand to ‘in’ (Edge)TypeError: right-hand side of ‘in’ must be an object, got ‘x’ (Firefox)TypeError: cannot use ‘in’ operator to search for ‘x’ in ‘y’ (Firefox, Chrome)
Error Type:
TypeError
Cause of the Error: The in operator can be used only for to check if a property is in an object. This can not be used for search in strings, numbers, or other primitive types.
Example 1: in operator can not be used for string search, So the error has occurred.
HTML
<script>"Geek" in "GeeksForGeeks"; // error here</script>
Output:
TypeError: Invalid operand to 'in'

Example 2: in operator can not be used for string search, So the error has occurred.
HTML
<script>var gfg = null;"Geek" in gfg; // error here</script>
Output:
TypeError: Invalid operand to 'in'

javascript-typedArray
JavaScript
Web Technologies
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
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?
floor() and ceil() function Python

These two methods are part of python math module which helps in getting the nearest integer values of a fractional number.
It accepts a number with decimal as parameter and returns the integer which is smaller than the number itself.
Syntax: floor(x)
Where x is a numeric value
In the below example we take different types of numeric values like, integer, positive decimal and negative decimal and apply the floor function to them. We get the nearest integer which is less than the numeric value supplied.
import math
x,y,z = 21 , -23.6 , 14.2
print("The value of ",x, "on applying floor() function is:", math.floor(x))
print("The value of ",y, "on applying floor() function is:", math.floor(y))
print("The value of ",z, "on applying floor() function is:", math.floor(z))
Running the above code gives us the following result −
The value of 21 on applying floor() function is: 21
The value of -23.6 on applying floor() function is: -24
The value of 14.2 on applying floor() function is: 14
It accepts a number with decimal as parameter and returns the integer which is greater than the number itself.
Syntax: veil(x)
Where x is a numeric value
In the below example we take different types of numeric values like, integer, positive decimal and negative decimal and apply the ceil function to them. We get the nearest integer which is greater than the numeric value supplied.
import math
x,y,z = 21 , -23.6 , 14.2
print("The value of ",x, "on applying ceil() function is:", math.ceil(x))
print("The value of ",y, "on applying ceil() function is:", math.ceil(y))
print("The value of ",z, "on applying ceil() function is:", math.ceil(z))
Running the above code gives us the following result −
The value of 21 on applying ceil() function is: 21
The value of -23.6 on applying ceil() function is: -23
The value of 14.2 on applying ceil() function is: 15
How to execute Python multi-line statements in the one-line at command-line?

There are multiple ways in which you can use multiline statements in the command line in python. For example, bash supports multiline statements, which you can use like −
$ python -c '
> a = True
> if a:
> print("a is true")
> '
This will give the output −
a is true
If you prefer to have the python statement in a single line, you can use the \n newline between the commands. 
$ python -c $'a = True\nif a: print("a is true");'
This will give the output −
a is true
How to update a column of varchar type in MySQL to increase its length?

Let us first create a table. Here, we have two columns with varchar type −
mysql> create table DemoTable
(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserFirstName varchar(10),
   UserLastName varchar(20) ,
   UserAge int
);
Query OK, 0 rows affected (0.96 sec)
Let us check the description of table using DESC command −
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| UserId        | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserFirstName | varchar(10) | YES  |     | NULL    |                |
| UserLastName  | varchar(20) | YES  |     | NULL    |                |
| UserAge       | int(11)     | YES  |     | NULL    |                |
+---------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Following is the query to update a column of varchar type in MySQL to increase its length −
mysql> alter table DemoTable modify UserFirstName varchar(40);
Query OK, 0 rows affected (0.23 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again to check what we did above. We updated the length of varchar type −
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| UserId        | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserFirstName | varchar(40) | YES  |     | NULL    |                |
| UserLastName  | varchar(20) | YES  |     | NULL    |                |
| UserAge       | int(11)     | YES  |     | NULL    |                |
+---------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Google Charts - Basic Donut Chart

Following is an example of a donut chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used pieHole configuration to set a pie chart as donut chart.
// Set chart options
var options = { 
   pieHole: 0.4
};
googlecharts_pie_donut.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Browser');
            data.addColumn('number', 'Percentage');
            data.addRows([
               ['Firefox', 45.0],
               ['IE', 26.8],
               ['Chrome', 12.8],
               ['Safari', 8.5],
               ['Opera', 6.2],
               ['Others', 0.7]
            ]);
               
            // Set chart options
            var options = {
               'title':'Browser market shares at a specific website, 2014',
               'width':550,
               'height':400,
               pieHole: 0.4
            };

            // Instantiate and draw the chart.
            var chart = new google.visualization.PieChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
How to use Waitersto check whether an S3 bucket exists,using Boto3 and AWS Client?

In this article, we will see how to use Boto3 library and the Waiter functionality to validate whether an S3 bucket exists or not. For example, use waiters to check whether Bucket_1 exists in S3
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − Use bucket_name as the parameter in the function.
Step 3 − Create an AWS session using boto3 library.
Step 4 − Create an AWS client for S3.
Step 5 − Now create the wait object for bucket_exists using get_waiter function.
Step 6 − Now, use the wait object to validate whether bucket exists or not. By default, it checks in every 5 seconds until a successful state is reached. An error is returned after 20 failed checks. However, user can define polling time and max attempts.
Step 7 − It returns None.
Step 8 − Handle the generic exception if something went wrong while checking the bucket.
Use the following code to use waiter to check whether bucket_exists or not −
import boto3
from botocore.exceptions import ClientError

def use_waiters_check_bucket_exists(bucket_name):
   session = boto3.session.Session(profile_name='saml')
   s3_client = session.client('s3')
   try:
      waiter = s3_client.get_waiter('bucket_exists')
      waiter.wait(Bucket=bucket_name,
                  WaiterConfig={
                     'Delay': 2, 'MaxAttempts': 5})
      print('Bucket exists: ' + bucket_name)
   except ClientError as e:
      raise Exception( "boto3 client error in use_waiters_check_bucket_exists: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in use_waiters_check_bucket_exists: " + e.__str__())

print(use_waiters_check_bucket_exists("Bucket_1"))
print(use_waiters_check_bucket_exists("Bucket_2"))
Bucket exists: Bucket_1
None

botocore.exceptions.WaiterError: Waiter BucketExists failed: Max
attempts exceeded
"Unexpected error in use_waiters_check_bucket_exists: " + e.__str__())
Exception: Unexpected error in use_waiters_check_bucket_exists: Waiter
BucketExists failed: Max attempts exceed
For Bucket_1, the output is print statement and None. Since the response doesn’t return anything, it prints None.
For Bucket_2, the output is an exception, since this bucket doesn’t exist.
In exception, it can be read that Max attempts exceeded.
Program to find the number of unique integers in a sorted list in Python

Suppose we have a list of sorted numbers called nums we have to find the number of unique elements in the list.
So, if the input is like nums = [3, 3, 3, 4, 5, 7, 7], then the output will be 4, as The unique numbers are [3, 4, 5, 7]
To solve this, we will follow these steps −
s:= a new set
cnt:= 0
for each i in nums, doif i is not in s, theninsert i into scnt := cnt + 1
if i is not in s, theninsert i into scnt := cnt + 1
insert i into s
cnt := cnt + 1
return cnt
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      s=set()
      cnt=0
      for i in nums:
         if i not in s:
            s.add(i)
            cnt += 1
      return cnt
ob = Solution()
print(ob.solve([3, 3, 3, 4, 5, 7, 7]))
[3, 3, 3, 4, 5, 7, 7]
4
Python | Pandas Series.equals() - GeeksforGeeks

13 Feb, 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.equals() function test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements.
Syntax: Series.equals(other)
Parameter :other : The other Series or DataFrame to be compared with the first.
Returns : True if all elements are the same in both objects, False otherwise.
Example #1: Use Series.equals() function to check whether the underlying data in the two given series objects are same or not.
# importing pandas as pdimport pandas as pd  # Creating the first Seriessr1 = pd.Series([80, 25, 3, 25, 24, 6])  # Creating the second Seriessr2 = pd.Series([80, 25, 3, 80, 24, 25])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the first series indexsr1.index = index_  # set the second series indexsr2.index = index_  # Print the first seriesprint(sr1)  # Print the second seriesprint(sr2)
Output :
Now we will use Series.equals() function to check if the underlying data in the two given series objects are same or not.
# check for equalityresult = sr1.equals(other = sr2)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.equals() function has returned False indicating the element in the two given series objects are not same. Example #2: Use Series.equals() function to check whether the underlying data in the two given series objects are same or not.
# importing pandas as pdimport pandas as pd  # Creating the first Seriessr1 = pd.Series([80, 25, 3, 25, 24, 6])  # Creating the second Seriessr2 = pd.Series([80, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the first series indexsr1.index = index_  # set the second series indexsr2.index = index_  # Print the first seriesprint(sr1)  # Print the second seriesprint(sr2)
Output :
Now we will use Series.equals() function to check if the underlying data in the two given series objects are same or not.
# check for equalityresult = sr1.equals(other = sr2)  # Print the resultprint(result)
Output :As we can see in the output, the Series.equals() function has returned True indicating the element in the two given series objects are same.
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.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Python program to right rotate a list by n

Given a user input list and given the rotation number. Our task is to rotate the list from the given rotation number.
Input A= [2, 4, 5, 12, 90]
rotation number=3
Output [ 90,12,2, 4, 5]

Here we traverse each element in the list and insert the element at required places in the second list.
def right_rotation(my_list, num): 
   output_list = []
   for item in range(len(my_list) - num, len(my_list)):
      output_list.append(my_list[item])
   for item in range(0, len(my_list) - num):
      output_list.append(my_list[item])
   return output_list
# Driver Code
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("n="))
   A.append(int(p))
   print (A)
rot_num=int(input("Enter rotate number"))
print("After rotation",right_rotation(A, rot_num))
python54.py
Enter the size of the List 6
Enter the number
n= 11
[11]
n= 22
[11, 22]
n= 33
[11, 22, 33]
n= 44
[11, 22, 33, 44]
n= 55
[11, 22, 33, 44, 55]
n= 66
[11, 22, 33, 44, 55, 66]
Enter rotate number 3
After rotation [44, 55, 66, 11, 22, 33]

Here we apply slicing technique using len().
A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[len(A) - n:len(A)] + A[0:len(A) - n])
print("After Rotation",A)
Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]

In this method, last n elements of the list A were taken and then remaining elements of the list A.
A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[-n:] + A[:-n])
print("After Rotation",A)
Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]
How to mark abbreviation or acronyms in HTML?

To add abbreviation or acronym in HTML, use the <abbr> tag. Both abbreviation and acronym are the shortened versions and are represented as a series of letters. Some of the examples include, "Mr.", "MRP", "GMT", “NASA”, etc.
You can try to run the following code to mark abbreviation or acronyms in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML abbr tag</title>
   </head>

   <body>
      <h1>Timings</h1>
      <p>
         We follow <abbr title="Indian Standard Time">IST</abbr> for our webinars.
      </p>
   </body>
</html>
Count the number of rows and columns of a Pandas dataframe - GeeksforGeeks

28 Jul, 2020
Pandas allow us to get the shape of the dataframe by counting the numbers of rows and columns in the dataframe. You can try various approaches to get the number of rows and columns of the dataframe. All of them have been discussed below.
Example: Let’s take an example of a dataframe which consists of data of exam result of students.
# importing pandas import pandas as pdresult_data = {'name': ['Katherine', 'James', 'Emily',                        'Michael', 'Matthew', 'Laura'],        'score': [98, 80, 60, 85, 49, 92],        'age': [20, 25, 22, 24, 21, 20],        'qualify_label': ['yes', 'yes', 'no',                          'yes', 'no', 'yes']}  # creating dataframedf = pd.DataFrame(result_data, index = None)  # computing number of rowsrows = len(df.axes[0])  # computing number of columnscols = len(df.axes[1])  print(df)print("Number of Rows: ", rows)print("Number of Columns: ", cols)
Output :
Example: Let’s take an example of a dataframe that consists of data on product sales.
# importing pandas import pandas as pd  # creating dataframedf = pd.DataFrame({'Product' : ['Carrots', 'Broccoli', 'Banana',                                 'Banana', 'Beans', 'Orange',                                'Broccoli', 'Banana'],                   'Category' : ['Vegetable', 'Vegetable', 'Fruit',                                  'Fruit', 'Vegetable', 'Fruit',                                  'Vegetable', 'Fruit'],                   'Quantity' : [8, 5, 3, 4, 5, 9, 11, 8],                   'Amount' : [270, 239, 617, 384, 626, 610, 62, 90]})  print(df)  # getting number of rowsprint("Number of Rows: ", len(df.axes[0]))  # getting number of columnsprint("Number of Columns: ", len(df.axes[1]))
Output :
Example: Here, we will try a different approach for calculating rows and columns of a dataframe of imported csv file.
# importing pandasimport pandas as pd  # importing csv filedf = pd.read_csv('https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv')  print(df.head())  # obtaining the shapeprint("shape of dataframe", df.shape)  # obtaining the number of rowsprint("number of rows : ", df.shape[0])  # obtaining the number of columnsprint("number of columns : ", df.shape[1])
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Node.js fs-extra remove() Function - GeeksforGeeks

15 Feb, 2022
the remove() function deletes the given file or directory. All the files inside a directory are deleted. If the given file or directory does not exist the function will do nothing.
Syntax:
fs.remove(path,callback)
Parameters: This function accepts two parameters as mentioned above and described below.
path: It is a string that contains the file path or directory path.
callback: It will be called after the function is executed. We can use promises in place of the callback function as well.
Return value: It does not return anything.
Follow the steps to implement the function:
The module can be installed by using the following command:
 
npm install fs-extra
After the installation of the module you can check the version of the installed module by using this command:
 
npm ls fs-extra
Create a file with the name index.js and require the fs-extra module in the file using the following command:
 
const fs = require('fs-extra');
To run the file write the following command in the terminal:
 
node index.js
sagar0719kumar
NodeJS-fs-extra
Technical Scripter 2020
JavaScript
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 var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
How to find the average of elements of an integer array in C#?

The following is our integer array −
int[] myArr = new int[6] {
   8,
   4,
   2,
   5,
   9,
   14
};
Firstly, get the length of the array, and loop through the array to find the sum of the elements. After that, divide it with the length.
int len = myArr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < len; i++) {
   sum += myArr[i];
}
average = sum / len;
Here is the complete code
 Live Demo
using System;
public class Program {
   public static void Main() {
      int[] myArr = new int[6] {
         8,
         4,
         2,
         5,
         9,
         14
      };
      int len = myArr.Length;
      int sum = 0;
      int average = 0;
      for (int i = 0; i < len; i++) {
         sum += myArr[i];
      }
      average = sum / len;
      Console.WriteLine("Sum = " + sum);
      Console.WriteLine("Average Of integer elements = " + average);
   }
}
Sum = 42
Average Of integer elements = 7
ISRO | ISRO CS 2011 | Question 56 - GeeksforGeeks

11 May, 2018
Let T(n) be defined by T(1) = 10 and T(n + 1) = 2n + T(n) and for all integers n ≥ 1 . Which of the following represents the order of growth of T(n) as a function of(A) O(n)(B) O(n log n)(C) O(n2)(D) O(n3)Answer: (C)Explanation:
T(n + 1) = 2n + T(n) 
By substitution method:
T(n + 1) = 2n + (2(n-1) + T(n-1))
T(n + 1) = 2n + (2(n-1) + (2(n-2) + T(n-2)))
T(n + 1) = 2n + (2(n-1) + (2(n-2) + (2(n-3) + T(n-3))))
T(n + 1) = 2n + 2(n-1) + 2(n-2) + 2(n-3)......2(n-(n-1) + T(1))
T(n + 1) = 2n + 2n - 2 + 2n - 4 + 2n - 6 +.... + 10
T(n + 1) = 2[n + n + n + ...] - 2[1 + 2 + 3 +...]
T(n + 1) = 2[n*n] - 2[n(n+1)/2]
T(n + 1) = 2[n*n] - [n*n + n]
T(n + 1) = n*n - n
T(n + 1) = O(n2)
Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2013 | Question 4
ISRO | ISRO CS 2013 | Question 52
ISRO | ISRO CS 2015 | Question 51
ISRO | ISRO CS 2018 | Question 16
ISRO | ISRO CS 2011 | Question 43
ISRO | ISRO CS 2011 | Question 26
ISRO | ISRO CS 2015 | Question 52
ISRO | ISRO CS 2013 | Question 6
ISRO | ISRO CS 2017 - May | Question 17
Python | time.get_clock_info() method

26 Aug, 2019
Time module in Python provides various time related functions.
time.get_clock_info() method in Time module is used to get the information on the specified clock name. This method return the information as a namespace object.The name of supported clocks and the method used to read that clock value are as follow:
clock : time.clock()
monotonic : time.monotonic()
perf_counter : time.perf_counter()
process_time : time.process_time()
thread_time : time.thread_time()
time : time.time()
Syntax: time.get_clock_info(name)
Parameter:name: A string value representing the clock name.
Return type: This method returns a namespace object whose attributes represents the information about specified clock name.Following are the attributes of namespace object:
adjustable: This is ‘True’ if the clock can be changed automatically or manually by the system administrator. Otherwise ‘False’.
implementation: The name of the underlying C function used to get the clock value.
monotonic: It’s value is true, if the clock can not go backward. Otherwise False.
resolution: This attribute specify the resolution of clock in seconds.
Code: Use of time.get_clock_info() method
# Python program to explain time.get_clock_info() method  # importing time moduleimport time  # Clock nameclock_name = 'clock'  # Get the information on# the specified clock nameclock_info = time.get_clock_info(clock_name)  # Print the informationprint("Information on '% s':" % clock_name)print(clock_info)   clock_name = 'perf_counter'  # Get the information on# the specified clock nameclock_info = time.get_clock_info(clock_name)  # Print the informationprint("\nInformation on '% s':" % clock_name)print(clock_info)   clock_name = 'process_time'  # Get the information on# the specified clock nameclock_info = time.get_clock_info(clock_name)  # Print the informationprint("\nInformation on '% s':" % clock_name)print(clock_info) 
Information on 'clock':
namespace(adjustable=False, implementation='clock()',
monotonic=True, resolution=1e-06)

Information on 'perf_counter':
namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)',
monotonic=True, resolution=1e-09)

Information on 'process_time':
namespace(adjustable=False, implementation='clock_gettime(CLOCK_PROCESS_CPUTIME_ID)',
monotonic=True, resolution=1e-09)

Reference: https://docs.python.org/3/library/time.html#time.get_clock_info
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is CTFs (Capture The Flag)

21 Nov, 2019
With the ever-rising need for cybersecurity experts, there has never been a better time to become an ethical hacker. If you have ever grown up wanting to be a hacker, now is the time to start working on your dream. Companies hire ethical hackers to find and patch up security flaws in their systems, so as to prevent cybercriminals from being able to hack them.
So How can one become an ethical hacker? While the process involves certification exams to prove your skills as a hacker, CTFs provide a way to understand the basics of computers and networking and put your skills into action.
What is CTF (Capture The Flag) ?A CTF stands for Capture the Flag, a game in which players put their skills to practice to solve problems or break into an opponent’s system. Below are different types of CTFs –
Jeopardy style: In this variant, players solve certain problems to acquire “flags”(a specific string of text) to win.
Attack-Defence: In this type, two teams are created- Red Team (which tries to breach the system) and Blue Team (which tries to defend the system).
What takes place in a CTF?In this post, we will talk about Jeopardy-style CTF since it is the most beginner-friendly. In a CTF, the CTF server hosts problems which upon solving reveals a “flag”. A flag is a string of text which needs to be entered into the website to show that you have solved the CTF.
What is required to participate in a CTF?Most CTFs are free and only require the participant to signup. Some skills required to start:
1. Basic Computer Knowledge
2. Basic Programming Skills
3. Basic Networking Skills
4. Creative Problem Solving Skills
5. Know how to research
Common Challenge Types –
Cryptography – Usually involves decrypting or encrypting a piece of data
Steganography – Involves finding information hidden in files or images
Binary – Reverse engineering or exploiting a binary file
Web Exploitation – Exploiting web pages to find the flag
Pwn – Exploiting a server to find the flag.
Why should one take part in a CTF?The best part about a CTF is that you can start with a basic knowledge base and advance your knowledge and skills as you progress further. Most players actively learn about new terminologies and technologies when they research online to understand the technology behind the problem or find a way to efficiently solve that kind of problem.Another reason to take part in a CTF is that you get to know more people as you compete against each other or collaborate to solve that one problem outside your area of expertise. This helps build your social skills as you learn to communicate and collaborate with others as a team, a skill many employers seek in potential employees.
Last but not least, the challenges are fun as you race to find a creative solution to that one problem or scavenge through the Internet trying to find if someone solved a similar problem before. Due to the interesting features and problems that are added, CTFs never get stale and help you learn new things about the cybersecurity field.
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Unpacking dictionary keys into tuple

26 Aug, 2019
In certain cases, we might come in a problem in which we require to unpack dictionary keys to tuples. This kind of problem can occur in cases we are just concerned of keys of dictionaries and wish to have a tuple of it. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple()
The simple type casting of dictionary into a tuple in fact does the required task. This function takes just the keys and converts them into key tuple as required.
# Python3 code to demonstrate working of# Unpacking dictionary keys into tuple# Using tuple()  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using tuple()# Unpacking dictionary keys into tupleres = tuple(test_dict)  # printing resultprint("The unpacked dict. keys into tuple is :  " + str(res))
The original dictionary is : {'best': 3, 'is': 2, 'Gfg': 1}
The unpacked dict. keys into tuple is :  ('best', 'is', 'Gfg')

 
Method #2 : Using "=" operator and multiple variablesThis method can also be used to perform this particular task. In this, we assign the comma separated variables to the dictionary. We use as many variables as keys in dictionary. This method is not recommended in case of unknown or many keys.
# Python3 code to demonstrate working of# Unpacking dictionary keys into tuple# Using "=" operator and multiple variables  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using "=" operator and multiple variables# Unpacking dictionary keys into tuplea, b, c = test_dictres = a, b, c  # printing resultprint("The unpacked dict. keys into tuple is :  " + str(res))
The original dictionary is : {'best': 3, 'is': 2, 'Gfg': 1}
The unpacked dict. keys into tuple is :  ('best', 'is', 'Gfg')

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find the most occurring character and its count

12 Jul, 2022
Given a string, write a python program to find the most occurrence character and its number of occurrences. Examples:
Input : hello
Output : ('l', 2)

Input : geeksforgeeks
Output : ('e', 4)
We can solve this problem quickly in python using Counter() method. Simple Approach is to 1) Create a dictionary using Counter method having strings as keys and their frequencies as values. 2) Find the maximum occurrence of a character i.e. value and get the index of it. 
Python
# Python program to find the most occurring# character and its countfrom collections import Counter  def find_most_occ_char(input):      # now create dictionary using counter method    # which will have strings as key and their     # frequencies as value    wc = Counter(input)      # Finding maximum occurrence of a character         # and get the index of it.    s = max(wc.values())    i = wc.values().index(s)          print wc.items()[i]  # Driver programif __name__ == "__main__":    input = 'geeksforgeeks'    find_most_occ_char(input)
Output:
('e', 4)
Time Complexity: O(N) where N is the length of the input string
Auxiliary Space: O(1)
One more approach to find the most occurring character and its count in python3
Python3
# python code to find most occurring character in a string and its countstring1="geeksforgeeks"list1=[]list2=[]for i in string1:  if i not in list1:    list1.append(i)#appending unique characters of string    list2.append(string1.count(i))#finding maximum in the listocc=max(list2)ele=list1[list2.index(occ)]print(ele,occ)     
e 4
Time Complexity: O(N)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
kogantibhavya
simmytarika5
ishankhandelwals
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check foreach Loop Key Value in PHP ?

10 May, 2021
In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as
To loop through a list of simple values.To loop through a list of key-value pairs.
To loop through a list of simple values.
To loop through a list of key-value pairs.
Using the foreach loop with simple values:
We can use the foreach loop to access and use the elements in an array of simple values, such as strings or numbers.
Example 1:
PHP
<?php    $names = array("Ramesh", "Suresh", "Ram", "Shyam");    foreach ($names as $value) {    echo "$value <br>";    }?>
Output:
Ramesh
Suresh
Ram
Shyam
In the above example, each element of the array names is iterated over and is assigned to the variable value.
Example 2:
PHP
<?php    $marks = array(45, 78, 93, 69);    foreach ($marks as $value) {      echo "$value <br>";    }?>
Output:
45
78
93
69
Using the foreach loop with Key-Value pairs:
We will use the same foreach loop to iterate over an array of key-value pairs.
Example 3: In this case, an array of students and their marks are taken in the array.
PHP
<?php    $markSheet = array("Ramesh"=>45, "Suresh"=>78, "Ram"=>93, "Shyam"=>69);    foreach ($markSheet as $key => $val) {      echo "$key - $val<br>";    }?>
Output:
Ramesh - 45
Suresh - 78
Ram - 93
Shyam - 69
In the example above, we iterate over each array element and then extract the key-value pair into variables key and val respectively.
PHP-function
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to test if a string contains specific words in Java?

The java.lang.String.contains() method returns true if and only if this string contains the specified sequence of char values.
Live Demo
public class Sample {
   public static void main(String args[]){
      String str = "Hello how are you welcome to tutorialspoint";
      String test = "tutorialspoint";
      Boolean bool = str.contains(test);
      System.out.println(bool);
   }
}
true