code-rag-bench/online-tutorials huggingface dataset:
PyQt5 QLabel - Setting blur radius to the blur effect - GeeksforGeeks

10 May, 2020
In this article we will see how we can set blur radius to the label blur effect, The blur radius (required), if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be. By default the blur radius value is 5.0 we can change it any time.
In order to do this we use setBlurRadius method.
Syntax : blur_effect.setBlurRadius(n)Here blur_effect is the QGraphicsBlurEffect object
Argument : It takes float value as argument
Return : It returns None
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 blur effect        self.blur_effect = QGraphicsBlurEffect()            # setting blur radius        self.blur_effect.setBlurRadius(15)          # adding blur effect to the label        label.setGraphicsEffect(self.blur_effect)    # 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
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Number Representation - GeeksforGeeks

12 Mar, 2018
P is a 16-bit signed integer. The 2's complement representation of P is (F87B)16.The 2's complement representation of 8*P 
(C3D8)16 
(187B)16 
(F878)16 
(987B)16 
P = (F87B)16 is -1111 1000 0111 1011 in binary Note that most significant bit in the binary representation is 1, which implies that the number is negative. To get the value of the number performs the 2's complement of the number. We get P as -1925 and 8P as -15400 Since 8P is also negative, we need to find 2's complement of it (-15400) Binary of 15400 = 0011 1100 0010 1000 2's Complement = 1100 0011 1101 1000 = (C3D8)16 
xy=30
possible combinations =(1,30),(2,15),(3,10)
Since No is negative S bit will be 1
Convert 14.25 into binary 1110.01
Normalize it : 1.11001 X 2 ^ 3
Biased Exponent (Add 127) : 3 + 127 = 130 (In binary 10000010)
Mantissa : 110010.....0 (Total 23 bits)

Num represented in IEEE 754 single precision format :

1 10000010 11001000000000000000000

In Hex (Group of Four bits) -

1100 0001 0110 0100 0000 0000 0000 0000

Num becomes : C1640000

0001 =1
1010 =A
1111 =F
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is Transmission Control Protocol (TCP)?
How to Calculate Number of Host in a Subnet?
Python OpenCV - Canny() Function
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
Replace Negative Number by Zeros in Pandas DataFrame - GeeksforGeeks

05 Sep, 2020
In this article, Let’s discuss how to replace the negative numbers by zero in Pandas 
Approach:
Import pandas module.
Create a Dataframe.
Check the DataFrame element is less than zero, if yes then assign zero in this element.
Display the final DataFrame
 First, let’s create the dataframe.
Python3
# importing pandas moduleimport pandas as pd  # Creating pandas DataFramedf = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6],                   "B": [3, -5, -6, 7, 3, -2],                   "C": [-4, 5, 6, -7, 5, 4],                   "D": [34, 5, 32, -3, -56, -54]})  # Displaying the original DataFrameprint("Original Array : ")df
Output :
Now, let’s find the negative element and replace it with zero.
Python3
# checking the element is < 0df[df < 0] = 0print("New Array :")df
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
How to use Plotly.js in React to Visualize and Interact with Your Data | by Ran (Reine) | Towards Data Science

I’ve written a tutorial on how to visualize interactive 3D networks (or data) with Python Plotly a few months ago and thought maybe it’ll be a good idea to write another one for Plotly.js.
One of the reasons why someone might prefer Plotly.js over Python Plotly could be because of loading speeds — I’ve once written a React + Flask application (where the datasets and Plotly figures are on Flask) and when I compared it to my React + Plotly.js application, interactivity and loading speeds are much better with Plotly.js.
So here’s a quick tutorial on how to use Plotly.js with React! ʕ•́ᴥ•̀ʔっ♡
The final codes for this tutorial can be found in this GitHub repository: https://github.com/Reine0017/mini-tutorials/tree/master/React-Tutorials/visualize-data-plotly.
Let’s start off with a basic React application. In your desired project directory, run:
npx create-react-app .
Then run:
npm start
to bring up the web page.
Next, we’ll want to install the Plotly.js library. You can refer to this link for installation instructions. But basically, you’ll want to just run (from their npm package page linked above):
npm install react-plotly.js plotly.js
Okay now that installation is done, let’s begin writing some codes!
There are TONS of different plots, maps and charts that you can play with with Plotly. In this tutorial, we’ll look at how to create a simple helix-shaped interactive 3D scatter plot with Plotly.js.
Let’s start off by creating the Plotly component and then importing the react-plotly library. After that, just type in the <Plot/> component like so:
Once we import it into our App.js file,
Here’s what it brings up:
Now, let’s populate the graph with some data. You can check out their official site to see what kinds of visualizations you can create with Plotly too.
Since we want to create a Helix 3D graph in this tutorial, we’ll first get the x, y, and z data coordinates for this 3D graph:
Next, let’s populate our <Plot/> component with this data.
There are way more parameters that you can play with for your desired diagram. But in this case, I only made some minor modifications to it. Here’s the final result:
This 3D scatter plot is fully interactive and you can configure certain actions too when a user clicks on it. For demo purposes, I’ll just make it console log its coordinates onClick.
To register a user’s clicks (on the coordinate points in the diagram), we can just write something like:
onClick={(data) => {  console.log(data.points[0])}}
inside the <Plot/> component.
Here’s the final result:
That’s it for today’s tutorial! Hope it was helpful and please feel free to comment or message me if you have any questions at all. Thank you guys for reading this and happy
How to create a database in MongoDB using Java?

