code-rag-bench/online-tutorials huggingface dataset:
How to display message from a stored procedure?

To display message from stored procedure on the basis of conditions, let us use IF-ELSE condition −
mysql> DELIMITER //
mysql> CREATE PROCEDURE showMessage(value int,Name varchar(20))
   BEGIN
      IF(value > 100) then
         SELECT CONCAT("HELLO"," ",Name);
      ELSE
         SELECT CONCAT("BYE"," ",Name);
      END IF;
      END
      //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;
Case 1 − Call the stored procedure using CALL command, when value is more than 100 −
call showMessage(200,'John');
This will produce the following output −
+--------------------------+
| CONCAT("HELLO"," ",Name) |
+--------------------------+
| HELLO John               |
+--------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.02 sec)
Case 2 − When the value is less than 100, a difference message will be visible since ELSE condition will execute −
mysql> call showMessage(10,'John');
This will produce the following output −
+------------------------+
| CONCAT("BYE"," ",Name) |
+------------------------+
| BYE John               |
+------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
C program to find Fibonacci series for a given number

Fibonacci Series is a sequence of numbers obtained by adding the two previous numbers.
Fibonacci series starts from two numbers f0 & f1.
The initial values of fo & f1 can be taken 0, 1 or 1, 1
Fibonacci series satisfies the following conditions −
fn = fn-1 + fn-2
Refer to the algorithm for the Fibonacci series.
START
Step 1: Read integer variable a,b,c at run time
Step 2: Initialize a=0 and b=0
Step 3: Compute c=a+b
Step 4: Print c
Step 5: Set a=b, b=c
Step 6: Repeat 3 to 5 for n times
STOP
Following is the C program for the Fibonacci series using While Loop −
 Live Demo
#include <stdio.h>
int main(){
   int number, i = 0, Next, first = 0, second = 1;
   printf("\n Please Enter the Range Number: ");
   scanf("%d",&number);
   while(i < number){
      if(i <= 1){
         Next = i;
      }
      else{
         Next = first + second;
         first = second;
         second = Next;
      }
      printf("%d \t", Next);
      i++;
   }
   return 0;
}
When the above program is executed, it produces the following result −
Please Enter the Range Number: 6
0 1 1 2 3 5
JavaScript - Date getDate() Method

Javascript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31.
Its syntax is as follows −
Date.getDate()

Returns today's date and time.
<html>
   <head>
      <title>JavaScript getDate Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date("December 25, 1995 23:15:00");
         document.write("getDate() : " + dt.getDate() ); 
      </script>      
   </body>
</html>

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
response.is_redirect - Python requests - GeeksforGeeks

01 Mar, 2020
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.is_redirect out of a response object. response.is_redirect returns True if the response was redirected, otherwise False.
To illustrate use of response.is_redirect, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
# import requests moduleimport requests  # Making a get requestresponse = requests.get('https://geeksforgeeks.org')  # print responseprint(response)  # print is_redirect Flagprint(response.is_redirect)
Save above file as request.py and run using
Python request.py

Check that False at the start of the output, it shows that is_redirect is False.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
base64.b32decode() in Python - GeeksforGeeks

26 Mar, 2020
With the help of base64.b32decode() method, we can decode the binary string using base32 alphabets into normal form.
Syntax : base64.b32decode(b_string)
Return : Return the decoded string.
Example #1 :In this example we can see that by using base64.b32decode() method, we are able to get the decoded string which can be in binary form by using this method.
# import base64from base64 import b32decodefrom base64 import b32encode  s = b'GeeksForGeeks's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s)  print(gfg)
Output :
b’GeeksForGeeks’
Example #2 :
# import base64from base64 import b32decodefrom base64 import b32encode  s = b'Hello World's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s)  print(gfg)
Output :
b’Hello World’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
MongoDB - Embedded Documents - GeeksforGeeks

14 Sep, 2021
MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents.  
Notes –  
In MongoDB, you can only nest document up to 100 levels.
The overall document size must not exceed 16 MB.
 
 
In MongoDB, you can easily embed a document inside another document. As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document. 
Syntax:  
{
....
field: {field1: value1, field2: value2}
....
}
Let us discuss this concept with the help of the given examples – 
Example 1: 
Suppose we have a database named ‘GeeksforGeeks’. Now this database has a collection named ‘Courses’ and this collection contains a document. Inside this document, we have a field named ‘name’ which contains another document and this document contain three fields(i.e, first, middle, last) with their values.  
 
