code-rag-bench/online-tutorials huggingface dataset:
numpy.sinh() in Python

04 Dec, 2020
The numpy.sinh() is a mathematical function that helps user to calculate hyperbolic sine for all x(being the array elements).
Equivalent to 1/2 * (np.exp(x) – np.exp(-x)) or -1j * np.sin(1j*x).
Syntax: numpy.sinh(x[, out]) = ufunc ‘sin’)Parameters :
array : [array_like] elements are in radians.2pi Radians = 36o degrees
Return : An array with hyperbolic sine of x for all x i.e. array elements
 Code #1 : Working
# Python3 program explaining# sinh() function  import numpy as npimport math  in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array)  Sinh_Values = np.sinh(in_array)print ("\nSine Hyperbolic values : \n", Sinh_Values)
Output :
Input array : 
 [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Sine Hyperbolic values : 
 [  0.           2.3012989    1.24936705  11.54873936]

 Code #2 : Graphical representation
# Python program showing Graphical# representation of sinh() functionimport numpy as npimport matplotlib.pyplot as plt  in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.sinh(in_array)  print("in_array : ", in_array)print("\nout_array : ", out_array)  # red for numpy.sinh()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.sinh()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output :
in_array :  [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798   -0.28559933
  0.28559933  0.856798    1.42799666  1.99919533  2.57039399  3.14159265]

out_array :  [-11.54873936  -6.49723393  -3.62383424  -1.9652737   -0.96554336
  -0.28949778   0.28949778   0.96554336   1.9652737    3.62383424
   6.49723393  11.54873936]
 References :https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sinh.html#numpy.sinh.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Matplotlib.pyplot.contourf() in Python

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The contourf() function in pyplot module of matplotlib library is used to plot contours. But contourf draw filled contours, while contourf draws contour lines.
Syntax: matplotlib.pyplot.contourf(\*args, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
X, Y: These parameter are the coordinates of the values in Z.
Z : This parameter is the height values over which the contour is drawn.
levels : This parameter is used to determine the numbers and positions of the contour lines / regions.
Returns: This returns the following:
c :This returns the QuadContourSet.
Below examples illustrate the matplotlib.pyplot.contourf() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom numpy import mafrom matplotlib import ticker, cm   N = 1000x = np.linspace(-6.0, 6.0, N)y = np.linspace(-7.0, 7.0, N)X, Y = np.meshgrid(x, y)   Z1 = np.exp(X * Y)z = 50 * Z1z[:5, :5] = -1z = ma.masked_where(z <= 0, z)   cs = plt.contourf(X, Y, z,                  locator = ticker.LogLocator(),                  cmap ="bone")  cbar = plt.colorbar(cs)  plt.title('matplotlib.pyplot.contourf() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np   # invent some numbers, turning # the x and y arrays into simple# 2d arrays, which make combining # them together easier.x = np.linspace(-3, 15, 50).reshape(1, -1)y = np.linspace(-3, 15, 20).reshape(-1, 1)z = np.cos(x)*2 - np.sin(y)*2  # we no longer need x and y to# be 2 dimensional, so flatten them.x, y = x.flatten(), y.flatten()   cs = plt.contourf(x, y, z,                   hatches =['-', '/',                            '\\', '//'],                  cmap ='Greens',                  extend ='both',                  alpha = 1)  plt.colorbar(cs)  plt.title('matplotlib.pyplot.contourf() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Program to find minimum number of bricks required to make k towers of same height in Python

Suppose we have a list of tower heights, and a positive value k. We want to select k towers and make them all the same height by adding more bricks, but using as few bricks as possible. We have to find the minimum number of bricks are needed to pick k towers and make them the same height.
So, if the input is like heights = [4, 7, 31, 14, 40] k = 3, then the output will be 17, as we can select 5, 8, and 15 which requires 17 bricks to make the same height.
To solve this, we will follow these steps −
sort the list heights
ans := infinity
s := 0
for each index i and value x in heights, dos := s + xif i >= k, thens := s - heights[i - k]if i >= k - 1, thenans := minimum of ans and (x * k - s)
s := s + x
if i >= k, thens := s - heights[i - k]
s := s - heights[i - k]
if i >= k - 1, thenans := minimum of ans and (x * k - s)
ans := minimum of ans and (x * k - s)
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, heights, k): heights.sort()
      ans = float("inf")
      s = 0
      for i, x in enumerate(heights):
         s += x
         if i >= k:
            s -= heights[i - k]
         if i >= k - 1:
            ans = min(ans, x * k - s)
      return ans
ob = Solution()
heights = [5, 8, 32, 15, 41]
k = 3
print(ob.solve(heights, k))
[5, 8, 32, 15, 41], 3
17
How to execute TypeScript file using command line?

05 Feb, 2020
TypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows JavaScript syntactically but adds more features to it. It is a superset of JavaScript. In order to execute or run any typescript file, first you need to install node and using it install typescript globally in your local system.
To check node is installed, run command if not you have to installed it first:node -v
node -v
Now to install typescript, use:npm install -g typescript
npm install -g typescript
After installing typescript, create a .ts file, for example, greet.ts as given below:
Example:var greet: string = "Greetings"; var geeks: string = "GeeksforGeeks"; console.log(greet + " from " + geeks); // save the file as hello.ts 
var greet: string = "Greetings"; var geeks: string = "GeeksforGeeks"; console.log(greet + " from " + geeks); // save the file as hello.ts 
Output:Greetings from GeeksforGeeks
Greetings from GeeksforGeeks
Procedure 1: This typescript file greet.ts will create a javascript file at runtime with the same name. To run any typescript file there are a few ways:Syntax:
Step 1: First, run the typescript file with the following command. This will create a javascript file from typescript automatically with the same name.tsc helloWorld.ts
tsc helloWorld.ts
Step 2:Now run the javascript file, the greet.ts file will get executed:node helloWorld.js
node helloWorld.js
Procedure 2: You can merge both the commands by using a pole | and && like below :Syntax:
In Windows:tsc greet.ts | node greet.js
tsc greet.ts | node greet.js
In Linux or MacOS:tsc helloWorld.ts && node helloWorld.js
tsc helloWorld.ts && node helloWorld.js
Procedure 3: You can also install ts-node along with typescript using the following command:
Syntax:
To install:npm install -g ts-node
npm install -g ts-node
To run:ts-node helloWorld.ts
ts-node helloWorld.ts
Output: Using any of the three ways, the output will remain the same.
Greetings from GeeksforGeeks
Picked
TypeScript
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
Differences between Functional Components and Class Components in React
How to set the current working directory in Python?

You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to.
>>> import os
>>> os.chdir('my_folder')
How to convert JSON data into a Python object?

The following code converts a json object(string) into a python object(dictionary). We import the json module and use the json.loads() method to do this.
import json
json_string = '{"name":"Sonali", "age": 21, "designation":" Software developer"}'
print type (json_string)
def func(strng):
    a =json.loads(strng)
    print type(a)
    print a
func(json_string)
<type 'str'>
<type 'dict'>
{u'age': 21, u'name': u'Sonali', u'designation': u'Software developer'}
How do you sort an array in C# in ascending order?

Firstly, set the unsorted array.
int[] list = {98, 23, 97, 36, 77};
Sort the array using the Sort() method.
Array.Sort(list);
You can try to run the following code to to sort an array in ascending order.
 Live Demo
using System;
namespace Demo {
   public class MyApplication {
      public static void Main(string[] args) {
         int[] list = {98, 23, 97, 36, 77};
         Console.WriteLine("Original Unsorted List");
         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Array.Sort(list);
         Console.WriteLine("\nSorted List");
         for(int i=0; i<list.Length; i++) {
            Console.Write(list[i] + " ");
         }
      }
   }
}
Original Unsorted List
98 23 97 36 77
Sorted List
23 36 77 97 98
What is the scope of an internal variable of a class in C#?

Internal variable is set using the internal access specifier.
internal double length;
internal double width;
Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
 Live Demo
using System;
namespace RectangleApplication {
   class Rectangle {
      //member variables
      internal double length;
      internal double width;
      double GetArea() {
         return length * width;
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   } //end class Rectangle
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.length = 4.5;
         r.width = 3.5;
         r.Display();
         Console.ReadLine();
      }
   }
}
Length: 4.5
Width: 3.5
Area: 15.75
Binary Tree Preorder Traversal in Python

Suppose we have a binary tree. We have to return the preorder traversal of that tree. So if the tree is like −
Then the preorder traversal will be: [3,9,20,15,7]
To solve this, we will follow these steps −
make empty lists called res and st.
node := root
while node or st is not emptywhile node is not null, theninsert val of node into res, insert node into st and set node := left of nodetemp := last element of st, and delete last element of stif right of temp is available, thennode := right of temp
while node is not null, theninsert val of node into res, insert node into st and set node := left of node
insert val of node into res, insert node into st and set node := left of node
temp := last element of st, and delete last element of st
if right of temp is available, thennode := right of temp
node := right of temp
return res
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         temp.left = TreeNode(data)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         temp.right = TreeNode(data)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
   insert(Tree, element)
   return Tree
class Solution(object):
   def preorderTraversal(self, root):
      res = []
      st = []
      node = root
      while node or st:
         while node:
            if node.data != None:
               res.append(node.data)
            st.append(node)
            node = node.left
         temp = st[-1]
         st.pop()
         if temp.right:
            node = temp.right
   return res
ob1 = Solution()
head = make_tree([3,9,20,None,None,15,7])
print(ob1.preorderTraversal(head))
[3,9,20,null,null,15,7]
[3, 9, 20, 15, 7]
How to use internal CSS (Style Sheet) in HTML?

CSS can be used in various ways in HTML. One of them is by using Internal CSS i.e. using a <style> tag. The <style> tag is used in the <head>...</head> tag. It defines CSS style for a single page.
You can try to run the following code to use internal CSS in HTML −
<!DOCTYPE html>
<html>
   <head>
      <style>
         h1 {color: red;}
         p {font-size: 12px;}
      </style>
   </head>
   
   <body>
      <h1>Tutorials</h1>
      <p>We provide free tutorials for engineers and professional.</p>
   </body>
</html>
Bitwise Right Shift Operators in Java - GeeksforGeeks

24 Dec, 2021
In C/C++ there is only one right shift operator ‘>>’ which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators.
Here we will be discussing both of right shift operators as listed:
Signed right shift “>>”
Unsigned right shift “>>>”
In Java, the operator ‘>>’ is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (leftmost bit) to fill the trailing positions after the shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if the binary representation of a number is 10....100, then right shifting it by 2 using >> will make it 11.......1.
Example:
Java
// Java Program to Illustrate Signed Right Shift Operator // Main classclass GFG {     // Main driver method    public static void main(String args[])    {         int x = -4;        System.out.println(x >> 1);         int y = 4;        System.out.println(y >> 1);    }}
-2
2
In Java, the operator ‘>>>’ denotes unsigned right shift operator and always fill 0 irrespective of the sign of the number.
Example:
Java
// Java Program to Illustrate Unsigned Right Shift Operator // Main classclass GFG {     // main driver method    public static void main(String args[])    {         // x is stored using 32 bit 2's complement form.        // Binary representation of -1 is all 1s (111..1)        int x = -1;         // The value of 'x>>>29' is 00...0111        System.out.println(x >>> 29);         // The value of 'x>>>30' is 00...0011        System.out.println(x >>> 30);         // The value of 'x>>>31' is 00...0001        System.out.println(x >>> 31);    }}
7
3
1
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nagen010
solankimayank
Java-Operators
Bit Magic
Java
Java-Operators
Bit Magic
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Program to find whether a given number is power of 2
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
VBA - Hour Function

The Hour Function returns a number between 0 and 23 that represents the hour of the day for the specified time stamp.
Hour(time) 

Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox("Line 1: " & Hour("3:13:45 PM"))
   msgbox("Line 2: " & Hour("23:13:45"))
   msgbox("Line 3: " & Hour("2:20 PM"))
End Sub
When you execute the above function, it produces the following output.
Line 1: 15
Line 2: 23
Line 3: 14 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to check if a string contains a certain word in C#?

Use the Contains() method to check if a string contains a word or not.
Set the string −
string s = "Together we can do so much!";
Now let’s say you need to find the word “much”
if (s.Contains("much") == true) {
   Console.WriteLine("Word found!");
}
Let us see the complete code −
 Live Demo
using System;

public class Demo {
   public static void Main() {
      string s = "Together we can do so much!";
      if (s.Contains("much") == true) {
         Console.WriteLine("Word found!");
      } else {
         Console.WriteLine("Word not found!");
      }
   }
}
Word found!
How to initialize a string to an empty string in C#?

To initialize a string to an empty list −
string myStr = null;
Now, use the built-in method IsNullOrEmpty() to check whether the list is empty or not −
if (string.IsNullOrEmpty(myStr)) {
   Console.WriteLine("String is empty or null!");
}
Let us see the complete code −
 Live Demo
using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string myStr = null;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         }
         Console.ReadKey();
      }
   }
}
String is empty or null!
Another way to initialize a string to an empty string, try the following code. Here, we have used string.Empty −
 Live Demo