There is no separate method to create a MongoDB database in Java, you can create a database by invoking the getDatabase() method of the com.mongodb.MongoClient class.
import com.mongodb.MongoClient;
public class CreatingDatabase {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      @SuppressWarnings("resource")
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Accessing the database
      mongo.getDatabase("myDatabase1");
      mongo.getDatabase("myDatabase2");
      mongo.getDatabase("myDatabase3");
      System.out.println("Databases created successfully");
   }
}
Databases created successfully
PHP date() Function

The date() function accepts a format string as a parameter, formats the local date/time in the specified format and returns the result.
date($format, $timestamp)

format (Mandatory)
This is a format string specifying the format in which you want the output date string to be.
timestamp (Optional)
 This is an integer value representing the timestamp of the required date
PHP date() function returns the current local time/date in the specified format.
This function was first introduced in PHP Version 4 and, works with all the later versions.
Try out following demonstrates the usage of the date() function −
<?php
   $date = date("D M d Y");
   print("Date: ".$date);
?>
This will produce following result −
Date: Fri May 08 2020

You can escape characters in a date format as shown below −
<?php
   $date = date("jS F l \t");
   print("Date: ".$date);
?>
This will produce following result −
Date: 18th May Monday

Following example invokes the date() function by passing the timestamp parameter −
<?php
   $ts = 1022555568;
   $date = date("D M d Y", $ts);
   print($date);
?>
This will produce following result −
Tue May 28 2002

<?php
   date_default_timezone_set('UTC');
   
   echo date("l");
   echo "";
   
   echo date('l dS \of F Y h:i:s A');
   echo "";
?>
This produces the following result −
Monday
Monday 05th of December 2016 10:27:13 AM

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Python | Custom sorting in list of tuples

11 May, 2020
Sometimes, while working with list of tuples, we can have a problem in which we need to perform it’s sorting. Naive sorting is easier, but sometimes, we have to perform custom sorting, i.e by decreasing order of first element and increasing order of 2nd element. And these can also be in cases of different types of tuples. Let’s discuss certain cases and solutions to perform this kind of custom sorting.
Method #1 : Using sorted() + lambdaThis task can be performed using the combination of above functions. In this, we just perform the normal sort, but in addition we feed a lambda function which handles the case of custom sorting discussed above.
# Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda  # Initializing listtest_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]  # printing original listprint("The original list is : " + str(test_list))  # Custom sorting in list of tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))  # printing resultprint("The tuple after custom sorting is : " + str(res))
The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
The tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]

 
Method #2 : Using sorted() + lambda() + sum() ( With sum of tuple condition)In this method, similar solution sustains. But the case here is that we have tuple as the 2nd element of tuple and its sum has to considered for sort order. Other functions than summation can be extended in similar solution.
# Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda() + sum()  # Initializing listtest_list = [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]  # printing original listprint("The original list is : " + str(test_list))  # Custom sorting in list of tuples# Using sorted() + lambda() + sum()res = sorted(test_list, key = lambda sub: (-sub[0], sum(sub[1])))  # printing resultprint("The tuple after custom sorting is : " + str(res))
The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]
The tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))]

Python list-programs
Python tuple-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How Change the vertical spacing between legend entries in Matplotlib?