Example 2: 
Again, we are taking GeeksforGeeks database. Inside this database, we already have a collection named ‘Courses’, now we add another document in this collection, which contains the details of the student who select paid courses. Inside this document, we have a field named ‘courseDetails’. This field contains a document and this document contains some field-value pairs and a sub-document which contains the paymentDetials.  
So, overall the Courses collection contains two documents and these documents contain nested documents.  
 
gulshankumarar231
MongoDB
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Difference between __sizeof__() and getsizeof() method - Python - GeeksforGeeks

06 May, 2021
Memory management is of utmost priority when we write large chunks of code. So in addition to good coding knowledge, it is important to be able to write programs, so as to handle memory efficiently. 
So let us look at the two ways of getting the size of a particular object in Python. These are getsizeof() method and __sizeof() method. The getsizeof() is a system-specific method and hence we have to import the sys module to use it. A sample code is as shown below for calculating the size of a list. 
Python3
import sysa =[1, 2]b =[1, 2, 3, 4]c =[1, 2, 3, 4]d =[2, 3, 1, 4, 66, 54, 45, 89]print(sys.getsizeof(a))print(sys.getsizeof(b))print(sys.getsizeof(c))print(sys.getsizeof(d))
Output:  
80
96
96
128
getsizeof() method calls the __sizeof__() method o the object with an additional garbage collector overhead. Hence the size returned by the getsize() method will be more than that returned by the __sizeof()__ method. For example, the getsizeof() method returns 64 bytes for an empty list and then 8 bytes for every additional element.Now let’s look at the __sizeof__() method. It returns the size of the object without any overhead. 
Python3
w =[1, 2]x =[4, 5, 7, 9]y =[2, 8, 6, 56, 45, 89, 88]z =[54, 45, 12, 23, 24, 90, 20, 40]print(w.__sizeof__())print(x.__sizeof__())print(y.__sizeof__())print(z.__sizeof__())
Output:  
56
72
96
104
For example, the __sizeof__() method returns 40 bytes for an empty list and then 8 bytes for every additional element. 
anshuman24
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Find Symmetric Pairs in dictionary - GeeksforGeeks

15 Oct, 2019
Sometimes, while working with Python dictionary, one can have a problem in which one desires to get key-value pairs that are symmetrical, i.e that has key-value pair of same value irrespective of the fact value is a key or value. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using generator + loop
This task can be solved in brute force method using loops and generators by yielding at runtime the values of matching key-value pairs.
# Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# using generator + loop  # generator function to perform taskdef find_sym_pairs(test_dict):    for key in test_dict.keys():        val = test_dict.get(key)          if test_dict.get(val) == key:            yield key, val    return   # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3,  1 : 'a', 2 : 'b'}  # printing original dict print("The original dict is : " + str(test_dict))  # Find Symmetric Pairs in dictionary# using generator + loopres = []for key, val in find_sym_pairs(test_dict):    temp = (key, val)    res.append(temp)  # printing resultprint("The pairs of Symmetric values : " + str(res))
The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'}
The pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')]

 
Method #2 : Using list comprehension
This task can also be performed as a one-liner using list comprehension as a shortened way of performing loop-based solution.
# Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# Using list comprehension  # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3,  1 : 'a', 2 : 'b'}  # printing original dict print("The original dict is : " + str(test_dict))  # Find Symmetric Pairs in dictionary# Using list comprehensiontemp = [(key, value) for key, value in test_dict.items()]res = [(x, y) for (x, y) in temp if (y, x) in temp]  # printing resultprint("The pairs of Symmetric values : " + str(res))
The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'}
The pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')]

Python dictionary-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to use onKeyPress event in ReactJS? - GeeksforGeeks