using System;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         string myStr = string.Empty;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         } else {
            Console.WriteLine("String isn't empty or null!");
         }
      }
   }
}
String is empty or null!
Domino and Tromino Tiling in C++

Suppose we have two types of shapes, Domino and Tromino. They can be rotated like below −
In a tiling, every square must be covered by a tile. Here two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Given N, then we have to find in how many ways we can tile 2xN board? So if the input is 3, then the output will be 5. So the arrangements can be [XYZ XXZ XYY XXY XYY] and [XYZ YYZ XZZ XYY XXY], here different letters are used for different tiles.
To solve this, we will follow these steps −
Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5
Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5
for i in range 4 to Ndp[i] := 2*dp[i – 1] + dp[i – 3]
for i in range 4 to N
dp[i] := 2*dp[i – 1] + dp[i – 3]
dp[i] := 2*dp[i – 1] + dp[i – 3]
return dp[N]
return dp[N]
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int add(int a, int b){
   return ((a % MOD) + (b % MOD)) % MOD;
}
class Solution {
   public:
   int numTilings(int N) {
      vector <int> dp(N + 5);
      dp[1] = 1;
      dp[2] = 2;
      dp[3] = 5;
      for(int i = 4; i <= N; i++){
         dp[i] = add(2 * dp[i - 1], dp[i - 3]);
      }
      return dp[N];
   }
};
main(){
   Solution ob;
   cout << (ob.numTilings(3));
}
3
5
Hacking RSA Cipher

