code-rag-bench/online-tutorials huggingface dataset:
MySQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or 
descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the 
DESC keyword.
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement selects all customers from the "Customers" table, 
sorted by the "Country" column:
The following SQL statement selects all customers from the "Customers" table, 
sorted DESCENDING by the "Country" column:
The following SQL statement selects all customers from the "Customers" table, 
sorted by the "Country" and the "CustomerName" column. This means that it orders 
by Country, but if some rows have the same Country, it orders them by 
CustomerName:
The following SQL statement selects all customers from the "Customers" table, 
sorted ascending by the "Country" and descending by the "CustomerName" column:
Select all records from the Customers table, sort the result alphabetically by the column City.
SELECT * FROM Customers
 ;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to sort a dictionary in Python?

A dictionary is a data structure that consists of key and value pairs. We can sort a dictionary using two criteria −
Sort by key − The dictionary is sorted in ascending order of its keys. The values are not taken care of.
Sort by value − The dictionary is sorted in ascending order of the values.
In this approach, the dictionary is sorted in ascending order of its keys.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{1:100, 2:90, 3:5, 5:67, 8:3}
As shown above, we can see the dictionary is sorted according to its keys.
 Live Demo
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2={}
for i in sorted(dic):
   dic2[i]=dic[i]
print(dic2)
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
Declare a dictionary which is to be sorted
Declare a dictionary which is to be sorted
Declare an empty dictionary where sorted key value pairs are to be added
Declare an empty dictionary where sorted key value pairs are to be added
sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]
sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]
For each key in sorted order, add the key and the corresponding value into dic2.
For each key in sorted order, add the key and the corresponding value into dic2.
dic2 has all the key-value pairs in sorted order of keys
dic2 has all the key-value pairs in sorted order of keys
In this approach, the dictionary is sorted in ascending order of values.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{8:3, 3:5 ,5:67 , 2:90, 1:100}
As shown above, we can see the dictionary is sorted according to its values.
We use the sorted() and items() methods together to sort the dictionary by value.
We use the sorted() and items() methods together to sort the dictionary by value.
The items() is used to retrieve the items or values of the dictionary.
The items() is used to retrieve the items or values of the dictionary.
The key=lambda x: x[1] is a sorting mechanism that uses a lambda function.
The key=lambda x: x[1] is a sorting mechanism that uses a lambda function.
This gives us key value pairs ehich are then converted into a dictionary using dict().
This gives us key value pairs ehich are then converted into a dictionary using dict().
 Live Demo
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2=dict(sorted(dic.items(),key= lambda x:x[1]))
print(dic2)
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
What is the difference between MySQL TRUNCATE and DELETE command?

As we know that TRUNCATE will remove all the rows without removing table’s structure from the database. Same work can be done with the help of DELETE command on removing all the rows from the table. But there is a significant difference of re-initialization of PRIMARY KEY AUTO_INCREMENT between both the commands.
Suppose a column is defined AUTO_INCREMENT having PRIMARY KEY CONSTRAINT, then on deleting all the rows with DELETE command would not re-initialize the table i.e. on entering the new rows, the AUTO_INCREMENT number will start after the last inserted row. In contrast, on using TRUNCATE, the table will be re-initializing like a newly created table. It means after using TRUNCATE command and on inserting new rows the AUTO_INCREMENT number will start from 1.
Following example will demonstrate the above concept −
mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.15 sec)

mysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Gaurav  |
| 2  | Rahul   |
| 3  | Aarav   |
| 4  | Yashraj |
| 5  | Manak   |
+----+---------+

5 rows in set (0.00 sec)

mysql> Delete from testing where id >=4;
Query OK, 2 rows affected (0.04 sec)

mysql> Select * from testing;

+----+--------+
| Id | Name   |
+----+--------+
| 1  | Gaurav |
| 2  | Rahul  |
| 3  | Aarav  |
+----+--------+

3 rows in set (0.00 sec)

mysql> Insert into testing(Name) values('Harshit'),('Lovkesh');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Gaurav  |
| 2  | Rahul   |
| 3  | Aarav   |
| 6  | Harshit |
| 7  | Lovkesh |
+----+---------+

5 rows in set (0.00 sec)

mysql> Truncate table testing;
Query OK, 0 rows affected (0.10 sec)

mysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');
Query OK, 4 rows affected (0.11 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+----+---------+
| Id | Name    |
+----+---------+
| 1  | Harshit |
| 2  | Lovkesh |
| 3  | Ram     |
| 4  | Gaurav  |
+----+---------+

4 rows in set (0.00 sec)
What is Bitwise XOR Assignment Operator (^=) in JavaScript?

It performs XOR operation on the right operand with the left operand and assigns the result to the left operand.
You can try to run the following code to learn how to work with Bitwise XOR Assignment Operator
Live Demo
<html>
   <body>
      <script>
         var a = 2;   // Bit presentation 10
         var b = 3;   // Bit presentation 11
         document.write("(a ^= b) => ");
         document.write(a ^= b);
      </script>
   </body>
</html>
bitset none() in C++ STL - GeeksforGeeks

12 Nov, 2020
bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set. 
Syntax:  
bool none() 

Parameter: The function accepts no parameter. 
Return Value: The function returns a boolean. The boolean value is True if none of its bits are set. It is False if at least one bit is set. 
Below programs illustrates the bitset::none() function. 
Program 1:  
C++
// C++ program to illustrate the// bitset::none() function#include <bits/stdc++.h>using namespace std; int main(){     // initialization of bitset    bitset<4> b1(string("1100"));    bitset<6> b2(string("000000"));     // Function to check if none of    // the bits are set or not in b1    bool result1 = b1.none();    if (result1)        cout << b1 << " has no bits set"             << endl;    else        cout << b1 << " has a minimum of one bit set"             << endl;     // Function to check if none of    // the bits are set or not in b1    bool result2 = b2.none();    if (result2)        cout << b2 << " has no bits set"             << endl;    else        cout << b2 << " has a minimum of one bit set"             << endl;     return 0;}
1100 has a minimum of one bit set
000000 has no bits set





 
Program 2:  
C++
// C++ program to illustrate the// bitset::none() function// when the input is a number#include <bits/stdc++.h>using namespace std; int main(){    // initialization of bitset    bitset<3> b1(4);    bitset<6> b2(0);     // Function to check if none of    // the bits are set or not in b1    bool result1 = b1.none();    if (result1)        cout << b1 << " has no bits set"             << endl;    else        cout << b1 << " has a minimum of one bit set"             << endl;     // Function to check if none of    // the bits are set or not in b1    bool result2 = b2.none();    if (result2)        cout << b2 << " has no bits set"             << endl;    else        cout << b2 << " has a minimum of one bit set"             << endl;     return 0;}
100 has a minimum of one bit set
000000 has no bits set





 
arorakashish0911
CPP-bitset
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL)
How to change status bar color to match app Android using Kotlin?

This example demonstrates how to change status bar color to match app Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="50dp"
   android:text="Tutorials Point"
   android:textAlignment="center"
   android:textColor="@android:color/holo_green_dark"
   android:textSize="32sp"
   android:textStyle="bold" />
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:text="Check the Color of the Status Bar"
   android:textAlignment="center"
   android:textColor="@color/colorAccent"
   android:textSize="24sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val window: Window = this@MainActivity.window
      window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
      window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      window.statusBarColor = ContextCompat.getColor(this@MainActivity, R.color.colorAccent)
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
Java Program to place component in bottom-right corner with BorderLayout

We have created a button component here, which will places in bottom-right corner −
JButton button = new JButton("This is Demo Text!");
button.setBackground(Color.blue);
button.setForeground(Color.white);
Create panels now to arrange the above created button component in the bottom right −
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(button, BorderLayout.LINE_END);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
The following is an example to place a component in bottom-right corner with BorderLayout −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JButton button = new JButton("This is Demo Text!");
      button.setBackground(Color.blue);
      button.setForeground(Color.white);
      JPanel bottomPanel = new JPanel(new BorderLayout());
      bottomPanel.add(button, BorderLayout.LINE_END);
      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
      // mainPanel.setPreferredSize(new Dimension(550, 400));
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.setSize(550, 400);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
XSD - Date Time

Date and Time data types are used to represent date and time in the XML documents.
The <xs:date> data type is used to represent date in YYYY-MM-DD format.
YYYY − represents year
YYYY − represents year
MM − represents month
MM − represents month
DD − represents day
DD − represents day
Element declaration in XSD −
<xs:element name = "birthdate" type = "xs:date"/>