13 Jan, 2021
Prerequisites: Matplotlib
In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph.
Approach:
Import required module.
Create data.
Change the vertical spacing between labels.
Normally plot the data.
Display plot.
Implementation:
Example 1:
In this example, we will draw different lines with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels.
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np  # create dataX = [1, 2, 3, 4, 5]Y = [3, 3, 3, 3, 3]  # plot linesplt.plot(X, Y, label = "Line-1")plt.plot(Y, X, label = "Line-2")plt.plot(X, np.sin(X), label = "Curve-1")plt.plot(X, np.cos(X), label = "Curve-2")  # Change the label spacing hereplt.legend(labelspacing = 3)plt.title("Line Graph - Geeksforgeeks")  plt.show()
Output:
Example 2:
In this example, we will draw a Vertical line with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels.
Python3
# importing packageimport matplotlib.pyplot as plt  #Create data and plot lines.plt.plot([0, 1], [0, 2.0], label = 'Label-1')plt.plot([1, 2], [0, 2.1], label = 'Label-2')plt.plot([2, 3], [0, 2.2], label = 'Label-3')  # Change the label spacing hereplt.legend(labelspacing = 2)plt.title("Line Graph - Geeksforgeeks")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2017 (Set 2) | Question 49

28 Jun, 2021
Consider the following C function.
int fun(int n)
{
    int i, j;
    for (i = 1; i <= n ; i++)
    {
        for (j = 1;  j < n; j += i)
        {
            printf("%d %d", i, j);
        }
    }
}

Time complexity of fun in terms of θ notation is:(A) θ(n √n)(B) θ(n2)(C) θ(n log n)(D) θ(n 2 log n)
Answer: (C)Explanation: Let us see how many times the innermost statement “printf(“%d %d”, i, j);” is executed.
For i = 1, the statement runs n timesThe i’th iteration, statement runs Θ(n/i) times.
Summing all iterations for i = 1 to n, we getThus T(n) = Θ(n(1 + 1/2 +1/3 + ....)) = Θ(n log n).
Note that the value of 1/1 + 1/2 + 1/3 + .... 1/n is approximately same as Log n for large values of n.Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js Introduction