25 Jan, 2021
The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers.
To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build an application that displays the key pressed in the input box.
Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from 'react';  const App = () => {  const [state, setState] = useState('');      const handler = (event) => {      // changing the state to the name of the key    // which is pressed    setState(event.key);  };      return (    <div>      <h1>Hi Geeks!</h1>        <p>Key pressed is: {state}</p>                {/* Passing the key pressed to the handler function */}      <input type="text" onKeyPress={(e) => handler(e)} />            </div>  );};  export default App;
Note: You can define your own styling in the App.css file.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data from one component to other component in ReactJS ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
ReactJS defaultProps
Re-rendering Components in ReactJS
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to Open URL in New Tab using JavaScript ? - GeeksforGeeks

20 Jul, 2021
In HTML, the anchor tag is used to open URLs in a new tab in an elementary and straightforward manner. More about this tag can be learnt from this article. However, sometimes there’s a need to do the same using Javascript. In this case window.open() method proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values.
Approach:
To open a new tab, we have to use _blank in second parameter of window.open().
The return value of window.open() is a reference to the newly created window or tab or null if it failed.
Do not add a third parameter to it as it will result in the opening of a new window rather than a tab
Syntax:
window.open(URL, '_blank');

Example 1:
<html>  <body>      <p>Click the button to open a new tab </p>      <button onclick="NewTab()">      Open Geeksforgeeks  </button>      <script>        function NewTab() {            window.open(              "https://www.geeksforgeeks.org", "_blank");        }    </script>  </body>  </html>
Output:
Example 2:
<html>  <body>      <p>Click the button to open google.</p>      <button onclick="Open()">Geeksforgeeks</button>      <script>        function Open() {            window.open("https://www.google.com", "_blank");        }    </script>  </body>  </html>
Output :
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
bad_alloc in C++ - GeeksforGeeks

27 Feb, 2018
Prerequisite : Exceptions in C++
Standard C++ contains several built-in exception classes. The most commonly used is bad_alloc, which is thrown if an error occurs when attempting to allocate memory with new.
This class is derived from exception.
To make use of bad_alloc, one should set up the appropriate try and catch blocks. Here’s a short example, that shows how it’s used :
C++
// CPP code for bad_alloc#include <iostream>#include <new>  // Driver codeint main () {  try  {     int* gfg_array = new int[100000000];  }  catch (std::bad_alloc & ba)  {     std::cerr << "bad_alloc caught: " << ba.what();  }  return 0;}
bad_alloc caught: std::bad_alloc

cpp-exception
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Inline Functions in C++
Convert string to char array in C++
Python | Count occurrences of an element in a Tuple - GeeksforGeeks

17 Jul, 2020
In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using simple approach and how inbuilt functions can be used to solve this problem.
Examples:
Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)

Input : 4
Output : 0 times

Input : 10
Output : 3 times

Input : 8
Output : 4 times

Method 1(Simple Approach):We keep a counter that keeps on increasing if the required element is found in the tuple.
# Program to count the number of times an element# Present in the listdef countX(tup, x):    count = 0    for ele in tup:        if (ele == x):            count = count + 1    return count   # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(countX(tup, enq))print(countX(tup, enq1))print(countX(tup, enq2))
Output:
0 times
3 times
4 times

Method 2(Using count()):The idea is to use method count() to count number of occurrences.
# Program to count the number of times an element# Present in the list# Count function is useddef Count(tup, en):    return tup.count(en)  # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(Count(tup, enq), "times")print(Count(tup, enq1), "times")print(Count(tup, enq2), "times")
Output:
0 times
3 times
4 times

python-tuple
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
HTML | <textarea> required Attribute - GeeksforGeeks

06 May, 2019
The HTML <textarea> required Attribute is a Boolean attribute which is used to specify that the <textarea> element must be filled out before submitting the Form.
Syntax:
<textarea required> 
Example: This Example illustrates the use of required attribute in Textarea Element.
<!DOCTYPE html><html>  <head>    <title>required Attribute</title>    <style>        h1,        h2 {            color: green;            font-style: italic;        }                  body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksForGeeks</h1>    <h2>HTML Textarea required attribute </h2>    <form action="#">        <textarea rows="7"                  cols="50"                   name="comment"                   required></textarea>        <input type="submit">    </form></body>  </html>
output:
Supported Browsers: The browser supported by HTML Textarea required Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
HTML Cheat Sheet - A Basic Guide to HTML
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
scipy stats.gamma() | Python - GeeksforGeeks

27 Mar, 2019
scipy.stats.gamma() is an gamma continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :-> q : lower and upper tail probability-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> a : shape parameters-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : gamma continuous random variable
Code #1 : Creating gamma continuous random variable
from scipy.stats import gamma   numargs = gamma .numargs[a] = [0.7, ] * numargsrv = gamma (a)  print ("RV : \n", rv) 
Output :
RV : 
 <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D57997F60>

Code #2 : generalized gamma random variates.
import numpy as npquantile = np.arange (0.01, 1, 0.1)   # Random VariatesR = gamma.rvs(a, scale = 2,  size = 10)print ("Random Variates : \n", R)  # PDFR = gamma.pdf(a, quantile, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R)
Output :
Random Variates : 
 [0.01601209 0.05164555 1.22072489 0.53476245 0.11529018 0.16966403
 0.59198231 0.71995529 0.86063603 3.81492177]

Probability Distribution : 
 [0.00710916 0.07919869 0.15097014 0.21974949 0.28337498 0.34020629
 0.38910556 0.42939763 0.46081639 0.48344302]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt  distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print("Distribution : \n", distribution)  plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution : 
 [0.         0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449  0.67346939
 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
 1.10204082 1.16326531 1.2244898  1.28571429 1.34693878 1.40816327
 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
 2.20408163 2.26530612 2.32653061 2.3877551  2.44897959 2.51020408
 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
 2.93877551 3.        ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np  x = np.linspace(0, 5, 100)  # Varying positional argumentsy1 = gamma.pdf(x, a, 1, 3)y2 = gamma.pdf(x, a, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python - Concatenate Dictionary string values - GeeksforGeeks

23 Jan, 2020
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss string concatenation of like key values and ways to solve it in this article.
Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line.
# Python3 code to demonstrate working of# Concatenate Dictionary string values# Using dictionary comprehension + keys()  # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using dictionary comprehension + keys()# Concatenate Dictionary string valuesres = {key: test_dict1[key] + test_dict2.get(key, '') for key in test_dict1.keys()}  # printing result print("The string concatenation of dictionary is : " + str(res))
The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}
The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}
The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}

 
Method #2 : Using Counter() + “+” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the plus operator can perform the task of concatenation.
# Python3 code to demonstrate working of# Concatenate Dictionary string values# Using Counter() + "+" operatorfrom collections import Counter  # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'}  # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # Using Counter() + "+" operator# Concatenate Dictionary string valuestemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] + temp2[key] for key in temp1})   # printing result print("The string concatenation of dictionary is : " + str(dict(res)))
The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}
The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}
The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}