Element usage in XML −
<birthdate>1980-03-23</birthdate>

The <xs:time> data type is used to represent time in hh:mm:ss format.
hh − represents hours
hh − represents hours
mm − represents minutes
mm − represents minutes
ss − represents seconds
ss − represents seconds
Element declaration in XSD −
<xs:element name = "startTime" type = "xs:time"/>

Element usage in XML −
<startTime>10:20:15</startTime>

The <xs:datetime> data type is used to represent date and time in YYYY-MM-DDThh:mm:ss format.
YYYY − represents year
YYYY − represents year
MM − represents month
MM − represents month
DD − represents day
DD − represents day
T − represents start of time section
T − represents start of time section
hh − represents hours
hh − represents hours
mm − represents minutes
mm − represents minutes
ss − represents seconds
ss − represents seconds
Element declaration in XSD −
<xs:element name = "startTime" type = "xs:datetime"/>

Element usage in XML −
<startTime>1980-03-23T10:20:15</startTime>

The <xs:duration> data type is used to represent time interval in PnYnMnDTnHnMnS format. Each component is optional except P.
P − represents start of date section
P − represents start of date section
nY − represents year
nY − represents year
nM − represents month
nM − represents month
nD − represents day
nD − represents day
T − represents start of time section
T − represents start of time section
nH − represents hours
nH − represents hours
nM − represents minutes
nM − represents minutes
nS − represents seconds
nS − represents seconds
Element declaration in XSD −
<xs:element name = "period" type = "xs:duration"/>

Element usage in xml to represent period of 6 years, 3 months, 10 days and 15 hours.
<period>P6Y3M10DT15H</period>

Following is the list of commonly used date data types.
date
Represents a date value
dateTime
Represents a date and time value
duration
Represents a time interval
gDay
Represents a part of a date as the day (DD)
gMonth
Represents a part of a date as the month (MM)
gMonthDay
Represents a part of a date as the month and day (MM-DD)
gYear
Represents a part of a date as the year (YYYY)
gYearMonth
Represents a part of a date as the year and month (YYYY-MM)
time
Represents a time value
Following types of restrictions can be used with Date data types −
enumeration
maxExclusive
maxInclusive
minExclusive
minInclusive
pattern
whiteSpace
 Print
 Add Notes
 Bookmark this page
C++ Program to Implement Russian Peasant Multiplication

Russian Peasant algorithm to multiply two numbers. It is a quick algorithm to calculate multiplication of two long numbers.
Begin
   Russianpeasant(num1, num2)
   Int result=0
   while (num2 > 0)
      if (num2 and 1)
         result = result + n;
         num1= num1 left shift 1;
         num2= num2left shift 1;
   return result
End
#include <iostream>
using namespace std;
unsigned int russianPeasant(unsigned int n, unsigned int m) {
   int result = 0;
   while (m > 0) {
      if (m & 1)
         result = result + n;
         n = n << 1;
         m = m >> 1;
   }
   return result;
}
int main() {
   cout << russianPeasant(10, 20) << endl;
   cout << russianPeasant(7, 6) << endl;
   return 0;
}
200
42
Go - Pointer to pointer

A pointer to a pointer is a form of chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following statement declares a pointer to a pointer of type int −
var ptr **int;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown in the following example −
package main

import "fmt"

func main() {
   var a int
   var ptr *int
   var pptr **int

   a = 3000

   /* take the address of var */
   ptr = &a

   /* take the address of ptr using address of operator & */
   pptr = &ptr

   /* take the value using pptr */
   fmt.Printf("Value of a = %d\n", a )
   fmt.Printf("Value available at *ptr = %d\n", *ptr )
   fmt.Printf("Value available at **pptr = %d\n", **pptr)
}
When the above code is compiled and executed, it produces the following result −
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2001 | Question 23 - GeeksforGeeks