24 Dec, 2021
p5.js is a JavaScript library used for creative coding. It is based on Processing which is a creative coding environment. The main focus of processing is to make it easy as possible for beginners to learn how to program interactive, graphical applications, to make a programming language more user-friendly by visualizing it.The advantage of using the JavaScript programming language is its broad availability and ubiquitous support: every web browser has a JavaScript interpreter built-in, which means that p5.js programs can be run on any web browser.Also, Processing is that language which emphasizes on feasibility for programmers to create software prototypes very quickly, to try out a new idea or see if something works. For this reason, Processing (and p5.js) programs are generally referred to as “sketches.”
Preferred Editors The official documentation of p5.js suggests to use Bracket or Sublime and then include the JavaScript files, finally lead us to work like any other programming language. But the online p5.js Web Editor is the best alternative. It is based on a web-based programming environment.
Difference between P5.js and JavaScript?JavaScript is a core language that provides all the features to build any functionalities into browsers. It can use Loop, Function, Conditional, DOM Manipulation, events, canvas, etc. Hence, by using it to develop and design any framework.p5.js is a library of JavaScript. P5.js is running on Pure JavaScript provides some functions that make JavaScript user life easy to draw in the web. Example:
function setup() {  createCanvas(400, 400); //Canvas size 400*400}  function draw() {  background('blue'); //background color blue}
Output:
setup(): It is the statements in the setup() function. It executes once when the program begins. createCanvas must be the first statement.draw(): The statements in the draw() are executed until the program is stopped. Each statement is executed in sequence and after the last line is read, the first line is executed again.
Reference: https://p5js.org/
Lauren McCarthy (creator of p5.js)
Cassie Tarakajian (creator of p5.js web editor)
sarthak_ishu11
JavaScript-p5.js
Technical Scripter 2018
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Gerrit - Download Examples Using Git

You can download the example using Git along with the source code of any project organized at gerrit.wikimedia.org using the following Git Bash command.
$ git clone 
ssh://<user_name>@gerrit.wikimedia.org:29418/sandbox

The git clone command clones a directory into a new directory; in other words gets a copy of an existing repository. When you run the above command,it will clone the 'examples' repository and receives the objects, files, etc. from that repository and stores it in your local branch.
 Print
 Add Notes
 Bookmark this page
Java program to display Hostname and IP address

To display Hostname and IP address in Java, the code is as follows −
 Live Demo
import java.net.*;
public class Demo{
   public static void main(String[] args){
      try{
         InetAddress my_address = InetAddress.getLocalHost();
         System.out.println("The IP address is : " + my_address.getHostAddress());
         System.out.println("The host name is : " + my_address.getHostName());
      }
      catch (UnknownHostException e){
         System.out.println( "Couldn't find the local address.");
      }
   }
}
The IP address is : 127.0.0.1
The host name is : jdoodle
A class named Demo contains the main function. In this main function, a ‘try’ and ‘catch’ block is defined. In the ‘try’ block, an instance of InetAddress is created and the ‘getLocalHost’ function is used to get the Host address and host name of the InetAddress instance. In case one of the attributes is not found, the ‘catch’ block defines catching the exception and printing the relevant message on the console.
How to display current connection info in MySQL?

MySQL provides many functions that give the current connection information. For instance, to know about the current user, use the user() function.
mysql> SELECT CURRENT_USER();

Here is the output that displays the name of the current user.
+----------------+
| CURRENT_USER() |
+----------------+
| root@%         |
+----------------+
1 row in set (0.00 sec)

In the above, % tells us about localhost.
To check the current connection id, use the following method −
mysql> SELECT CONNECTION_ID();
The following is the output that shows the current connection id.
+-----------------+
| CONNECTION_ID() |
+-----------------+
|               8 |
+-----------------+
1 row in set (0.02 sec)

The following is the syntax to check all the current information with a single command.
mysql> status;
The following is the output −
--------------
C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe  Ver 8.0.12 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          8
Current database:       business
Current user:           root@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         8.0.12 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    cp850
Conn.  characterset:    cp850
TCP port:               3306
Uptime:                 1 hour 11 min 24 sec

Threads: 2  Questions: 26  Slow queries: 0  Opens: 129  Flush tables: 2  Open tables: 105  Queries per second avg: 0.006
--------------
Align a flex item at the end in Bootstrap 4

Use the .align-self-end class to align flex item at the end in Bootstrap 4.
The following is my div −
<div class="d-flex bg-info" style="height:200px">
Now you need to set the flex items, wherein I am aligning the 3rd flex item −
<div class="d-flex bg-info" style="height:200px">
  <div class="p-2 border">Item 1</div>
  <div class="p-2 border">Item 2</div>
  <div class="p-2 border align-self-end">Item 3</div>
  <div class="p-2 border">Item 4</div>
</div>
You can try to run the following code to implement the align-self-end class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
<body>
  <div class="container mt-3">
    <h1>Align Specific Flex Item from the end</h1>
      <div class="d-flex bg-info" style="height:200px">
        <div class="p-2 border">Item 1</div>
        <div class="p-2 border">Item 2</div>
        <div class="p-2 border align-self-end">Item 3</div>
        <div class="p-2 border">Item 4</div>
      </div>
  </div>
 </body>
</html>
JavaScript String - substr() Method

This method returns the characters in a string beginning at the specified location through the specified number of characters.
The syntax to use substr() is as follows −
string.substr(start[, length]);

start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string).
start − Location at which to start extracting characters (an integer between 0 and one less than the length of the string).
length − The number of characters to extract.
length − The number of characters to extract.
Note − If start is negative, substr uses it as a character index from the end of the string.
The substr() method returns the new sub-string based on given parameters.
Try the following example.
<html>
   <head>
      <title>JavaScript String substr() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = "Apples are round, and apples are juicy.";         
         document.write("(1,2): "    + str.substr(1,2));
         document.write("<br />(-2,2): "   + str.substr(-2,2));
         document.write("<br />(1): "      + str.substr(1));
         document.write("<br />(-20, 2): " + str.substr(-20,2));
         document.write("<br />(20, 2): "  + str.substr(20,2));
      </script>      
   </body>
