code-rag-bench/online-tutorials huggingface dataset:
Print Single and Multiple variables in Java

To print single and multiple variables in Java, the code is as follows −
 Live Demo
public class Demo {
   public static void main(String args[]){
      String name_1 = "Hello";
      String name_2 = "World";
      System.out.println("Printing single variable");
      System.out.printf("%s", name_1);
      System.out.println("\nPrinting multiple variables");
      System.out.printf("First Name: %s\nLast Name: %s",name_1, name_2);
   }
}
Printing single variable
Hello
Printing multiple variables
First Name: Hello
Last Name: World
A class named Demo contains the main function, which defines two strings. These strings are
displayed using the ‘println’ function and using the ‘printf’ function.
Bound methods python - GeeksforGeeks

11 Dec, 2019
A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods.
Let’s understand this concept with an example:
# Python code to demonstrate# use of bound methods  class A:      def func(self, arg):        self.arg = arg        print("Value of arg = ", arg)    # Creating an instanceobj = A()    # bound methodprint(obj.func)
Output:
< bound method A.func of <__main__.A object at 0x7fb81c5a09e8>>

Here,
 obj.func(arg) is translated by python as A.func(obj, arg).
The instance obj is automatically passed as the first argument to the function called and hence the first parameter of the function will be used to access the variables/functions of the object.
Let’s see another example of the Bound method.
# Python code to demonstrate# use of bound methods    class Car:    # Car class created    gears = 5      # a class method to change the number of gears     @classmethod    def change_gears(cls, gears):        cls.gears = gears    # instance of class Car createdCar1 = Car()    print("Car1 gears before calling change_gears() = ", Car1.gears)Car1.change_gears(6) print("Gears after calling change_gears() = ", Car1.gears)  # bound methodprint(Car1.change_gears)
Output:
Car1 gears before calling change_gears() =  5
Gears after calling change_gears() =  6
<bound method Car.change_gears of <class '__main__.Car'>>

The above code is an example of a classmethod. A class method is like a bound method except that the class of the instance is passed as an argument rather than the instance itself. Here in the above example when we call Car1.change_gears(6), the class ‘Car’ is passed as the first argument.
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
SimpleDateFormat('E, dd MMM yyyy HH:mm:ss Z') in Java

Using the SimpleDateFormat(“E, dd MMM yyyy HH:mm:ss Z”), wherein E is for Day of Week −
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date −
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
      System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
      // displaying date
      Format f = new SimpleDateFormat("dd/MMMM/yyyy");
      String strDate = f.format(new Date());
      System.out.println("Current Date = "+strDate);
      // displaying month number
      f = new SimpleDateFormat("M");
      String strMonth = f.format(new Date());
      System.out.println("Month Number = "+strMonth);
      // current time
      f = new SimpleDateFormat("HH.mm.ss Z");
      String strTime = f.format(new Date());
      System.out.println("Current Time = "+strTime);
      // displaying hour
      f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
   }
}
Today's date and time = Mon, 26 Nov 2018 09:18:28 +0000
Current Date = 26/November/2018
Month Number = 11
Current Time = 09.18.28 +0000
Current Hour = 9
Current Minutes = 18
Current Seconds = 28
C++ if statement

An if statement consists of a boolean expression followed by one or more statements.
The syntax of an if statement in C++ is −
if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true
}

If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If  boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.
#include <iostream>
using namespace std;
 