28 Jun, 2021
Consider a schema R(A,B,C,D) and functional dependencies A->B and C->D.
Then the decomposition of R into R1(AB) and R2(CD) is(A) dependency preserving and lossless join(B) lossless join but not dependency preserving(C) dependency preserving but not lossless join(D) not dependency preserving and not lossless joinAnswer: (C)Explanation: Dependency Preserving Decomposition:Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of of FDs before decomposition.A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition.
In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D) and there are only two FDs A -> B and C -> D. So, the decomposition is dependency preserving
Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)
    R1 ∩ R2 → R1
   OR
    R1 ∩ R2 → R2

In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D), and R1 ∩ R2 is empty. So, the decomposition is not lossless.
Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2001 | Question 48
Append special characters to column values in MySQL

Let us first create a −
mysql> create table DemoTable1626
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.37 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1626 values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1626 values('Bob');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable1626 values('Robert');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select −
mysql> select * from DemoTable1626;
This will produce the following output −
+--------+
| Name   |
+--------+
| Chris  |
| Bob    |
| Robert |
+--------+
3 rows in set (0.00 sec)
Following is the query to append special characters −
mysql> select rpad(Name,if(length(Name) >= 5,10,7),'*') from DemoTable1626;
This will produce the following output −
+-------------------------------------------+
| rpad(Name,if(length(Name) >= 5,10,7),'*') |
+-------------------------------------------+
| Chris*****                                |
| Bob****                                   |
| Robert****                                |
+-------------------------------------------+
3 rows in set (0.00 sec)
JUnit - Time Test

JUnit provides a handy option of Timeout. If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Let us see the @Test(timeout) in action.
Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE.
Add an infinite while loop inside the printMessage() method.
/*
* This class prints the given message on console.
*/

public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message; 
   }

   // prints the message
   public void printMessage(){
      System.out.println(message);
      while(true);
   }   

   // add "Hi!" to the message
   public String salutationMessage(){
      message = "Hi!" + message;
      System.out.println(message);
      return message;
   }   
}  	
Create a java test class, say, TestJunit.java. Add a timeout of 1000 to testPrintMessage() test case.
Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit {

   String message = "Robert";	
   MessageUtil messageUtil = new MessageUtil(message);
   
   @Test(timeout = 1000)
   public void testPrintMessage() {	
      System.out.println("Inside testPrintMessage()");     
      messageUtil.printMessage();     
   }

   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Robert";
      assertEquals(message,messageUtil.salutationMessage());
   }
}
Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
		
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
}  	
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java

Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner

Verify the output. testPrintMessage() test case will mark the unit testing failed.
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
testPrintMessage(TestJunit): test timed out after 1000 milliseconds
false


    24 Lectures 
     2.5 hours 

 Nishita Bhatt

    56 Lectures 
     7.5 hours 

 Dinesh Varyani
 Print
 Add Notes
 Bookmark this page
Python – tensorflow.math.reduce_max()

14 May, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
reduce_max() is used to find maximum of elements across dimensions of a tensor.
Syntax: tensorflow.math.reduce_max( input_tensor, axis, keepdims, name)
Parameters:
input_tensor: It is numeric tensor to reduce.
axis(optional): It represent the dimensions to  reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced.
keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a) # Printing the resultprint('Result: ', res)
Output:
Input:  tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
Result:  tf.Tensor(4.0, shape=(), dtype=float64)
Example 2:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)
Output:
Input:  tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float64)
Result:  tf.Tensor(
[[2.]
 [4.]], shape=(2, 1), dtype=float64)
surinderdawra388
Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count Occurrences of a Given Character using Regex in Java

15 Nov, 2021
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex.
Examples:
Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.

Input: str = "abccdefgaa", c = 'a' 
Output: 3
'a' appears three times in str.
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. 
Get the String in which it is to be matched
Find all occurrences of the given character using Matcher.find() function (in Java)
For each found occurrence, increment the counter by 1
Below is the implementation of the above approach:
Java
// Java program to count occurrences// of a character using Regex  import java.util.regex.*;  class GFG {      // Method that returns the count of the given    // character in the string    public static long count(String s, char ch)    {          // Use Matcher class of java.util.regex        // to match the character        Matcher matcher            = Pattern.compile(String.valueOf(ch))                  .matcher(s);          int res = 0;          // for every presence of character ch        // increment the counter res by 1        while (matcher.find()) {            res++;        }          return res;    }      // Driver method    public static void main(String args[])    {        String str = "geeksforgeeks";        char c = 'e';        System.out.println("The occurrence of " + c + " in "                           + str + " is " + count(str, c));    }}
The occurrence of e in geeksforgeeks is 4
Related Article: 
Program to count the occurrence of a given character in a string
Count occurrence of a given character in a string using Stream API in Java
nishkarshgandhi
gabaa406
java-regular-expression
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Return new list on element insertion