</html>
(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d


    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
Java String codePointBefore() Method

❮ String Methods

Return the Unicode of the first character in a string (the Unicode value 
  of "H" is 72):
String myStr = "Hello";
int result = myStr.codePointBefore(1);
System.out.println(result);

Try it Yourself »

The codePointBefore() method returns the Unicode 
value of the character before the specified index in a string.
The index of the first character is 1, the second character is 2, and so on.
Note: The value 0 will generate an error, as this is a negative number (out 
of reach).
public int codePointBefore(int index)

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
JSTL - fn:replace() Function

The fn:replace() function replaces all occurrences of a string with another string.
The fn:replace () function has the following syntax −
boolean replace(java.lang.String, java.lang.String, java.lang.String)

Following is the example to explain the functionality of the fn:replace() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<html>
   <head>
      <title>Using JSTL Functions</title>
   </head>

   <body>
      <c:set var = "string1" value = "This is first String."/>
      <c:set var = "string2" value = "${fn:replace(string1, 'first', 'second')}" />
      <p>Final String : ${string2}</p>
   </body>
</html>
You will receive the following result −
Final String : This is second String.


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Program to find minimum swaps required to make given anagram in python

Suppose we have two strings S and T and they are anagrams of each other. We have to find the minimum number of swaps required in S to make it same as T.
So, if the input is like S = "kolkata" T = "katloka", then the output will be 3, as can swap in this sequence [katloka (given), kotlaka, koltaka, kolkata].
To solve this, we will follow these steps −
Define a function util() . This will take S, T, i
if i >= size of S , thenreturn 0
return 0
if S[i] is same as T[i], thenreturn util(S, T, i + 1)
return util(S, T, i + 1)
x := T[i]
ret := 99999
for j in range i + 1 to size of T, doif x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j]
if x is same as S[j], thenswap S[i] and S[j]ret := minimum of ret and (1 + util(S, T, i + 1))swap S[i] and S[j]
swap S[i] and S[j]
ret := minimum of ret and (1 + util(S, T, i + 1))
swap S[i] and S[j]
return ret
From the main method do the following:
return util(S, T, 0)
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
   def util(self, S, T, i) :
      S = list(S)
      T = list(T)
      if i >= len(S):
         return 0
      if S[i] == T[i]:
         return self.util(S, T, i + 1)
      x = T[i]
      ret = 99999;
      for j in range(i + 1, len(T)):
         if x == S[j]:
            S[i], S[j] = S[j], S[i]
            ret = min(ret, 1 + self.util(S, T, i + 1))
            S[i], S[j] = S[j], S[i]
      return ret
     
   def solve(self, S, T):
      return self.util(S, T, 0)

ob = Solution()
S = "kolkata"
T = "katloka"
print(ob.solve(S, T))
"kolkata", "katloka"
3
How can we import data from .CSV file into MySQL table?

Actually.CSV is also a text file in which the values are separated by commas or in other words we can say that text file with CSV(comma separated values). We need to use FIELDS SEPARATED OPTION with LOAD DATA INFILE statement while importing the data from .CSV file to MySQL table. We are considering the following example to make it understand −
Followings are the comma separated values in A.CSV file −
105,Chum,USA,11000
106,Danny,AUS,12000
We want to import this data into the following file named employee1_tbl −
mysql> Create table employee1_tbl(Id Int, Name Varchar(20), Country Varchar(20),Salary Int);