Hacking RSA cipher is possible with small prime numbers, but it is considered impossible if it is used with large numbers. The reasons which specify why it is difficult to hack RSA cipher are as follows −
Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time.
Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time.
Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it.
Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it.
Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters.
Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters.
There are no specific mathematical tricks to hack RSA cipher.
There are no specific mathematical tricks to hack RSA cipher.
The RSA decryption equation is −
M = C^d mod n

With the help of small prime numbers, we can try hacking RSA cipher and the sample code for the same is mentioned below −
def p_and_q(n):
   data = []
   for i in range(2, n):
      if n % i == 0:
         data.append(i)
   return tuple(data)

def euler(p, q):
   return (p - 1) * (q - 1)

def private_index(e, euler_v):
   for i in range(2, euler_v):
      if i * e % euler_v == 1:
         return i

def decipher(d, n, c):
   return c ** d % n
	def main():
      e = int(input("input e: "))
      n = int(input("input n: "))
      c = int(input("input c: "))
      
      # t = 123
      # private key = (103, 143)
      p_and_q_v = p_and_q(n)
      # print("[p_and_q]: ", p_and_q_v)
      euler_v = euler(p_and_q_v[0], p_and_q_v[1])
      
      # print("[euler]: ", euler_v)
      d = private_index(e, euler_v)
      plain = decipher(d, n, c)
      print("plain: ", plain)