28 Jan, 2019
The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using + operatorThis task can be performed if we make a single element list and concatenate original list with this newly made single element list.
# Python3 code to demonstrate # returning new list on element insertion# using + operator  # initializing listtest_list = [5, 6, 2, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # element to add K = 10  # using + operator# returning new list on element insertionres = test_list + [K]  # printing result print ("The newly returned added list : " +  str(res))
Output :
The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]

 Method #2 : Using * operatorSimilar kind of task can be used using * operator in which we use * operator to take all the elements and also add the new element to output the new list.
# Python3 code to demonstrate # returning new list on element insertion# using * operator  # initializing listtest_list = [5, 6, 2, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # element to add K = 10  # using * operator# returning new list on element insertionres = [*test_list, K]  # printing result print ("The newly returned added list : " +  str(res))
Output :
The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sort mixed list in Python

11 May, 2020
Sometimes, while working with Python, we can have a problem in which we need to sort a particular list which has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sort() + comparator
This problem can be solved using sort functionality provided by Python. We can construct our own custom comparator to complete the task of mixed sort.
# Python3 code to demonstrate working of# Sort Mixed List# using sort() + comparator  # comparator function for sortdef mixs(num):    try:        ele = int(num)        return (0, ele, '')    except ValueError:        return (1, num, '')    # initialize list test_list = [4, 'gfg', 2, 'best', 'is', 3]  # printing original list print("The original list : " + str(test_list))  # Sort Mixed List# using sort() + comparatortest_list.sort(key = mixs)  # printing resultprint("List after mixed sorting : " + str(test_list))
The original list : [4, 'gfg', 2, 'best', 'is', 3]
List after mixed sorting : [2, 3, 4, 'best', 'gfg', 'is']

 
Method #2 : Using sorted() + key + lambda + isdigit()
The combination of above functionalities can also be used to achieve solution to this problem. In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit().
# Python3 code to demonstrate working of# Sort Mixed List# using sorted() + key + lambda + isdigit()  # initialize list test_list = ['4', 'gfg', '2', 'best', 'is', '3']  # printing original list print("The original list : " + str(test_list))  # Sort Mixed List# using sorted() + key + lambda + isdigit()res = sorted(test_list, key = lambda ele: (0, int(ele))                        if ele.isdigit() else (1, ele))  # printing resultprint("List after mixed sorting : " + str(res))
The original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']

Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MATLAB - The Nested if Statements

It is always legal in MATLAB to nest if-else statements which means you can use one if or elseif statement inside another if or elseif statement(s).
The syntax for a nested if statement is as follows −
if <expression 1>
   % Executes when the boolean expression 1 is true 
   if <expression 2>
      % Executes when the boolean expression 2 is true    
   end
end

You can nest elseif...else in the similar way as you have nested if statement.
Create a script file and type the following code in it −
a = 100;
b = 200;
   % check the boolean condition 
   if( a == 100 )
   
      % if condition is true then check the following 
      if( b == 200 )
       
         % if condition is true then print the following 
         fprintf('Value of a is 100 and b is 200\n' );
      end
       
   end
   fprintf('Exact value of a is : %d\n', a );
   fprintf('Exact value of b is : %d\n', b );
When you run the file, it displays −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

CSS Grid Intro
Tryit: The column-gap property
How can I delete MySQL temporary table?

As we know that MySQL temporary table would be deleted if the current session is terminated. But of still in between the session we want to delete the temporary table than with the help of the DROP statement we can delete the temporary table. It can be understood with the help of the following example −
In this example, we are deleting the temporary table named ‘SalesSummary’ −
mysql> DROP TABLE SalesSummary;
Query OK, 0 rows affected (0.00 sec)
The above query will delete the table and it can be confirmed from the query below −
mysql> Select * from SalesSummary;
ERROR 1146 (42S02): Table 'query.SalesSummary doesn't exist
How to create a comma separated string from a list of string in C#?