int main () {
   // local variable declaration:
   int a = 10;
 
   // check the boolean condition
   if( a < 20 ) {
      // if condition is true then print the following
      cout << "a is less than 20;" << endl;
   }
   cout << "value of a is : " << a << endl;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Instruction type ANI d8 in 8085 Microprocessor

In 8085 Instruction set, ANI is a mnemonic, which stands for “ANd Immediate with Accumulator” and “d8” stands for any 8-bit or 1-Bytedata. This instruction is used to AND 8-bit immediate data with the Accumulator’s content. The result of this ANDingoperation will be stored in the Accumulator itself over writing its previous content. As it is an arithmetic operation do S, P, and Z flags are affected based on the result. Cy is reset to 0, and AC is set to 1. It occupies 2-Bytes in the memory.
Let us consider ANI CDH as a sample instruction of this type. It is a 2-Byte instruction. We are considering the initial content of Accumulator is ABH. So after this ANI operation result will be stored back on to the Accumulator itself. The result of execution of this instruction has been depicted in the following tracing table −
(A)
(F)
The internal calculation has been done as follows −
(A) ABH ---> 1010 1011
(d8) CDH ---> 1100 1101
          ---------
      ANI CDH ---> 1000 1001 (89H)

The timing diagram against this instruction ANI CDH execution is as follows.
Summary − So this instruction ANA E requires 2-Bytes, 2 Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram.
How do I change the background color of the ActionBar of an ActionBarActivity?

This example demonstrates how to change the background color of the ActionBar of an ActionBarActivity
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"?>
<androidx.constraintlayout.widget.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   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:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample">
   <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>
Step 4 − Add the following code to res/values/styles.xml
<resources>
   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
      <item name="colorPrimary">#995544</item>
      <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
      <item name="colorAccent">@color/colorAccent</item>
   </style>
   <style name="ActionBar.Solid.Ribbit.TitleTextStyle"
      parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
      <item name="android:textColor">#976325</item>
   </style>
</resources>
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 the android studio, open one of your project's activity files and click 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.
C library function - strncmp()

The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2.
Following is the declaration for strncmp() function.
int strncmp(const char *str1, const char *str2, size_t n)
str1 − This is the first string to be compared.
str1 − This is the first string to be compared.
str2 − This is the second string to be compared.
str2 − This is the second string to be compared.
n − The maximum number of characters to be compared.
n − The maximum number of characters to be compared.
This function return values that are as follows −
if Return value < 0 then it indicates str1 is less than str2.
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
if Return value = 0 then it indicates str1 is equal to str2.
The following example shows the usage of strncmp() function.
#include <stdio.h>
#include <string.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;

   strcpy(str1, "abcdef");
   strcpy(str2, "ABCDEF");

   ret = strncmp(str1, str2, 4);

   if(ret < 0) {
      printf("str1 is less than str2");
   } else if(ret > 0) {
      printf("str2 is less than str1");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
str2 is less than str1


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Flask â URL Building

The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.
The following script demonstrates use of url_for() function.
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)
The above script has a function user(name) which accepts a value to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.
Save the above code and run from Python shell.
Open the browser and enter URL as − http://localhost:5000/user/admin
The application response in browser is −
Hello Admin

Enter the following URL in the browser − http://localhost:5000/user/mvl
The application response now changes to −
Hello mvl as Guest


    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Program to find length of longest palindromic substring in Python

Suppose we have a string S. We have to find the length of longest palindromic substring in S.
We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the
longest palindromic substring is “BAB” and length is 3.
To solve this, we will follow these steps −
Define one square matrix of order same as the length of string, and fill it with False
Define one square matrix of order same as the length of string, and fill it with False
Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1
Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1
start := 0
start := 0
for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
for l in range 2 to length of S + 1
for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
for i in range 0 to length of S – l + 1
end := i + l
end := i + l
if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
if l = 2, then
if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1], then
DP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
otherwise
if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1] and DP[i + 1, end - 2], then
DP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
return max_len
return max_len
Let us see the following implementation to get better understanding −
class Solution(object):
   def solve(self, s):
      dp = [[False for i in range(len(s))] for i in range(len(s))]
         for i in range(len(s)):
            dp[i][i] = True
         max_length = 1
         start = 0
         for l in range(2,len(s)+1):
            for i in range(len(s)-l+1):

               end = i+l

               if l==2:
                  if s[i] == s[end-1]:
                     dp[i][end-1]=True
                     max_length = l
                     start = i
               else:
                  if s[i] == s[end-1] and dp[i+1][end-2]:
                     dp[i][end-1]=True
                  max_length = l
                  start = i
return max_length

ob = Solution()
print(ob.solve('BABAC'))
"ABBABBC"
5
React Native - Router