if __name__ == "__main__":
   main()
The above code produces the following output −

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to use prepared statement for select query in Java with MySQL?

You need to use executeQuery() for this. The syntax is as follows −
yourPreparedStatementObject=yourConnectionObject.prepareStatement(yourQueryName);
yourresultSetObject=yourPreparedStatementObject.executeQuery();
Create a table in the database ‘sample’. The query to create a table is as follows −
mysql> create table JavaPreparedStatement
   -> (
   -> Id int,
   -> Name varchar(10),
   -> Age int
   -> );
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into JavaPreparedStatement values(1,'Larry',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into JavaPreparedStatement values(2,'Sam',25);
Query OK, 1 row affected (0.21 sec)
mysql> insert into JavaPreparedStatement values(3,'Mike',26);
Query OK, 1 row affected (0.12 sec)
Now you can display all records of the table using Java PreparedStatement. You need to use the executeQuery() method.
Here is the Java code −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatementSelectQueryDemo {
   public static void main(String[] args) {
      String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
      String Username = "root";
      String password = "123456";
      Connection con = null;
      PreparedStatement pstmt = null;
      ResultSet rst = null;
      String myQuery = "select Id,Name,Age from JavaPreparedStatement";
      try {
         con = DriverManager.getConnection(JdbcURL, Username, password);
         pstmt = con.prepareStatement(myQuery);
         rst = pstmt.executeQuery();
         System.out.println("Id\t\tName\t\tAge\n");
         while(rst.next()) {
            System.out.print(rst.getInt(1));
            System.out.print("\t\t"+rst.getString(2));
            System.out.print("\t\t"+rst.getInt(3));
            System.out.println();
         }
      } catch(Exception exec) {
         exec.printStackTrace();
      }
   }
}
Here is the snapshot of Java code −
Here is the snapshot of sample output −
C++ Program to Find Largest Number Among Three Numbers

The largest number among three numbers can be found using if statement multiple times. This is given in a program as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a = 5 ,b = 1 ,c = 9;
   if(a>b) {
      if(a>c)
      cout<<a<<" is largest number";
      else
      cout<<c<<" is largest number";
   }else {
      if(b>c)
      cout<<b<<" is largest number";
      else
      cout<<c<<" is largest number";
   }
   return 0;
}
9 is largest number
In the above program, firstly, a is compared to b. If a is greater than b, then it is compared to c. If it is greater than c as well, that means a is the largest number and if not, then c is the largest number.
if(a>b) {
   if(a>c)
   cout<<a<<" is largest number";
   else
   cout<<c<<" is largest number";
}
If a is not greater than b, that means b is greater than a. Then b is compared to c. If it is greater than c, that means b is the largest number and if not, then c is the largest number.
else {
   if(b>c)
   cout<<b<<" is largest number";
   else
   cout<<c<<" is largest number";
}
Count frequencies of all elements in array in Python