A List of string can be converted to a comma separated string using built in string.Join extension method.
string.Join("," , list);
This type of conversion is really useful when we collect a list of data (Ex: checkbox selected data) from the user and convert the same to a comma separated string and query the database to process further.
 Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         List<string> fruitsList = new List<string> {
            "banana",
            "apple",
            "mango"
         };
         string fruits = string.Join(",", fruitsList);
         Console.WriteLine(fruits);
         Console.ReadLine();
      }
   }
}
The output of the above code is
banana,apple,mango
Similarly, a property in a list of complex objects can also be converted to a comma separated string like below.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         var studentsList = new List<Student> {
            new Student {
               Id = 1,
               Name = "John"
            },
            new Student {
               Id = 2,
               Name = "Jack"
            }
         };
         string students = string.Join(",", studentsList.Select(student => student.Name));
         Console.WriteLine(students);
         Console.ReadLine();
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}
The output of the above code is
John,Jack
Write a Java program to capitalize each word in the string?

You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.
 Live Demo
public class StringToUpperCaseEmp {
   public static void main(String[] args) {
      String str = "string abc touppercase ";
      String strUpper = str.toUpperCase();
      System.out.println("Original String: " + str);
      System.out.println("String changed to upper case: " + strUpper);
   }
}
Original String: string abc touppercase
String changed to upper case: STRING ABC TOUPPERCASE
Matplotlib.pyplot.hist2d() 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 hist2d() function in pyplot module of matplotlib library is used to make a 2D histogram plot.
Syntax:matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x, y : These parameter are the sequence of data.
bins : This parameter is an optional parameter and it contains the integer or sequence or string.
range : This parameter is an optional parameter and it the lower and upper range of the bins.
density : This parameter is an optional parameter and it contains the boolean values.
weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
cmin : This parameter has all bins that has count less than cmin will not be displayed.
cmax : This parameter has all bins that has count more than cmax will not be displayed.
Returns: This returns the following:
h :This returns the bi-dimensional histogram of samples x and y.
xedges :This returns the bin edges along the x axis.
yedges :This returns the bin edges along the y axis.
image :This returns the QuadMesh.
Below examples illustrate the matplotlib.pyplot.hist2d() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt     N_points = 100000x = np.random.randn(N_points)y = 4 * x + np.random.randn(100000) + 50   plt.hist2d(x, y,           bins = 100,            norm = colors.LogNorm(),            cmap ="gray")  plt.title('matplotlib.pyplot.hist2d() function \Example\n\n', fontweight ="bold")  plt.show()
Output:
Example #2:
#Implementation of matplotlib functionfrom matplotlib import colorsimport numpy as npfrom numpy.random import multivariate_normalimport matplotlib.pyplot as plt      result = np.vstack([    multivariate_normal([10, 10],            [[3, 2], [2, 3]], size=1000000),    multivariate_normal([30, 20],            [[2, 3], [1, 3]], size=100000)])  plt.hist2d(result[:, 0],           result[:, 1],           bins = 100,            cmap = "Greens",           norm = colors.LogNorm())plt.title('matplotlib.pyplot.hist2d function \Example')plt.show()  plt.hist2d(result[:, 0],            result[:, 1],           bins = 100,            cmap = "RdYlGn_r",           norm = colors.LogNorm())plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to Rename Multiple PySpark DataFrame Columns