Python dictionary-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Java Program for Linear Search - GeeksforGeeks

04 Dec, 2018
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
Java
// Java code for linearly search x in arr[]. If x// is present then return its location, otherwise// return -1class LinearSearch {    // This function returns index of element x in arr[]    static int search(int arr[], int n, int x)    {        for (int i = 0; i < n; i++) {            // Return the index of the element if the element            // is found            if (arr[i] == x)                return i;        }          // return -1 if the element is not found        return -1;    }      public static void main(String[] args)    {        int[] arr = { 3, 4, 1, 7, 5 };        int n = arr.length;                  int x = 4;          int index = search(arr, n, x);        if (index == -1)            System.out.println("Element is not present in the array");        else            System.out.println("Element found at position " + index);    }}
Element found at position 1

The time complexity of the above algorithm is O(n).
Please refer complete article on Linear Search for more details!
Java Programs
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
PyQt5 Label – Accessing opacity level of the Opacity effect - GeeksforGeeks

10 May, 2020
In this article we will see how we can access the opacity level of the opacity effect of the label, the more the value of opacity the label will be clearly the visible and if opacity value is lesser more transparent it will become. By default opacity level is 0.7 and in order to set the opacity we use setOpacity method.
In order to do this we use opacity method.
Syntax : opacity_effect.opacity(n)
Argument : It takes no argument
Return : It returns float value
Note : Opacity level value ranges from 0 to 1
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating label        label = QLabel("Label", self)          # setting geometry to the label        label.setGeometry(200, 100, 150, 60)          # setting alignment to the label        label.setAlignment(Qt.AlignCenter)          # setting font        label.setFont(QFont('Arial', 15))          # setting style sheet of the label        label.setStyleSheet("QLabel"                            "{"                            "border : 2px solid green;"                            "background : lightgreen;"                            "}")          # creating a opacity effect        self.opacity_effect = QGraphicsOpacityEffect()          # setting opacity level        self.opacity_effect.setOpacity(0.3)          # adding opacity effect to the label        label.setGraphicsEffect(self.opacity_effect)          # result label        result = QLabel(self)          # setting geometry of the result label        result.setGeometry(200, 200, 300, 30)          # getting opacity level        level = self.opacity_effect.opacity()          # setting text to the result label        result.setText("Opacity level : " + str(level))    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
C function to Swap strings - GeeksforGeeks