In this chapter, we will understand navigation in React Native.
To begin with, we need to install the Router. We will use the React Native Router Flux in this chapter. You can run the following command in terminal, from the project folder.
npm i react-native-router-flux --save

Since we want our router to handle the entire application, we will add it in index.ios.js. For Android, you can do the same in index.android.js.
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import Routes from './Routes.js'

class reactTutorialApp extends Component {
   render() {
      return (
         <Routes />
      )
   }
}
export default reactTutorialApp
AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)
Now we will create the Routes component inside the components folder. It will return Router with several scenes. Each scene will need key, component and title. Router uses the key property to switch between scenes, component will be rendered on screen and the title will be shown in the navigation bar. We can also set the initial property to the scene that is to be rendered initially.
import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'

const Routes = () => (
   <Router>
      <Scene key = "root">
         <Scene key = "home" component = {Home} title = "Home" initial = {true} />
         <Scene key = "about" component = {About} title = "About" />
      </Scene>
   </Router>
)
export default Routes
We already have the Home component from previous chapters; now, we need to add the About component. We will add the goToAbout and the goToHome functions to switch between scenes.
import React from 'react'
import { TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';

const Home = () => {
   const goToAbout = () => {
      Actions.about()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
         <Text>This is HOME!</Text>
      </TouchableOpacity>
   )
}
export default Home
import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'

const About = () => {
   const goToHome = () => {
      Actions.home()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
         <Text>This is ABOUT</Text>
      </TouchableOpacity>
   )
}
export default About
The app will render the initial Home screen.
You can press the button to switch to the about screen. The Back arrow will appear; you can use it to get back to the previous screen.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Difference between Entity constraints, Referential constraints and Semantic constraints

11 Oct, 2021
The data in a relational database is stored in form of a table. A table makes the data look organized. Yet in some cases we might face issues while working with the data like repetition. We might want enforce rules on the data to avoid such technical problems. Theses rules are called constraints. A constraint can be defined as a rule that has to enforced on the data to avoid faults. There are three kinds of constraints: entity, referential and semantic constraints. Listed below are the differences between these three constraints :
1. Entity constraints :These constraints are given within one table. The entity constraints are primary key, foreign key, unique.
Example :
create table student (rollnumber int primary key, name varchar2(30), course varchar2(10));
Insert into student values(111, 'ABC', 'Chemical');
Insert into student values(112, 'JJP', 'Mech');

These values are inserted in the table. Suppose a value given below is inserted :
Insert into student values(111, 'MAB', 'EEE');

It gives an error as the roll-number is enforced a primary key constraint that refrains from duplication. These constraints ensures to maintain uniqueness in the tables to avoid duplication’s.
2. Referential constraints :These constraints are used for referring other tables to enforce conditions on the data. The widely used referential constraint is foreign key.
Example :
create table marks (rollnumber int, name varchar2(30), course varchar2(30)
references student, marks int);

A table is created with a constraint that the marks should be rewarded to those students that are pursuing courses stated in the student table only. If a user tries to enter a value that doesn’t exist, it returns an error.
3. Semantic constraints :Datatypes are the semantic constraints enforced in a table. Datatypes help the data segregate according to its type.
Example :A name is a combination of different letters. We can place the name column in the char datatype yet char doesn’t satisfy the condition thereby varchar is preferably used for name.
name varchar2(30);

Difference between Entity constraints, Referential constraints and Semantic constraints :
surindertarika1234
DBMS
Difference Between
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between OLAP and OLTP in DBMS
Difference between Where and Having Clause in SQL
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
How to get the image size (height & width) using JavaScript ?

15 Apr, 2019
For getting size of an image (height and width), Element.clientHeight and Element.clientWidth properties is used.
Element.clientHeight: We can access the inner height of an element with this property. This height include the padding but not the margin and border.
Element.clientWidth: We can access the inner width of an element with this property. This width include the padding but not the margin and border.
Note: Here Element is image, So image.clientHeight and image.clientWidth will be used respectively for getting height and width of the image.
Example: Getting image size.
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <title>      getting-height-width-image-using-javascript  </title>    <style>        h1 {            text-align: center;            letter-spacing: 1px;        }                  img,        button {            display: block;            margin: 0 auto;        }                  button {            font-size: large;        }    </style></head>  <body>      <h1>      Getting height and width of an image  </h1>    <br>    <br>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png"         alt="logo-geeksforgeeks"         id="image">    <button type="submit"            onclick="myFunc()">      Get height and width  </button>      <div style="background-color: lightgray">        <div id="height">          </div>          <div id="width">          </div>    </div></body>  <script>    function myFunc() {        let image = document.getElementById('image');        let height = document.getElementById('height');        var width = document.getElementById('width');          height.innerHTML += '<h1>height of image is :'        + image.clientHeight + 'px </h1>';                width.innerHTML += '<h1>width of image is :'        + image.clientWidth + 'px </h1>';    }</script>  </html>
Output:After clicking on the button:
After clicking on the button:
Picked
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 Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
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 ?
MySQL | PASSWORD Function

08 Nov, 2019
The MySQL PASSWORD function is used for the generation of a hashed password using a plain-text password string It uses hashing techniques to generate the hashed password. This function is carried out by the authentication system.
MySQL server uses the PASSWORD function to encrypt MySQL passwords for storage in the Password column of the user grant table. The value returned by the PASSWORD function is a hashed string, or NULL if the argument was NULL. The PASSWORD function accepts one parameter which is the string to be encrypted.
Syntax:
PASSWORD( string_to_encrypt )
Parameters Used:
string_to_encrypt – It is used to specify the plain text string that is to be encrypted.
Return Value:The PASSWORD function in MySQL returns a hashed string.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing PASSWORD function on a string.
SELECT 
PASSWORD('xyz'); 
Output:
6gd7gb67shy87865 
Example-2: Implementing PASSWORD function on a string with a combination of characters and integer values.
SELECT 
PASSWORD('xyz123'); 
Output:
54fg56gs32sgi3862 
Example-3: Implementing PASSWORD function on a bigger string.
SELECT 
PASSWORD('geeksforgeeks'); 
Output:
79sgs54uksr1fy76509 
Example-4: Implementing PASSWORD function on a NULL string.
SELECT 
PASSWORD('NULL'); 
Output:
NULL 
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
Window functions in SQL
Difference between DDL and DML in DBMS
What is Smart Contract in Solidity?

11 May, 2022
Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on the Ethereum. 
Example:
Solidity
// Solidity program to // demonstrate how to// write a smart contract pragma solidity >= 0.4.16 < 0.7.0;  // Defining a contractcontract Storage{        // Declaring state variables    uint public setData;      // Defining public function     // that sets the value of     // the state variable    function set(uint x) public    {        setData = x;    }          // Defining function to    // print the value of    // state variable    function get(    ) public view returns (uint) {        return setData;    }}
Explanation:
1. Version Pragma: 
pragma solidity >=0.4.16 <0.7.0;

Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.7.0.
2. The contract keyword: 
contract Storage{ 
//Functions and Data 
}

The contract keyword declares a contract under which is the code encapsulated.
3. State variables: 
uint public setData;

State variables are permanently stored in contract storage that is they are written in Ethereum Blockchain. The line uint setData declares a state variable called setData of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database.
4. A function declaration:
function set(uint x) public
function get() public view returns (uint)

This is a function named set of access modifier type public which takes a variable x of datatype uint as a parameter. This was an example of a simple smart contract which updates the value of setData. Anyone can call the function set and overwrite the value of setData which is stored in Ethereum blockchain and there is possibly no way for anyone to stop someone from using this function. This is an example of a decentralized application that is censorship proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of Ethereum blockchain, this smart contract will be accessible.
Function get will retrieve and print the value of the state variable.
Output:
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Removing newline character from string

05 Jul, 2022
Many times, while working with Python strings, we can have a problem in which we have a huge amount of data and we need to perform preprocessing of a certain kind. This can also be removing stray newline characters in strings. Let’s discuss certain ways in which this task can be performed.
Here, we will cover 4 different methods to Remove Newline From String in Python:
Using the replace() function
Using the strip() function
Using  splitlines() method
Using the re.sub() Function
This task can be performed using brute force in which we check for “\n” as a string in a string and replace that from each string using a loop. 
Python3
# initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] # printing original listprint("The original list : " + str(test_list)) # Removing newline character from string# using loopres = []for sub in test_list:    res.append(sub.replace("\n", "")) # printing resultprint("List after newline character removal : " + str(res))
Output :
The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n']
List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']
The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string. 
Python3
lis = "\n Geeks for  Geeks \n"string = lis.strip()print(string)
Output:
Geeks for  Geeks
Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break.
Python3
def func(value):    return ''.join(value.splitlines())  mystring = "\n Geeks \n for \n  Geeks \n"print("Original string:", mystring)print("After deleting the new line:", func(mystring))
Output:
Actual string: 
 Geeks 
 for 
 Geeks 

After deleting the new line:  Geeks  for   Geeks 
This task can also be executed using regex functions which can also perform the global replace of all the newline characters with an empty string.
Python3
import re # initialize listtest_list = ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n'] # printing original listprint("The original list : " + str(test_list)) # Removing newline character from string# Using regexres = []for sub in test_list:    res.append(re.sub('\n', '', sub)) # printing resultprint("List after newline character removal : " + str(res))
Output :
The original list : ['gf\ng', 'i\ns', 'b\nest', 'fo\nr', 'geeks\n']
List after newline character removal : ['gfg', 'is', 'best', 'for', 'geeks']
surajkumarguptaintern
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SymPy - Integration

The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression.
For example −
integrate(f, x)

To compute a definite integral, pass the argument as follows −
(integration_variable, lower_limit, upper_limit)

>>> from sympy import * 
>>> x,y = symbols('x y') 
>>> expr=x**2 + x + 1 
>>> integrate(expr, x)

The above code snippet gives an output equivalent to the below expression −
x33+x22+x
>>> expr=sin(x)*tan(x) 
>>> expr 
>>> integrate(expr,x)

The above code snippet gives an output equivalent to the below expression −
−log⁡(sin⁡(x)−1)2+log⁡(sin⁡(x)+1)2−sin⁡(x)
The example of definite integral is given below −
>>> expr=exp(-x**2) 
>>> integrate(expr,(x,0,oo) )

The above code snippet gives an output equivalent to the below expression −
π2
You can pass multiple limit tuples to perform a multiple integral. An example is given below −
>>> expr=exp(-x**2 - y**2)
>>> integrate(expr,(x,0,oo),(y,0,oo))

The above code snippet gives an output equivalent to the below expression −
π4
You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method.
>>> expr = Integral(log(x)**2, x) 
>>> expr

The above code snippet gives an output equivalent to the below expression −
∫log(x)2dx
>>> expr.doit()

The above code snippet gives an output equivalent to the below expression −
xlog⁡(x)2−2xlog(x)+2x
SymPy supports various types of integral transforms as follows −
laplace_transform
fourier_transform
sine_transform
cosine_transform
hankel_transform
These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively.
Example 1
>>> from sympy import fourier_transform, exp 
>>> from sympy.abc import x, k 
>>> expr=exp(-x**2) 
>>> fourier_transform(expr, x, k)

On executing the above command in python shell, following output will be generated −
sqrt(pi)*exp(-pi**2*k**2)

Which is equivalent to −
π∗eπ2k2
Example 2
>>> from sympy.integrals import laplace_transform 
>>> from sympy.abc import t, s, a 
>>> laplace_transform(t**a, t, s)

On executing the above command in python shell, following output will be generated −
(s**(-a)*gamma(a + 1)/s, 0, re(a) > -1)
Matplotlib.pyplot.sca() in Python

03 May, 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. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The sca() method pyplot module of matplotlib library is used to set the current axes to be a.
Syntax: matplotlib.pyplot.sca(self, a)
Parameters: This method accept the following parameters that are discussed below:
a:This parameter is the current axes.
Returns: This method returns the axes.
Below examples illustrate the matplotlib.pyplot.sca() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom scipy import sin, cos    fig, ax = plt.subplots(2, 1)x = [1, 2, 3, 4, 5, 6, 7, 8, 9]  y1 = sin(x)y2 = cos(x)  plt.sca(ax[0])plt.plot(x, y1)  plt.sca(ax[1])plt.plot(x, y2)  fig.suptitle("""matplotlib.pyplot.sca()function Example\n\n""", fontweight ="bold")     plt.show() 
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt     fig, axes = plt.subplots(2, 2) axes = axes.flatten()   for i in range(4):    plt.sca(axes[i])    axes[i].text(0.5, 0.5, i + 1)      fig.suptitle("""matplotlib.pyplot.sca()function Example\n\n""", fontweight ="bold")     plt.show()  
Output:
Matplotlib Pyplot-class
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 | os.path.join() method
Python OOPs Concepts
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
Node.js URL.fileURLToPath API

14 Oct, 2021
This URL.fileURLToPath function decodes the file URL to a path string and ensures that the URL control characters (/, %) are correctly appended/adjusted when converting the given file URL into a path.
Syntax:
url.fileURLToPath( url )
Parameters: This function accepts single parameter url which holds the file URL string or object to convert into path.
Return Value: It returns a string which represents the fully-resolved platform-specific file path.
Below programs illustrates the use of URL.fileURLToPath() Method in Node.js:
Example 1:
// Node program to demonstrate the // URL.fileURLToPath() API as Setter  // Importing the module 'url' const url = require('url');   // Some random path from systemconst file = 'file://computerscience/geeksforgeeks.txt'  // Converting our file to properly encoded path                    console.log(url.fileURLToPath(file)) 
Output:
\\computerscience\geeksforgeeks.txt
Example 2:
// Node program to demonstrate the // URL.fileURLToPath() API as Setter  // Importing the module 'url' const url = require('url');  // Some random path from systemconst file = 'file:///C:/path/example/gfg'   // Converting the file to properly encoded pathconsole.log(url.fileURLToPath(file))
Output:
 C:\path\example\gfg 
Note: The above program will compile and run by using the node app.js command.
Reference: https://nodejs.org/api/url.html#url_url_fileurltopath_url
Node-URL
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
How to connect Node.js with React.js ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Roadmap to Learn JavaScript For Beginners
Python program to print the dictionary in table format

31 Aug, 2021
Given a Dictionary. The task is to print the dictionary in the table format.Examples: 
Input: {1: [“Samuel”, 21, ‘Data Structures’], 2: [“Richie”, 20, ‘Machine Learning’], 3: [“Lauren”, 21, ‘OOPS with java’], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java  
Method 1: Displaying result by iterating through values.  
Python3
# Define the dictionarydict ={} # Insert data into dictionarydict1 = {1: ["Samuel", 21, 'Data Structures'],     2: ["Richie", 20, 'Machine Learning'],     3: ["Lauren", 21, 'OOPS with java'],     } # Print the names of the columns.print ("{:<10} {:<10} {:<10}".format('NAME', 'AGE', 'COURSE')) # print each data item.for key, value in dict1.items():    name, age, course = value    print ("{:<10} {:<10} {:<10}".format(name, age, course))
Output: 
NAME       AGE        COURSE    
Samuel     21         Data Structures
Richie     20         Machine Learning
Lauren     21         OOPS with java
Method 2: Displaying by using matrix format  
Python3
# define the dictionarydict1 = {} # insert data into dictionarydict1 = {(0, 0): 'Samuel', (0, 1): 21, (0, 2): 'Data structures',         (1, 0): 'Richie', (1, 1): 20, (1, 2): 'Machine Learning',         (2, 0): 'Lauren', (2, 1):21, (2, 2): 'OOPS with Java'} # print the name of the columns explicitly.print(" NAME ", " AGE ", "  COURSE " ) # Iterate through the dictionary# to print the data.for i in range(3):         for j in range(3):        print(dict1[(i, j)], end ='   ')             print()
Output: 
 NAME   AGE    COURSE 
Samuel   21   Data structures   
Richie   20   Machine Learning   
Lauren   21   OOPS with Java 
Method 3: Displaying by using zip format  
Python3
# define the dictionarydict1 = {} # insert data into dictionary.dict1 = {'NAME':['Samuel', 'Richie', 'Lauren'],         'AGE':[21, 20, 21],         'COURSE':['Data Structures', 'Machine Learning', 'OOPS with Java']} # print the contents using zip format.for each_row in zip(*([i] + (j)                      for i, j in dict1.items())):           print(*each_row, " ")
Output: 
NAME  AGE COURSE  
Samuel 21 Data Structures  
Richie 20 Machine Learning  
Lauren 21 OOPS with Java
 
sagar0719kumar
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python MongoDB – Update_many Query

26 May, 2020
MongoDB is  a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a python script. It needs both python and mongoDB to be installed on the system.
Update function has been deprecated in newer versions of  MongoDB (3.xx and above). Earlier update function could be used for both single updates and multiple using “multi = true”. But in newer versions of mongoDB it is recommended to use update_many() and update_one(). 
The major difference is that the user needs to plan ahead if the query is going to be updating single or multiple documents.
Syntax:
db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>
   }
)