29 Jun, 2021
In this article, we will discuss how to rename the multiple columns in PySpark Dataframe. For this we will use withColumnRenamed() and toDF() functions.
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  data  with null values# we can define null values with nonedata = [[None, "sravan", "vignan"],        ["2", None, "vvit"],        ["3", "rohith", None],        ["4", "sridevi", "vignan"],        ["1", None, None],        ["5", "gnanesh", "iit"]]  # specify column namescolumns = ['ID', 'NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  # show columnsprint(dataframe.columns)  # display dataframedataframe.show()
Output:
Method 1: Using withColumnRenamed()
This method is used to rename a column in the dataframe
Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”)
where
dataframe is the pyspark dataframe
old_column_name is the existing column name
new_column_name is the new column name
To change multiple columns, we can specify the functions for n times, separated by “.” operator
Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”).
withColumnRenamed”old_column_name”, “new_column_name”)
Example 1: Python program to change the column name for two columns
Python3
# display actual columnsprint("Actual columns: ", dataframe.columns)  # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed(  "college", "university").withColumnRenamed("ID", "student_id")  # display modified columnsprint("modified columns: ", dataframe.columns)  # final dataframedataframe.show()
Output:
Example 2: Rename all columns
Python3
# display actual columnsprint("Actual columns: ", dataframe.columns)  # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed(  "college", "university").withColumnRenamed(  "ID", "student_id").withColumnRenamed("NAME", "student_name")  # display modified columnsprint("modified columns: ", dataframe.columns)  # final dataframedataframe.show()
Output:
Method 2: Using toDF()
This method is used to change the names of all the columns of the dataframe
Syntax: dataframe.toDF(*(“column 1′′,”column 2”,”column n))
where, columns are the columns in the dataframe
Example: Python program to change the column names
Python3
# display actualprint("Actual columns: ", dataframe.columns)  # change column names to A,B,Cdataframe = dataframe.toDF(*("A", "B", "C"))  # display new columnsprint("New columns: ", dataframe.columns)  # display dataframedataframe.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
R – if statement

18 Oct, 2021
If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax: 
if (expression) {
   #statement to execute if condition is true
}
If the expression is true, the statement gets executed. But if the expression is FALSE, nothing happens. The expression can be a logical/numerical vector, but only the first element is taken into consideration. In the case of numeric vector, zero is taken as FALSE, rest as TRUE.
Control falls into the if block.
The flow jumps to Condition.
Condition is tested. If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
Flow steps out of the if block.
python
# R program to illustrate if statement # assigning value to variable aa <- 5 # conditionif(a > 0){    print("Positive Number")  # Statement}
Output: 
Positive Number
In this example, variable a is assigned a value of 2. The given expression will check if the value of variable a is greater than 0. If the value of a is greater than zero, the print statement will be executed and the output will be “Positive Number”. If the value of a is less than 0, nothing will happen. 
Python
# Assigning value to variable xx <- 12 # Conditionif (x > 20){    print("12 is less than 20")  # Statement}print("Hello World")
Output: 
12 is less than 20
Hello World
In this example, variable x is assigned a value. The given expression will check if the value of variable x is greater than 20. 
If the value of x is greater than 20, the statement given in the curly braces will be executed and the output will be “12 is less than 20”. Here, we have one more statement outside the curly braces. This statement will be executed whenever we run the program as it’s not a part of the given condition.
R
# R program to illustrate if statement# assigning value to variable aa <- -5 # conditionif(a > 0){    print("Positive Number")  # Statement}else{    print("-ve number")}
Output:
"-ve number"
kumar_satyam
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Creating a Data Frame from Vectors in R Programming
Check whether a character is Uppercase or not in Java

To check whether a character is in Uppercase or not in Java, use the Character.isUpperCase() method.
We have a character to be checked.
char val = 'K';
Now let us use the Character.isUpperCase() method.
if (Character.isUpperCase(val)) {
   System.out.println("Character is in Uppercase!");
}else {
   System.out.println("Character is in Lowercase!");
}
Let us see the complete example now to check for Uppercase in Java.
 Live Demo
public class Demo {
   public static void main(String []args) {
      System.out.println("Checking for Uppercase character...");
      char val = 'K';
      System.out.println("Character: "+val);
      if (Character.isUpperCase(val)) {
         System.out.println("Character is in Uppercase!");
      }else {
         System.out.println("Character is in Lowercase!");
      }
   }
}
Checking for Uppercase character...
Character: K
Character is in Uppercase!
GATE | GATE-CS-2015 (Set 3) | Question 56 - GeeksforGeeks

28 Jun, 2021
Consider B+ tree in which the search key is 12 bytes long, block size is 1024 bytes, record pointer is 10 bytes long and block pointer is 8 bytes long. The maximum number of keys that can be accommodated in each non-leaf node of the tree is(A) 49(B) 50(C) 51(D) 52Answer: (B)Explanation:
Let m be the order of B+ tree

m(8)+(m-1)12 <= 1024  
[Note that record pointer is not needed in non-leaf nodes]

m <= 51

Since maximum order is 51, maximum number of keys is 50. 
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90