In this tutorial, we are going to write a program that finds the frequency of all the elements in an array. We can find it in different ways let's explore two of them.
Initialize the array.
Initialize the array.
Initialize an empty dict.
Initialize an empty dict.
Iterate over the list.If the element is not in dict, then set the value to 1.Else increment the value by 1.
Iterate over the list.
If the element is not in dict, then set the value to 1.
If the element is not in dict, then set the value to 1.
Else increment the value by 1.
Else increment the value by 1.
Print the element and frequencies by iterating over the dict.
Print the element and frequencies by iterating over the dict.
Let's see the code.
# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
   # checking whether it is in the dict or not
   if element in elements_count:
      # incerementing the count by 1
      elements_count[element] += 1
   else:
      # setting the count to 1
      elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
   print(f"{key}: {value}")
If you run the above program, you will get the following results.
1: 3
2: 4
3: 5
Let's see the second approach using Counter class of the collections module.
Import the collections module.
Import the collections module.
Initialize the array.
Initialize the array.
Pass the list to the Counter class. And store the result in a variable.
Pass the list to the Counter class. And store the result in a variable.
Print the element and the frequencies by iterating over the result.
Print the element and the frequencies by iterating over the result.
See the code below.
# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
   print(f"{key}: {value}")
If you run the above code, you will get the same output as previous one.
1: 3
2: 4
3: 5
If you have any doubts in the tutorial, mention them in the comment section.
Concat Method in C#

To concat lists in C#, ue the Concat method.
The following is the list −
var list1 = new List<int>{12, 40};
var list2 = new List<int>{98, 122, 199, 230};
Here is the Concat method −
var res = list1.Concat(list2);
The following is the example to work with Concat method −
 Live Demo
using System.Collections.Generic;
using System.Linq;
using System;

public class Demo {
   public static void Main() {

      // two lists
      var list1 = new List<int>{12, 40};
      var list2 = new List<int>{98, 122, 199, 230};
   
      // concat
      var res = list1.Concat(list2);

      foreach(int i in res) {
         Console.WriteLine(i);
      }
   }
}
12
40
98
122
199
230
Scala Set map() method with example - GeeksforGeeks