Update Operators in MongoDB
Setting Values:
$set: Used to set a fields value.
$setOnInsert: Update value only if a new document insertion.
$unset: Remove the field and its value.
Numeric Operators:
$inc: Increases the value by a given amount.
$min/$max: returns minimum or maximum of value.
$mul: multiplies the values by a given amount.
Miscellaneous Operators:
$currentDate: Updates value of a field to current date.
$rename: Renames a field
Sample Database:
Some use cases we are going to see in this article where updating many records can be useful: 
Changing or incrementing several elements based on a condition.Inserting a new field to multiple or all documents.
Changing or incrementing several elements based on a condition.
Inserting a new field to multiple or all documents.
Example 1: All the students with marks greater than 35 has been passed.
Python3
from pymongo import MongoClient    # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017')  # Accessing desired database and collectiondb = client.gfgcollection = db["classroom"]  # Update passed field to be true for all# students with marks greater than 35collection.update_many(    {"marks": { "$gt": "35" } },        {            "$set": { "passed" : "True" }        })
Database After Query: 
Example 2: New field called address added to all documents
Python
from pymongo import MongoClient    # Creating an instance of MongoClient # on default localhostclient = MongoClient('mongodb://localhost:27017')  # Accessing desired database and collectiondb = client.gfgcollection = db["classroom"]  # Address filed to be added to all documentscollection.update_many(        {},        {"$set":            {                "Address": "value"            }        },       # don't insert if no document found   upsert=False,   array_filters=None   )
Database After query: 
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js console.warn() Function

14 Oct, 2021
The console.warn() function from console class of Node.js is used to display the warning messages on the console. It prints to stderr with newline.
Note: This function is an alias of console.error() function.
Syntax:
console.warn( [data][, ...args] )
Parameter: This function can contains multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution values.
Return Value: The function returns the warning message.
Below programs demonstrate the working of the console.warn() function:
Program 1:
function displayWarning(x) {    console.warn(`GeeksforGeeks is a ${x} portal`);}   const x = 'Computer Science';  displayWarning(x);
Output:
GeeksforGeeks is a Computer Science portal
Program 2:
function compareNumber(x, y) {          // Check condition    if (x > y) {        console.warn(`${x} is greater then ${y}`);    }    else {        console.warn(`${x} is less then or equal to ${y}`);    }}  // Store number to variablex = 100;y = 50;  compareNumber(x, y);
Output:
100 is greater then 50
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
minimize_window driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around minimize_window driver method in Selenium. minimize_window method minimizes the current window that webdriver is using.
Syntax –
driver.minimize_window()
Example –Now one can use minimize_window method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.minimize_window()

To demonstrate, minimize_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s minimize window,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")    # minimize window positiondriver.minimize_window()
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.