Query OK, 0 rows affected (0.91 sec)
Now, the transfer of data from a file to a database table can be done with the help of the following table −
mysql> LOAD DATA LOCAL INFILE 'd:\A.csv' INTO table employee1_tbl FIELDS TERMINATED BY ',';
Query OK, 2 rows affected (0.16 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0

mysql> Select * from employee1_tbl;
+------+-------+---------+--------+
| Id   | Name  | Country | Salary |
+------+-------+---------+--------+
| 105  | Chum  | USA     |  11000 |
| 106  | Danny | AUS     |  12000 |
+------+-------+---------+--------+
2 rows in set (0.00 sec)
The above result set shows that the data from A.CSV file has been transferred to the table.
Compressing string in JavaScript

We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters.
The function should compress the string like this −
'wwwaabbbb' -> 'w3a2b4'
'kkkkj' -> 'k4j'
And if the length of the compressed string is greater than or equal to the original string we should return the original string.
For example −
'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab'
The code for this will be −
 Live Demo
const str1 = 'wwwaabbbb';
const str2 = 'kkkkj';
const str3 = 'aab';
const compressString = (str = '') => {
   let res = '';
   let count = 1;
   for(let i = 0; i < str.length; i++){
      let cur = str[i];
      let next = str[i + 1];
      if(cur === next){
         count++;
      }else{
         res += cur + String(count);
         count = 1;
      };
   }
   return res.length < str.length ? res : str;
};
console.log(compressString(str1));
console.log(compressString(str2));
console.log(compressString(str3));
And the output in the console will be −
3a2b4
k4j1
aab
Scope of Variables in C#

The scope of a variable is a region of code that indicates where the variables are being accessed.
For a variable, it has the following levels −
Variable declared inside a method is a local variable.
Variable declared inside a class is a local variable are class member variables.
Let us see an example of scope of variables −
 Live Demo
using System;

namespace Demo {
   class Program {
      public int Divide(int num1, int num2) {
         // local variable in a method
         int result;
         result = num1 / num2;
         return result;
      }
      static void Main(string[] args) {
         // local variable
         int a = 150;
         int b = 10;
         int res;
         Program p = new Program();
         res = p.Divide(a, b);
         Console.WriteLine("Division Result = {0}", res );
         Console.ReadLine();
      }
   }
}
Division Result = 15
TypeScript - Array every()

every() method tests whether all the elements in an array passes the test implemented by the provided function.
array.every(callback[, thisObject]);

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns true if every element in this array satisfies the provided testing function.
function isBigEnough(element, index, array) { 
   return (element >= 10); 
} 
          
var passed = [12, 5, 8, 130, 44].every(isBigEnough); 
console.log("Test Value : " + passed );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Test Value : false


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Django model data to JSON data in 2 lines

In this article, we are going to learn a handy trick to convert Django model data directly to JSON data. Sometimes, we need to return model data in JSON format; it can also be used in making API or just showing simple data to our frontend in JSON format. JSON is easy to access so it is really handful.
Create a Django project and an app.
In settings.py, add the app name in INSTALLED_APPS.
In urls.py of the Project main directory, add the following lines −
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
   path('admin/', admin.site.urls),
   path('',include('modeltojson.urls'))
]
Here we added our app's urls.py.
In the App's urls.py, add the following lines −
from django.urls import path
from . import views
urlpatterns = [
   path('',views.home,name="home")
]
Here we rendered our home view, which is simple.
In models.py, add the following lines −
from django.db import models

# Create your models here.
class EmployeeData(models.Model):
   name=models.CharField(max_length=100)
   Salary=models.CharField(max_length=100)
   department=models.CharField(max_length=100)
Here, we created our model and add some dummy data for testing and trying.
In admin.py, add the following lines −
from django.contrib import admin
from .models import EmployeeData

# Register your models here.
admin.site.register(EmployeeData)
Here, we simply registered our EmployeeData model in admin page.
In views.py, add the following lines
from django.http import JsonResponse
from .models import EmployeeData
# Create your views here.
def home(request):
   data=list(EmployeeData.objects.values())
   return JsonResponse(data,safe=False)
Here, we created a list of all key-values using .value() function of our model data and then we rendered it as a JSON response.
Now it is all done, don't forget to add some random data.
[
   {
      "id": 1,
      "name": "Ross Taylor",
      "Salary": "1 lakh",
      "department": "Technical"
   },
   {
      "id": 2,
      "name": "Rohit Sharma",
      "Salary": "2 lakh",
      "department": "Sales"
   },
   {
      "id": 3,
      "name": "Steve Smith",
      "Salary": "3 lakh",
      "department": "Sales"
   }
]
XSLT <template>

<xsl:template> defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context.
Following is the syntax declaration of <xsl:template> element.
<xsl:template 
   name = Qname 
   match = Pattern 
   priority = number 
   mode = QName >
</xsl:template>

name
Name of the element on which template is to be applied.
match
Pattern which signifies the element(s) on which template is to be applied.
priority
Priority number of a template. Matching template with low priority is not considered in from in front of high priority template.
mode
Allows element to be processed multiple times to produce a different result each time.
Parent elements
xsl:stylesheet, xsl:transform
Child elements
xsl:apply-imports,xsl:apply-templates,xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:param, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements
This template rule has a pattern that identifies <student> elements and produces an output in a tabular format.
students.xml
<?xml version = "1.0"?> 
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?> 
<class> 
   <student rollno = "393"> 
      <firstname>Dinkar</firstname> 
      <lastname>Kad</lastname> 
      <nickname>Dinkar</nickname> 
      <marks>85</marks> 
   </student> 
   <student rollno = "493"> 
      <firstname>Vaneet</firstname> 
      <lastname>Gupta</lastname> 
      <nickname>Vinni</nickname> 
      <marks>95</marks> 
   </student> 
   <student rollno = "593"> 
      <firstname>Jasvir</firstname> 
      <lastname>Singh</lastname> 
      <nickname>Jazz</nickname> 
      <marks>90</marks> 
   </student> 