06 Jul, 2018
Let us consider the below program.
#include<stdio.h>void swap(char *str1, char *str2){  char *temp = str1;  str1 = str2;  str2 = temp;}     int main(){  char *str1 = "geeks";  char *str2 = "forgeeks";  swap(str1, str2);  printf("str1 is %s, str2 is %s", str1, str2);  getchar();  return 0;}
Output of the program is str1 is geeks, str2 is forgeeks. So the above swap() function doesn’t swap strings. The function just changes local pointer variables and the changes are not reflected outside the function.
Let us see the correct ways for swapping strings:
Method 1(Swap Pointers)If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other’s data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer.
#include<stdio.h>  /* Swaps strings by swapping pointers */ void swap1(char **str1_ptr, char **str2_ptr){  char *temp = *str1_ptr;  *str1_ptr = *str2_ptr;  *str2_ptr = temp;}     int main(){  char *str1 = "geeks";  char *str2 = "forgeeks";  swap1(&str1, &str2);  printf("str1 is %s, str2 is %s", str1, str2);  getchar();  return 0;}
This method cannot be applied if strings are stored using character arrays.
Method 2(Swap Data)If you are using character arrays to store strings then preferred way is to swap the data of both arrays.
#include<stdio.h>#include<string.h>#include<stdlib.h>   /* Swaps strings by swapping data*/void swap2(char *str1, char *str2){  char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));  strcpy(temp, str1);  strcpy(str1, str2);  strcpy(str2, temp);  free(temp);}     int main(){  char str1[10] = "geeks";  char str2[10] = "forgeeks";  swap2(str1, str2);  printf("str1 is %s, str2 is %s", str1, str2);  getchar();  return 0;}
This method cannot be applied for strings stored in read-only block of memory.
Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.
C Array and String
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write a Pseudo Code?
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
SQL Interview Questions
Understanding "extern" keyword in C
Mutex vs Semaphore
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
GATE | GATE-CS-2005 | Question 87 - GeeksforGeeks

28 Jun, 2021
We are given 9 tasks T1, T2.... T9. The execution of each task requires one unit of time. We can execute one task at a time. Each task Ti has a profit Pi and a deadline di Profit Pi is earned if the task is completed before the end of the dith unit of time.
Task     T1  T2     T3  T4  T5  T6     T7 T8  T9
Profit   15  20     30  18  18  10     23 16  25
Deadline 7   2      5   3      4   5      2  7   3 
Are all tasks completed in the schedule that gives maximum profit?(A) All tasks are completed(B) T1 and T6 are left out(C) T1 and T8 are left out(D) T4 and T6 are left outAnswer: (D)Explanation:
Task     T1  T2     T3  T4  T5  T6     T7 T8  T9
Profit   15  20     30  18  18  10     23 16  25
Deadline 7   2      5   3      4   5      2  7   3 
To maximize profit, we can finish tasks in following order T7, T2, T9, T5, T3, T8, T1Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
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-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Instant getEpochSecond() method in Java with Examples - GeeksforGeeks

22 Nov, 2018
The getEpochSecond() method of Instant class is used to return the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. It means the difference between time in seconds of this instance and time represented by “1970-01-01T00:00:00Z” is returned by this method. The epoch second count is a simple incrementing count of seconds where the second 0 is 1970-01-01T00:00:00Z.
Syntax:
public long getEpochSecond()
Returns: This method returns the seconds from the epoch of 1970-01-01T00:00:00Z.
Below programs illustrate the Instant.getEpochSecond() method:
Program 1:
// Java program to demonstrate// Instant.getEpochSecond() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create  instance object        Instant instant            = Instant.parse("2018-10-20T16:55:30.00Z");          // print Instant Value        System.out.println("Instant: " + instant);          // get epochValue using getEpochSecond        long epochValue = instant.getEpochSecond();          // print results        System.out.println("Java epoch Value: "                           + epochValue);    }}
Instant: 2018-10-20T16:55:30Z
Java epoch Value: 1540054530

Program 2:
// Java program to demonstrate// Instant.getEpochSecond() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create current instance object        Instant instant            = Instant.now();          // print Instant Value        System.out.println("Current Instant: "                           + instant);          // get epochValue using getEpochSecond        long epochValue = instant.getEpochSecond();          // print results        System.out.println("Java epoch Value: "                           + epochValue);    }}
Current Instant: 2018-11-22T08:26:19.502Z
Java epoch Value: 1542875179

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#getEpochSecond()
java-basics
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
PyQt5 QDial - Getting Slider's Value - GeeksforGeeks