18 Oct, 2019
The map() method is utilized to build a new set by applying a function to all elements of this set.
Method Definition: def map[B](f: (A) => B): immutable.Set[B]
Return Type: It returns a new set containing all the elements after applying the given function.
Example #1:
// Scala program of map() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(5, 1, 3, 2, 4)                   // Applying map method         val result = s1.map(x => x*x)                  // Display output        println(result)    } } 
Set(25, 1, 9, 16, 4)

Example #2:
// Scala program of map() // method   // Creating object object GfG {       // Main method     def main(args:Array[String])     {         // Creating a set         val s1 = Set(5, 1, 3, 2, 4)                   // Applying map method         val result = s1.map(x => x/2)                  // Display output        println(result)    } } 
Set(2, 0, 1)

Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Hello World in Scala
Operators in Scala
Class and Object in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
How to get the first element of List in Scala
Break statement in Scala
How to declare a global variable in Python?

A global variable is a variable that is declared outside the function but we need to use it inside the function.
 Live Demo
def func():
   print(a)
a=10
func()
10
Here, variable a is global. As it is declared outside the function and can be used inside the function as well. Hence the scope of variable a is global.
We will see what happens if we create a variable of same name as global variable inside the function.
In the above example, the variable a is declared outside the function and hence is global.
If we declare another variable with same name inside the function with some another value. That variable will act as the local variable of the function and its scope will be limited to inside the function. Outside the function, the global variable will hold its original value.
It can be better understood with the help of an example.
 Live Demo
a=10
def func():
   a=5
print("Inside function:",a)
func()
print("Outside function:",a)
Inside function: 5
Outside function: 10
In the above example, a is global variable whose value is 10. Later the func() is called.
Inside func(), another variable a is declared with different value whose scope is only limited to inside the function. Hence, when value of a is printed outside the function later, it carries the same original value as global variable which 10.
The keyword global is used when you need to declare a global variable inside a function.
The scope of normal variable declared inside the function is only till the end of the function.
However, if you want to use the variable outside of the function as well, use global keyword while declaring the variable.
Understand the difference between both with the help of example implementations.
def func():
   a=5
   print("Inside function:",a)
func()
print("Outside function:",a)
Inside function: 5
Traceback (most recent call last):
print("Outside function:",a)
NameError: name 'a' is not defined
In the above example, the value of a cannot be accessed outside the function, since it is a local variable. Thus, accessing the value of an outside function throws an exception.
The exception raised in the above example can be resolved if we declare variable a using keyword global.
 Live Demo
def func():
   global a
   a=5
   print("Inside function:",a)
func()
print("Outside function:",a)
Inside function: 5
Outside function: 5
In the above example, the variable a is global and hence its value can be accessed outside the function as well.
Shifting Letters in C++

Suppose we have a string S of lowercase letters, and an integer array shifts. The shift of a letter means the next letter in the alphabet, for z, it will be a. Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times. We have to find the final string after all such shifts to S are applied. So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer.
To solve this, we will follow these steps −
for i in range size of shift array – 2 down to 0shift[i] := shift[i] + shift[i + 1]shift[i] := shift[i] mod 26
shift[i] := shift[i] + shift[i + 1]
shift[i] := shift[i] mod 26
for i in range 0 to size of S – 1S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a
S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a
return S
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string shiftingLetters(string S, vector<int>& shifts) {
      for(int i = shifts.size() - 2 ;i >=0; i--){
         shifts[i] += shifts[i + 1];
         shifts[i] %= 26;
      }
      for(int i = 0; i < S.size(); i++) {
         S[i] = ( ((S[i] - 'a') + shifts[i]) % 26 + 'a');
      }
      return S;
   }
};
main(){
   vector<int> v = {3,5,9};
   Solution ob;
   cout << (ob.shiftingLetters("abc", v));
}
"abc"
[3,5,9]
rpl
Algorithms | Graph Shortest Paths | Question 8 - GeeksforGeeks