</class>
students_imports.xsl
<?xml version = "1.0" encoding = "UTF-8"?> 
<xsl:stylesheet version = "1.0" 
   xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">  
	
   <xsl:template match = "/"> 
      <html> 
         <body> 
            <h2>Students</h2> 
            <table border = "1"> 
               <tr bgcolor = "#9acd32"> 
                  <th>Roll No</th> 
                  <th>First Name</th> 
                  <th>Last Name</th> 
                  <th>Nick Name</th> 
                  <th>Marks</th> 
               </tr>
					
               <xsl:for-each select = "class/student"> 
                  <tr> 
                     <td><xsl:value-of select = "@rollno"/></td> 
                     <td><xsl:value-of select = "firstname"/></td> 
                     <td><xsl:value-of select = "lastname"/></td> 
                     <td><xsl:value-of select = "nickname"/></td> 
                     <td><xsl:value-of select = "marks"/></td>
                  </tr> 
               </xsl:for-each> 
            </table> 
         </body> 
      </html> 
   </xsl:template>  
</xsl:stylesheet>
 Print
 Add Notes
 Bookmark this page
plotly.express.line() function in Python - GeeksforGeeks

20 Jul, 2020
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use.
This function is used to create a line plot. It can also be created using the pandas dataframe where each row of data_frame is represented as vertex of a polyline mark in 2D space.
Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame: DataFrame or array-like or dict needs to be passed for column names.
x, y: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x and y axis in cartesian coordinates respectively. 
color: This parameters assign color to marks.
line_group: This parameter is used to group rows of data_frame into lines.
line_dash: This parameter is used to assign dash-patterns to lines.
hover_name:  Values from this column or array_like appear in bold in the hover tooltip.
hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip.
Example 1:
Python3
import plotly.express as px  df = px.data.tips()  plot = px.line(df, x = 'day', y = 'time')plot.show()
Output:
Example 2: Using color argument
Python3
import plotly.express as px  df = px.data.tips()  plot = px.line(df, x = 'time',                y = 'total_bill',               color = 'sex')plot.show()
Output:
Example 3: Using the line_group argument
Python3
import plotly.express as px  df = px.data.tips()  plot = px.line(df, x = 'time',               y = 'total_bill',               color = 'sex',                line_group = 'day')  plot.show()
Output:
Python Plotly express-class
Python-Plotly
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
C Program for focal length of a lens

Given two floating values; image distance and object distance from a lens; the task is to print the focal length of the lens.
What is focal length?
Focal length of an optical system is the distance between the center of lens or curved mirror and its focus.
Let’s understand with the help of figure given below −
In the above figure i is the object, and F is the image of the object which is formed and f is the focal length of the image.
So to find the focal length of the image from the lens the formula is −
1F= 1O+1I
Where, F is the focal length.
O is the total distance of the lens and the object.
I is the total distance between lens and the image formed by the lens.
Input: image_distance=5, object_distance=10
Output: Focal length of a lens is: 3.333333
Explanation: 1/5 + 1/10 = 3/10🡺 F = 10/3 = 3.33333333

Input: image_distance = 7, object_distance = 10
Output: Focal length of a lens is: 4.1176470
Approach we are using to solve the above problem −
Take the input of the image_disance and object_distance.
Find the sum 1/image_distance and 1/object_distance and return the result divided by 1.
Print the result.
Start
Step 1-> In function float focal_length(float image_distance, float object_distance)
   Return 1 / ((1 / image_distance) + (1 / object_distance))

Step 2-> In function int main()
   Declare and initialize the first input image_distance = 5
   Declare and initialize the second input object_distance = 10
   Print the results obtained from calling the function focal_length(image_distance, object_distance)
Stop
 Live Demo
#include <stdio.h>
// Function to find the focal length of a lens
float focal_length(float image_distance, float object_distance) {
   return 1 / ((1 / image_distance) + (1 / object_distance));
}
// main function
int main() {
   // distance between the lens and the image
   float image_distance = 5;
   // distance between the lens and the object
   float object_distance = 10;
   printf("Focal length of a lens is: %f\n", focal_length(image_distance, object_distance));
   return 0;
}
Focal length of a lens is: 3.333333
C/C++ Program to find sum of elements in a given array - GeeksforGeeks