07 Jul, 2020
In this article we will see how we can get slider’s value of the QDial. User can change the value with the help of mouse although we can change it programmatically with the help of setValue method. The slider forces the value to be within the legal range i.e value should be greater than or equal to the minimum value and it should be less than or equal to the maximum limit. Changing the value also changes the slider position.
In order to do this we use value method with the QDial object
Syntax : dial.value()
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating QDial object        dial = QDial(self)          # setting geometry to the dial        dial.setGeometry(100, 100, 100, 100)          # making notch visible        dial.setNotchesVisible(True)          # value        value = 50          # setting value to the dial slider        dial.setValue(value)            # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(220, 125, 200, 60)          # making label multiline        label.setWordWrap(True)                  # getting slider value        value = dial.value()                  # setting text to the label        label.setText("Value : " + str(value))        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDial
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
PyQt5 – Set Icon for Check Box - GeeksforGeeks

22 Apr, 2020
In this article we will see about how to set icon to a check box. Setting icon to a check box is similar to setting icon to a main window, icon of check box appear in between the indicator and the check box it self below is how normal check box vs check box with icon looks like.
 
In order to do this we will use setIcon method.
Syntax : checkbox.setIcon(QIcon(‘icon.png’))
Argument : It takes file name or path as argument.
Action performed : It will set icon to the check box
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating the check-box        checkbox = QCheckBox('Geek ?', self)          # setting geometry of check box        checkbox.setGeometry(200, 150, 100, 30)          # setting icon to check box        checkbox.setIcon(QIcon('logo.png'))      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
CSV Full Form - GeeksforGeeks

12 Jun, 2020
Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension.The data fields in a ksd)(*&^%$#@nslnl like in databases or spreadsheets CSV are usually separated by delimiters, a space or a comma
1. alex, 528, IT
2. mallika, 650, Commerce
3. joy, 670, Humanities
4. yash, 679, IT 
The CSV files are used for transferring large databases between multiple programs maintaining a strict format. The CSV files can be opened with any text editor, Notepad, Excel etc
Characteristics :
The data fields are separated by commasEach data record is entered in a new line. In case the record is too large, it can cover multiple lines.The fields containing commas are separated by double-quotes are contained in a set of double quotes.The fields containing double quotes are contained in a set of double quotes.The space characters that are next to built-in commas are not taken into account.
The data fields are separated by commas
Each data record is entered in a new line. In case the record is too large, it can cover multiple lines.
The fields containing commas are separated by double-quotes are contained in a set of double quotes.
The fields containing double quotes are contained in a set of double quotes.
The space characters that are next to built-in commas are not taken into account.
Advantages :
Faster in handling
Easy to generate
User friendly : processed by almost all apps and easy to read and understand.
Easy implementation : easy to store and edit data and simple to parse the file.
It is a standard format for a text file providing and easy to look straight forward data schema.
Smaller in size : overcomes the redundancy of storage of header and footer tags.
Disadvantages :
No distinction between textual and numerical data.
It facilitates the storage of simple data only. Complex fields are difficult to handle.
Special characters and control characters are not represented correctly
Lack of standard way of denoting binary data.
Picked
DBMS
Full Form
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
HTTP Full Form
DBA Full Form
CDMA Full Form
Peripheral Component Interconnect (PCI)
RDBMS Full Form
The MySQL Command-Line Client

The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format. When it is used noninteractively, like a filter, the result would be presented in tab-separated format.
The output format can be changed with the help of command options. If there are issues because of insufficient memory for large result sets, the --quick option can be used.
This forces the mysql to retrieve results from the server, a row at a time instead of retrieving the entire result set at once and buffering it in memory before it is being displayed. This is done by returning the result set with the help of the mysql_use_result() C API function which is present in the client/server library instead of mysql_store_result().
Using mysql is an easy task. It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below −
shell> mysql db_name
(or)
shell> mysql --user=user_name --password db_name
Enter password: your_password
Then an SQL statement can be typed, and can be ended with ;, \g, or \G.
Typing Control+C interrupts the current statement if there is such a statement, or cancels any partial input line if not.
SQL statements can be executed in a script file (or batch file). It has been shown below −
shell> mysql db_name < script.sql > output.tab

On Unix, the mysql client logs statements which are executed interactively to a history file.