28 Jun, 2021
In a weighted graph, assume that the shortest path from a source ‘s’ to a destination ‘t’ is correctly calculated using a shortest path algorithm. Is the following statement true?If we increase weight of every edge by 1, the shortest path always remains same.(A) Yes(B) NoAnswer: (B)Explanation: See the following counterexample.
There are 4 edges s-a, a-b, b-t and s-t of wights 1, 1, 1 and 4 respectively. The shortest path from s to t is s-a, a-b, b-t. IF we increase weight of every edge by 1, the shortest path changes to s-t.

   1      1     1
s-----a-----b-----t
 \              /
   \          /
     \______/
        4
Quiz of this Question
Algorithms-Graph Shortest Paths Quiz
Graph Shortest Paths Quiz
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 8
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Sorting | Question 9
GATE | GATE MOCK 2017 | Question 23
Algorithms | Sorting | Question 5
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Sorting | Question 6
Explain Polymorphism in PHP.

To begin with, Polymorphism is gotten from the Greek words Poly (which means many) and morphism (which meaning forms).
Polymorphism portrays an example in object-oriented programming where methods in various classes that do similar things should have a similar name. Polymorphism is essentially an OOP pattern that enables numerous classes with different functionalities to execute or share a commonInterface. The usefulness of polymorphism is code written in different classes doesn't have any effect which class it belongs because they are used in the same way. In order to ensure that the classes do implement the polymorphism guideline, we can pick between one of the two alternatives of either abstract classes or interfaces.
So let's implement the polymorphism principle with the help of the interface.
Interface An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes executing an interface must execute all methods characterized by the interface.
<?php
   interface Machine {
      public function calcTask();
   }
   class Circle implements Machine {
      private $radius;
      public function __construct($radius){
         $this -> radius = $radius;
      }
      public function calcTask(){
         return $this -> radius * $this -> radius * pi();
      }
   }
   class Rectangle implements Machine {
      private $width;
      private $height;
      public function __construct($width, $height){
         $this -> width = $width;
         $this -> height = $height;
      }
      public function calcTask(){
         return $this -> width * $this -> height;
      }
   }
   $mycirc = new Circle(3);
   $myrect = new Rectangle(3,4);
   echo $mycirc->calcTask();
   echo $myrect->calcTask();
?>
28.274
12
The interface with the name of " Machine" commits all the classes that implement it to define an abstract method with the name of calcTask(). In accordance, the Circle class implements the interface by defining the callTask() method with the respective body inside it. The rectangle class also implements the Machine interface but defines the method calcTask() with a different body that differs from the circle class CalTask() method. The polymorphism guideline says that, for this situation, all the methods that calculate the task would have the equivalent name. Now, at whatever point we would need to compute the Task for the different Classes, we would call a method with the name of calcTask() without giving a lot of consideration to the details of how to actually calculate the Task for the different Machine. The main thing that we would need to know is the name of the method that calculates the Task.
How to get a horizontal scrollbar in Tkinter?

The Scrollbar widget in tkinter is one of the useful widgets that is used to pack the container elements and their contents with a scrollbar. With Scrollbars, we can view large sets of data very efficiently.
Generally, Tkinter allows to add vertical and horizontal scrollbars. To add a horizontal scrollbar in an application, we've to use the orientation as Horizontal in the scrollbar constructor.
Let us create a text editor that contains a horizontal scrollbar in it.
# Import the required library
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

# Create an instance of tkinter frame
win=Tk()

# Set the geometry
win.geometry("700x350")

# Add a Scrollbar(horizontal)
h=Scrollbar(win, orient='horizontal')
h.pack(side=BOTTOM, fill='x')

# Add a text widget
text=Text(win, font=("Calibri, 16"), wrap=NONE, xscrollcommand=h.set)
text.pack()

# Add some text in the text widget
for i in range(5):
   text.insert(END, "Welcome to Tutorialspoint...")

# Attach the scrollbar with the text widget
h.config(command=text.xview)

win.mainloop()
If we run the above code, it will display a text editor that will have some text in it. The text widget is packed with a horizontal scrollbar which gets visible whenever the text overflows.
GATE | GATE-CS-2004 | Question 63