28 Aug, 2018
Given an array of integers, find sum of its elements.
Examples :
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

/* CPP Program to find sum of elements in a given array */#include <bits/stdc++.h>  // function to return sum of elements// in an array of size nint sum(int arr[], int n){    int sum = 0; // initialize sum      // Iterate through all elements     // and add them to sum    for (int i = 0; i < n; i++)    sum += arr[i];      return sum;}  int main(){    int arr[] = {12, 3, 4, 15};    int n = sizeof(arr) / sizeof(arr[0]);    printf("Sum of given array is %d", sum(arr, n));    return 0;}
Please refer complete article on Program to find sum of elements in a given array for more details!
CBSE - Class 11
school-programming
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Shallow Copy and Deep Copy in C++
delete keyword in C++
Passing a function as a parameter in C++
Different Media Types in CSS

CSS Media Types are the device types on which the document is rendered and specific styles can be defined for every media type.
Following are the Media Types in CSS3 and Media Queries 4 −
NOTE −Several media types (such as aural, braille, embossed, handheld, projection, ttv and tv) are deprecated in Media Queries 4 and shouldn't be used. The aural type has been replaced by speech media type.
Let’s see an example for styling screen and print media types −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="screen.css">
<link rel="stylesheet" type="text/css" media="print" href="print.css">
</head>
<body>
<div></div>
</body>
</html>
div {
   height: 50px;
   width: 100px;
   border-radius: 20%;
   border: 2px solid blueviolet;
   box-shadow: 22px 12px 3px 3px lightblue;
   position: absolute;
   left: 30%;
   top: 20px;
}
CSS document (print.css):
div {
   height: 50px;
   width: 100px;
   border-radius: 20%;
   border: 2px solid #dc3545;
   box-shadow: 22px 12px 3px 3px #dc3545;
   position: absolute;
   left: 30%;
   top: 20px;
}
When document is visible in a screen mediatype −
When document is visible in a print mediatype −
Let’s see another example for styling screen and print media types −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
@import url(screen.css) screen;
@import url(print.css) print;
</style>
</head>
<body>
<p> Vivamus commodo, dolor eu porttitor sagittis, orci nisl consectetur ipsum, vel volutpat nibh lectus at erat. Cras scelerisque faucibus tellus aliquam commodo.Donec sem urna, facilisis at ipsum id, viverra sollicitudin est. Nam rhoncus sollicitudin lorem, a accumsan purus varius eget. </p>
<p class="two">In ultrices lectus nisi. Nulla varius ex ut tortor congue viverra. Sed sodales vehicula leo, vitae interdum elit vehicula nec. Donec turpis nunc, iaculis et nisi sit amet, feugiat lacinia metus. </p>
<p>Suspendisse eget ligula et risus lobortis ornare id at elit. Suspendisse potenti. Vivamus pellentesque eleifend pellentesque. Vestibulum neque ante, iaculis a sagittis et, fermentum at metus.</p>
</body>
</html>
p { color: navy; font-style: italic; }
.two { color: #c303c3; font-size: 20px; }
body { background-color: honeydew;}
CSS document (print.css):
p { color: red; font-style: italic;}
.two { color: #989898; font-size: 40px; }
When document is visible in a screen mediatype −
When document is visible in a print mediatype −
Create a Pivot Table with multiple columns – Python Pandas

We can create a Pivot Table with multiple columns. To create a Pivot Table, use the pandas.pivot_table to create a spreadsheet-style pivot table as a DataFrame.
At first, import the required library −
import pandas as pd
Create a DataFrame with Team records −
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
Create a Pivot Table with multiple columns. We have set more than more than two columns −
pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"])
Following is the code −
import pandas as pd

# create DataFrame with Team records
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})

print("\n... Pivot ...")

# multiple columns
print(pd.pivot_table(dataFrame, index = ["Team ID", "Team Name", "Team Rank"]))
This will produce the following output −
... Pivot ...
                                  Team Points
Team ID  Team Name    Team Rank
2        Sri Lanka    Three                80
5        India        One                  95
6        Bangladesh   Six                  42
7        England      Five                 55
9        Australia    Two                  93
11       South Africa Four                 60