25 Oct, 2018
Direction for questions 63 to 64:Consider the following program segment for a hypothetical CPU having three user registers R1, R2 and R3.
 Instruction      Operation      Instruction Size(in words)
 MOV R1,5000;      R1 ¬ Memory[5000]      2
 MOV R2, (R1);      R2 ¬ Memory[(R1)]      1
 ADD R2, R3;      R2 ¬ R2 + R3              1
 MOV 6000, R2;      Memory [6000] ¬ R2      2
 HALT              Machine halts              1 
Consider that the memory is byte addressable with size 32 bits, and the program has been loaded starting from memory location 1000 (decimal). If an interrupt occurs while the CPU has been halted after executing the HALT instruction, the return address (in decimal) saved in the stack will be(A) 1007(B) 1020(C) 1024(D) 1028Answer: (D)Explanation: Instructions size are given in words. So first instruction will take 2 words i.e 8 bytes(as 32 bit byte addressable, word size will be 32 bit ) so on for 2nd instruction 4 byte, for 3rd 4 bytes, 4th 8 bytes..5th 4 bytes. As 1st instruction starts from 1000 and the size is 8 bytes second instruction address will be 1008, like wise 3rd instruction address will be 1012,4th instruction address 1016,5th instruction address 1024 and halt instruction address will be 1028. As an interrupt occurs executing the HALT instruction, the return address (in decimal) saved in the stack will be the address of the halt instruction ..so answer is 1028.Note – If interrupt occur, then value of PC will be return address of that instruction after HALT.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
sector() function in C

06 Dec, 2019
The header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector.Syntax :
void sector(int x, int y, int s_angle, 
           int e_angle, int x_radius, 
                        int y_radius);

where,
(x, y) is center of the sector.
(s_angle, e_angle) are starting 
and ending angles.
(x_radius, y_radius) are x and y
radius of sector.

Examples :
Input : x = 200, y = 200, s_angle = 0,
         e_angle = 150, x_radius = 50, 
         y_radius = 65
Output : 

Input : x = 200, y = 200, s_angle = 30, 
        e_angle = 120, x_radius = 90, 
        y_radius = 85 
Output : 

Below is the implementation of sector() function :
// C Implementation for sector()#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // sector function    sector(200, 200, 0, 150, 50, 65);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


Akanksha_Rai
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
WPF - Togglebutton

A Toggle Button is a control that can switch states, such as CheckBox and RadioButton. The hierarchical inheritance of ToggleButton class is as follows −
IsChecked
Gets or sets whether the ToggleButton is checked.
IsCheckedProperty
Identifies the IsChecked dependency property.
IsThreeState
Gets or sets a value that indicates whether the control supports three states.
IsThreeStateProperty
Identifies the IsThreeState dependency property.
Checked
Fires when a ToggleButton is checked.
Indeterminate
Fires when the state of a ToggleButton is switched to the indeterminate state.
Unchecked
Occurs when a ToggleButton is unchecked.
Let’s create a new WPF project with WPFToggleButtonControl.
Drag a text block and a toggle button from the toolbox.
Change the background color of the text block from the properties window.
The following example shows the usage of ToggleButton in an XAML application. 
The following XAML code creates a ToggleButton and initializes it with some properties.
<Window x:Class = "WPFToggleButtonControl.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFToggleButtonControl" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <ToggleButton x:Name = "tb" Content = "Toggle"  
         Checked = "HandleCheck" Unchecked = "HandleUnchecked"Margin = "20"
         Width = "108"HorizontalAlignment = "Center" /> 
      <TextBlock x:Name = "text2" Margin = "20" Width = "300" 
         HorizontalAlignment = "Center" FontSize = "24" Background = "#FFFDE0E0" />
   </StackPanel> 
	
</Window> 
Here is the C# implementation of Checked and Unchecked events.
using System.Windows;  

namespace WPFToggleButtonControl { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
	
   public partial class MainWindow : Window {
	
      public MainWindow() { 
         InitializeComponent(); 
      } 
		
      private void HandleCheck(object sender, RoutedEventArgs e) { 
         text2.Text = "Button is Checked"; 
      }  
		
      private void HandleUnchecked(object sender, RoutedEventArgs e) { 
         text2.Text = "Button is unchecked."; 
      }  
		
   } 
}
When you compile and execute the above code, it will produce the following window. When you click the button, it will change the color and update the text block.
We recommend that you execute the above example code and try the other properties and events of ToggleButton.