code-rag-bench/online-tutorials huggingface dataset:
How to subset rows of data frame without NA using dplyr in R?

To subset rows of data frame without NA using dplyr in R, we can follow the below steps −
First of all, create a data frame.
Then, use filter function of dplyr package to subset the rows with !is.na.
Let's create a data frame as shown below −
 Live Demo
x<-sample(c(NA,1,2),20,replace=TRUE)
df<-data.frame(x)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  x
1 2
2 2
3 1
4 1
5 1
6 NA
7 1
8 NA
9 NA
10 1
11 1
12 1
13 2
14 1
15 NA
16 2
17 2
18 2
19 NA
20 1
Using filter function of dplyr package to subset the rows of df with !is.na as shown below −
x<-sample(c(NA,1,2),20,replace=TRUE)
df<-data.frame(x)
library(dplyr)
df %>% filter(!is.na(x))
  x
1 2
2 2
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 2
11 1
12 2
13 2
14 2
15 1
How to sort array according to age in JavaScript?

We are required to write a JavaScript function that takes in an array of numbers representing
ages of some people.
Then the function should bring all the ages less than 18 to the front of the array without using any extra memory.
The code for this will be −
const ages = [23, 56, 56, 3, 67, 8, 4, 34, 23, 12, 67, 16, 47];
const sorter = (a, b) => {
   if (a < 18) {
      return -1;
   };
   if (b < 18) {
      return 1;
   };
   return 0;
}
const sortByAdults = arr => {
   arr.sort(sorter);
};
sortByAdults(ages);
console.log(ages);
The output in the console −
[
   16, 12, 4, 8, 3, 23, 56,
   56, 67, 34, 23, 67, 47
]
Python - Itertools.Product() - GeeksforGeeks

04 Sep, 2021
In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B. Consider the below example for better understanding.Examples:
Input : arr1 = [1, 2, 3] arr2 = [5, 6, 7] Output : [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] Input : arr1 = [10, 12] arr2 = [8, 9, 10] Output : [(10, 8), (10, 9), (10, 10), (12, 8), (12, 9), (12, 10)]  
The above solution can be done by looping but we will use a special Python library itertools.product() for finding the Cartesian Product. Let’s go through the working and use cases of this Python library. 
Python Itertools is a library in Python which consists of multiple methods that are used in various iterators to compute a fast and code efficient solution. 
itertools.product() falls under the category called Combinatoric iterators of the Python itertools library.
Note: For more information, refer to Python Itertools 
itertools.product() is used to find the cartesian product from the given iterator, output is lexicographic ordered. The itertools.product() can used in two different ways:
itertools.product(*iterables, repeat=1):It returns the cartesian product of the provided iterable with itself for the number of times specified by the optional keyword “repeat”. For example, product(arr, repeat=3) means the same as product(arr, arr, arr).
itertools.product(*iterables):It returns the cartesian product of all the iterable provided as the argument. For example, product(arr1, arr2, arr3).
Example:
Python3
from itertools import product def cartesian_product(arr1, arr2):     # return the list of all the computed tuple    # using the product() method    return list(product(arr1, arr2))   # Driver Functionif __name__ == "__main__":    arr1 = [1, 2, 3]    arr2 = [5, 6, 7]    print(cartesian_product(arr1, arr2))
Output:
[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] 
sooda367
gabaa406
Python-itertools
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
Java String codePointCount() Method

❮ String Methods

Return the number of Unicode values found in a string:
String myStr = "Hello";
int result = myStr.codePointCount(0, 5);
System.out.println(result);

Try it Yourself »

The codePointCount() method returns the 
number of Unicode values found in a string.
Use the startIndex and endIndex parameters to specify where 
to begin and end the search.
The index of the first character is 0, the second character is 1, and so on.
public int codePointCount(int startIndex, int endIndex)

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.
Display the minimum and maximum value of primitive data types in Java

Every data type in Java has a minimum as well as maximum range, for example, for Float.
Min = 1.4E-45
Max = 3.4028235E38
Let’s say for Float, if the value extends the maximum range displayed above, it leads to Overflow.
However, if the value is less than the minimum range displayed above, it leads to Underflow.
The following is the Java Program to display the minimum and maximum value of primitive data types.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      System.out.println("Integer Datatype values...");
      System.out.println("Min = " + Integer.MIN_VALUE);
      System.out.println("Max = " + Integer.MAX_VALUE);

      System.out.println("Float Datatype values...");
      System.out.println("Min = " + Float.MIN_VALUE);
      System.out.println("Max = " + Float.MAX_VALUE);

      System.out.println("Double Datatype values...");
      System.out.println("Min = " + Double.MIN_VALUE);
      System.out.println("Max = " + Double.MAX_VALUE);

      System.out.println("Byte Datatype values...");
      System.out.println("Min = " + Byte.MIN_VALUE);
      System.out.println("Max = " + Byte.MAX_VALUE);

      System.out.println("Short Datatype values...");
      System.out.println("Min = " + Short.MIN_VALUE);
      System.out.println("Max = " + Short.MAX_VALUE);
   }
}
Integer Datatype values...
Min = -2147483648
Max = 2147483647
Float Datatype values...
Min = 1.4E-45
Max = 3.4028235E38
Double Datatype values...
Min = 4.9E-324
Max = 1.7976931348623157E308
Byte Datatype values...
Min = -128
Max = 127
Short Datatype values...
Min = -32768
Max = 32767
In the above program, we have taken each datatype one by one and used the following properties to get the minimum and maximum values. For example, datatype Short.
Short.MIN_VALUE;
Short.MAX_VALUE
The above returns the minimum and maximum value of Short datatype. In the same way, it works for other datatypes.
Min = -32768
Max = 32767
Create Hoverable Buttons with CSS

Use the CSS :hover selector to create hoverable buttons. You can try to run the following code to create hoverable buttons:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .btn {
            background-color: yellow;
            color: black;
            text-align: center;
            font-size: 15px;
            padding: 20px;
            border-radius: 15px;
            border: 3px dashed blue;
         }
         .btn:hover {
            background-color: orange;
            color: black;
            border: 3px solid blue;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <button class = "btn">Result</button>
   </body>
</html>
Example of createSignalingChannel() in HTML5

Web RTC required peer-to-peer communication between browsers. This mechanism required signalling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. An example of createSignalingChannel():
var signalingChannel = createSignalingChannel();
var pc;
var configuration = ...;

// run start(true) to initiate a call
function start(isCaller) {
   pc = new RTCPeerConnection(configuration);
   // send any ice candidates to the other peer
   pc.onicecandidate = function (evt) {
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
   };
   
   // once remote stream arrives, show it in the remote video element
   pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
   };

   // get the local stream, show it in the local video element and send it
   navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
      selfView.src = URL.createObjectURL(stream);
      pc.addStream(stream);
      if (isCaller)
         pc.createOffer(gotDescription);
      else
         pc.createAnswer(pc.remoteDescription, gotDescription);
      function gotDescription(desc) {
         pc.setLocalDescription(desc);
         signalingChannel.send(JSON.stringify({ "sdp": desc }));
      }
   });
}
signalingChannel.onmessage = function (evt) {
   if (!pc)
      start(false);
      var signal = JSON.parse(evt.data);
      if (signal.sdp)
      pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
   else
      pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
};
Filters in Linux - GeeksforGeeks

13 Jul, 2021
Filters are programs that take plain text(either stored in a file or produced by another program) as standard input, transforms it into a meaningful format, and then returns it as standard output. Linux has a number of filters. Some of the most commonly used filters are explained below: 
1. cat : Displays the text of the file line by line. 
Syntax:  
cat [path]
2. head : Displays the first n lines of the specified text files. If the number of lines is not specified then by default prints first 10 lines. 
Syntax:  
head [-number_of_lines_to_print] [path] 
3. tail : It works the same way as head, just in reverse order. The only difference in tail is, it returns the lines from bottom to up. 
Syntax:  
tail [-number_of_lines_to_print] [path]
4. sort : Sorts the lines alphabetically by default but there are many options available to modify the sorting mechanism. Be sure to check out the main page to see everything it can do. 
Syntax: 
sort [-options] [path]
5. uniq : Removes duplicate lines. uniq has a limitation that it can only remove continuous duplicate lines(although this can be fixed by the use of piping). Assuming we have the following data. 
Syntax: 
uniq [options] [path]
You can see that applying uniq doesn’t remove any duplicate lines, because uniq only removes duplicate lines which are together.  
When applying uniq to sorted data, it removes the duplicate lines because, after sorting data, duplicate lines come together. 
6. wc : wc command gives the number of lines, words and characters in the data. 
Syntax: 
wc [-options] [path]
In above image the wc gives 4 outputs as:  
number of lines
number of words
number of characters
path
7. grep : grep is used to search a particular information from a text file. 
Syntax: 
grep [options] pattern [path]
Below are the two ways in which we can implement grep.  
8. tac : tac is just the reverse of cat and it works the same way, i.e., instead of printing from lines 1 through n, it prints lines n through 1. It is just reverse of cat command. 
Syntax:  
tac [path] 
9. sed : sed stands for stream editor. It allows us to apply search and replace operation on our data effectively. sed is quite an advanced filter and all its options can be seen on its man page. 
Syntax: 
sed  [path]
The expression we have used above is very basic and is of the form ‘s/search/replace/g’  
In the above image, we can clearly see that Scooby is replaced by Scrapy. 
10. nl : nl is used to number the lines of our text data. 
Syntax: 
nl [-options] [path]
It can clearly be seen in the above image that the lines have been numbered 
princekhj555
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
Thread functions in C/C++
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Inspect live objects in Python

Functions in this module provide usefule information about live objects such as modules, classes, methods, functions, code objects etc. These functions perform type checking, retrieve source code, inspect classes and functions, and examine the interpreter stack.
getmembers()− This function returns all the members of an object in a list of name, value pairs sorted by name. If the optional predicate is supplied, only members for which the predicate returns a true value are included. getmodulename() −This function returns the name of the module named by the file path, without including the names of enclosing packages
We shall be using following script for understanding the behaviour of inspect module.
#inspect-example.py
'''This is module docstring'''
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
#class definitions
class parent:
   '''parent docstring'''
   def __init__(self):
      self.var='hello'
   def hello(self):
      print (self.var)
class child(parent):
   def hello(self):
      '''hello function overridden'''
      super().hello()
      print ("How are you?")
starts with '__'
>>> import inspect, inspect_example
>>> for k,v in inspect.getmembers(inspect_example):
      if k.startswith('__')==False:print (k,v)
child
hello
parent
>>>
Predicate is a logical condition applied to functions in inspect module. For example getmembers() function returns list of module's members for which given predicate condition is true. Following predicates are defined in inspect module
Here only class members in the module will be returned.
>>> for k,v in inspect.getmembers(inspect_example, inspect.isclass):
      print (k,v)
child <class 'inspect_example.child'>
parent <class 'inspect_example.parent'>
>>>
To retrieve members of a specified class 'child' −
>>> inspect.getmembers(inspect_example.child)
>>> x=inspect_example.child()
>>> inspect.getmembers(x)
The getdoc() function retrieves docstring of a module, class or function.
>>> inspect.getdoc(inspect_example)
'This is module docstring'
>>> inspect.getdoc(inspect_example.parent)
'parent docstring'
>>> inspect.getdoc(inspect_example.hello)
'hello docstring'
The getsource() function fetches the definition code of a function −
>>> print (inspect.getsource(inspect_example.hello))
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
>>> sign=inspect.signature(inspect_example.parent.hello)
>>> print (sign)
The inspect module also has a command line interface.
C:\Users\acer>python -m inspect -d inspect_example
Target: inspect_example
Origin: C:\python36\inspect_example.py
Cached: C:\python36\__pycache__\inspect_example.cpython-36.pyc
Loader: <_frozen_importlib_external.SourceFileLoader object at
0x0000029827BD0D30>
Following command returns source code of 'Hello()' function in the module.
C:\Users\acer>python -m inspect inspect_example:hello
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
Replace a string using StringBuilder

Set a String −
StringBuilder str = new StringBuilder("Fitness is important");
Use the Replace() method to replace a string −
str.Replace("important", "essential");
The following is the code to replace a string using StringBuilder −
 Live Demo
using System;
using System.Text;

class Demo {
   static void Main() {

      // Initial String
      StringBuilder str = new StringBuilder("Fitness is important");
      Console.WriteLine(str.ToString());

      // Replace
      str.Replace("important", "essential");

      // New String
      Console.WriteLine(str.ToString());
      Console.ReadLine();
   }
}
Fitness is important
Fitness is essential
How to print in same line in Python?

The print() method in Python automatically prints in the next line each time. The print() method by default takes the pointer to the next line.
 Live Demo
for i in range(5):
   print(i)
0
1
2
3
4
The print method takes an extra parameter end=” “ to keep the pointer on the same line.
The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.
print(“.....” , end=” “)
The end=” “ is used to print in the same line with space after each element. It prints a space after each element in the same line.
 Live Demo
for i in range(5):
   print(i,end=" ")
0 1 2 3 4
The end=”” is used to print on same line without space. Keeping the doube quotes empty merge all the elements together in the same line.
 Live Demo
for i in range(5):
   print(i,end="")
01234
The end=”,” is used to print in the same line with a comma after each element. We can use some other sign such as ‘.’ or ‘;’ inside the end parameter.
 Live Demo
for i in range(5):
   print(i,end=",")
   print(i,end=".")
0,1,2,3,4,
0.1.2.3.4.
Disable a list item in a Bootstrap list group

Use the .disabled class in Bootstrap to disable a list item in a list group in Bootstrap.
You can try to run the following code to disable a list item −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Beverages</h2>
         <div class = "list-group">
            <a href = "#" class = "list-group-item">Gatorade</a>
            <a href = "#" class = "list-group-item">Coca Cola</a>
            <a href = "#" class = "list-group-item">Pepsi</a>
            <a href = "#" class =" list-group-item disabled">Sting</a>
         </div>
      </div>
   </body>
</html>
How to create Database Connection in Perl?

Assuming we are going to work with MySQL database with Perl. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database.
You have created a database with a name TESTDB.
You have created a table with a name TEST_TABLE in TESTDB.
This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
Perl Module DBI is installed properly on your machine.
You have gone through MySQL tutorial to understand MySQL Basics.
Following is the example of connecting with MySQL database "TESTDB" −
#!/usr/bin/perl
use DBI
use strict;
my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "testuser";
my $password = "test123";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
If a connection is established with the datasource then a Database Handle is returned and saved into dbhforfurtheruseotherwisedbh is set to undef value and $DBI::errstr returns an error string.
To disconnect Database connection, use disconnect API as follows −
$rc = $dbh->disconnect or warn $dbh->errstr;
The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect.
CURDATE() Function in MySQL - GeeksforGeeks

23 Nov, 2020
CURDATE() function :This function in MySQL is used to return the current date. The date is returned to the format of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). This function equals the CURRENT_DATE() function.
Syntax :
CURDATE()

Parameter :
This method does not accept any parameter.
Returns :
It returns the current date.
Example-1 :
Getting the current date in the format of “YYYY-MM-DD” (string).
SELECT CURDATE();

Output :
2020-11-19

Example-2 :
Getting the date 1 day later than the current date in the format of YYYYMMDD (numeric).
SELECT CURDATE() + 1;

Output :
20201120

Example-3 :
Getting the date of 5 days before of current date in the format of YYYYMMDD (numeric).
SELECT CURDATE() + 5;

Output :
20201114

Application : 
This function is used to get the current date or the specified number of days before or after the current date in the two different formats of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). 
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
How to make surfaceview transparent in an Android App?

This example demonstrates how to make surfaceview transparent in an Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <SurfaceView
      android:id="@+id/cameraSurface"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />
   <ImageView
      android:id="@+id/IV_MASK"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/mask"
      android:background="@android:color/transparent"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
How to count distinct values in MySQL?

To count distinct values, you can use distinct in aggregate function count().
The syntax is as follows −
select count(distinct yourColumnName) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table DistinctDemo
   −> (
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)
For our example, let us insert duplicate records in the table. The query to insert records is as follows −
mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.10 sec)
Display all records with the help of select statement. The query to display all records is as follows −
mysql> select *from DistinctDemo;
The following is the output displaying some duplicate records −
+---------+
| Name    |
+---------+
| John    |
| Sam     |
| John    |
| Johnson |
| John    |
| Johnson |
| Sam     |
| Johnson |
+---------+
8 rows in set (0.00 sec)
Here is the query that can be used to count distinct values from the table −
mysql> select count(distinct Name) as DistinctValues from DistinctDemo;
The following is the output −
+----------------+
| DistinctValues |
+----------------+
|              3 |
+----------------+
1 row in set (0.01 sec)
The result i3 tells that we have 3 distinct values in the table.
How to clear screen in python? - GeeksforGeeks

05 Apr, 2018
Most of the time, while working with python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason.In an interactive shell/terminal, we can simply use
ctrl+l
But, what if we want to clear the screen while running a python script.Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
We can use ANSI escape sequence but these are not portable and might not produce desired output.
print(chr(27)+'[2j')print('\033c')print('\x1bc')
So, here’s what we’re going to do in our script:
From os import system.Define a function.Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).Call the function we defined.
From os import system.
Define a function.
Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.
Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).
Call the function we defined.
# import only system from osfrom os import system, name  # import sleep to show output for some time periodfrom time import sleep  # define our clear functiondef clear():      # for windows    if name == 'nt':        _ = system('cls')      # for mac and linux(here, os.name is 'posix')    else:        _ = system('clear')  # print out some textprint('hello geeks\n'*10)  # sleep for 2 seconds after printing outputsleep(2)  # now call function we defined aboveclear()
NOTE: You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’).
Another way to accomplish this is using subprocess module.
# import call method from subprocess modulefrom subprocess import call  # import sleep to show output for some time periodfrom time import sleep  # define clear functiondef clear():    # check and make call for specific operating system    _ = call('clear' if os.name =='posix' else 'cls')  print('hello geeks\n'*10)  # sleep for 2 seconds after printing outputsleep(2)  # now call function we defined aboveclear()
python-modules
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to clear the canvas using clearRect in HTML ?

27 Jan, 2022
The clearRect() method of the Canvas 2D API which is used to erase the pixel in a rectangular area by setting the pixel color to transparent black (rgba(0, 0, 0, 0)).Syntax: 
abc.clearRect(x, y, width, height);
Parameters: 
x, y: These parameter represents the top-left coordinate of the rectangular box.
width: It is used to set the width of the rectangular box
height: It is used to set the of the rectangular box
Example 1: In the following example the clearRect() method is used to clear the pixel of a rectangle of size (200×300) from (50, 20).
html
<!DOCTYPE html><html lang="en"> <head>    <title>        How to clear the canvas        using clearRect in HTML?    </title></head> <body>    <canvas id="canvas"></canvas>     <script>        const canvas = document.getElementById("canvas");        const abc = canvas.getContext('2d');             abc.beginPath();        abc.fillStyle = "red";        abc.fillRect(0, 0, 200, 300);             abc.clearRect(50, 20, 100, 100);    </script></body> </html>
Output: 
Example 2: 
html
<!DOCTYPE html><html lang="en"> <head>    <title>        How to clear the canvas        using clearRect in HTML?    </title></head> <body>    <canvas id="canvas"></canvas>     <script>        const canvas = document.getElementById("canvas");        const abc = canvas.getContext('2d');                  // Draws a rectangle of 200x300        abc.beginPath();        abc.fillStyle = "red";        abc.fillRect(0, 0, 200, 300);                  // Draws a triangle        abc.beginPath();        abc.fillStyle = "green";        abc.moveTo(10, 10);        abc.lineTo(150, 10);        abc.lineTo(120, 120);        abc.closePath();        abc.fill();              abc.clearRect(40, 25, 100, 70);    </script></body> </html>
Output: 
Example 3: In this example we will erase whole canvas. 
html
<!DOCTYPE html><html lang="en"> <head>    <title>        How to clear the canvas        using clearRect in HTML?    </title></head> <body>    <canvas id="canvas"></canvas>     <script>        const canvas = document.getElementById("canvas");        const abc = canvas.getContext('2d');              abc.beginPath();        abc.fillStyle = "red";        abc.fillRect(0, 0, 200, 300);                  // This line will erase whole canvas and        // we will get an empty screen        abc.clearRect(0, 0, canvas.width, canvas.height);    </script></body> </html>
Note: Be aware that clearRect() may cause unintended side effects if you’re not using paths properly. Make sure to call beginPath() before starting to draw new items after calling clearRect().Reference: https://www.geeksforgeeks.org/html-canvas-clearrect-method/
kk773572498
saurabh1990aror
kk9826225
HTML-Canvas
HTML-Misc
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.ylim() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes.
Syntax: matplotlib.pyplot.ylim(*args, **kwargs)
Parameters: This method accept the following parameters that are described below:
bottom: This parameter is used to set the ylim to bottom.
top: This parameter is used to set the ylim to top.
**kwargs: This parameter is Text properties that is used to control the appearance of the labels.
Returns: This returns the following:
bottom, top :This returns the tuple of the new y-axis limits.
Below examples illustrate the matplotlib.pyplot.ylim() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  ax = plt.subplot(111)  t = np.arange(0.0, 5.0, 0.01)s = np.cos(2 * np.pi * t)line, = plt.plot(t, s, lw = 2)  plt.annotate('local max', xy =(2, 1),             xytext =(3, 1.5),             arrowprops = dict(facecolor ='black',                               shrink = 0.05), )  plt.ylim(-2, 2)plt.title(" matplotlib.pyplot.ylim() Example")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  np.random.seed(9680801)  mu, sigma = 50, 13x = mu + sigma * np.random.randn(10000)  # the histogram of the datan, bins, patches = plt.hist(x, 50,                             density = True,                            facecolor ='g',                            alpha = 0.75)    plt.xlabel('No of Users in K')plt.title('Histogram of IQ')plt.text(50, .035, r'$\mu = 50,\\ \sigma = 13$')  plt.xlim(-10, 110)plt.ylim(0, 0.04)  plt.grid(True)plt.title(" matplotlib.pyplot.ylim() Example")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Node.js GM thumbnail() Function

11 Oct, 2021
The thumbnail() function is an inbuilt function in the GraphicsMagick library which is used to make the thumbnail image of the given image. The function returns the true value on success.Syntax:  
thumbnail( x, y )
Parameters: This function accepts two parameters as mentioned above and described below:  
x: This parameter is used to specify width of the thumbnail image.
y: This parameter is used to specify height of the thumbnail image.
Return Value: This function returns the GraphicsMagick object.Original Image: 
Example 1: 
javascript
// Include gm libraryvar gm = require('gm');  // Import the imagegm('1.png')  // Invoke thumbnail function x, y as 300, 200.thumbnail(300, 200)  // Process and Write the image.write("thumbnail1.png", function (err) {  if (!err) console.log('done');});
Output: 
Example 2: 
javascript
// Include gm libraryvar gm = require('gm');  // Import the imagegm(600, 300, 'white')  // set the color for the stroke.stroke("green", 3)  // Set the font .font("Helvetica.ttf", 60)  //Call to drawText Function.drawText(100, 280, "GeeksforGeeks!")  // Invoke thumbnail function//  on x, y as 300, 150.thumbnail(300, 150)  // Process and write the image .write("thumbnail2.png", function (err) {  if (!err) console.log('done');});
Output: 
Reference: 
http://www.graphicsmagick.org/GraphicsMagick.html#details-rotate
https://www.npmjs.com/package/gm
adnanirshad158
Image-Processing
Node.js-GM
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby - if...else, case, unless

Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements and modifiers available in Ruby.
if conditional [then]
   code...
[elsif conditional [then]
   code...]...
[else
   code...]
end

if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.
Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.
An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon.
#!/usr/bin/ruby

x = 1
if x > 2
   puts "x is greater than 2"
elsif x <= 2 and x!=0
   puts "x is 1"
else
   puts "I can't guess the number"
end
x is 1

code if condition

Executes code if the conditional is true.
#!/usr/bin/ruby

$debug = 1
print "debug\n" if $debug
This will produce the following result −
debug

unless conditional [then]
   code
[else
   code ]
end

Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
#!/usr/bin/ruby

x = 1 
unless x>=2
   puts "x is less than 2"
 else
   puts "x is greater than 2"
end
This will produce the following result −
x is less than 2

code unless conditional

Executes code if conditional is false.
#!/usr/bin/ruby

$var =  1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var

$var = false
print "3 -- Value is set\n" unless $var
This will produce the following result −
1 -- Value is set
3 -- Value is set

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.
The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause.
A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon. Thus −
case expr0
when expr1, expr2
   stmt1
when expr3, expr4
   stmt2
else
   stmt3
end

is basically similar to the following −
_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
   stmt1
elsif expr3 === _tmp || expr4 === _tmp
   stmt2
else
   stmt3
end
#!/usr/bin/ruby

$age =  5
case $age
when 0 .. 2
   puts "baby"
when 3 .. 6
   puts "little child"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "youth"
else
   puts "adult"
end
This will produce the following result −
little child


    46 Lectures 
     9.5 hours 

 Eduonix Learning Solutions

    97 Lectures 
     7.5 hours 

 Skillbakerystudios

    227 Lectures 
     40 hours 

 YouAccel

    19 Lectures 
     10 hours 

 Programming Line

    51 Lectures 
     5 hours 

 Stone River ELearning

    39 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Setting column values as column names in the MySQL query result?

To set column values as column names in the query result, you need to use a CASE statement.
The syntax is as follows −
select yourIdColumnName,
max(case when (yourColumnName1='yourValue1') then yourColumnName2 else NULL
end) as 'yourValue1',
max(case when (yourColumnName1='yourValue2') then yourColumnName2 else NULL
end) as 'yourValue2',
max(case when yourColumnName1='yourValue3') then yourColumnName2 else NULL
end) as 'yourValue3’,
.
.
N
from valueAsColumn
group by yourIdColumnName
order by yourIdColumnName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table valueAsColumn
   -> (
   -> UserId int,
   -> UserColumn1 varchar(10),
   -> UserColumn2 varchar(10)
   -> );
Query OK, 0 rows affected (0.75 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into valueAsColumn values(0,'John','A+');
Query OK, 1 row affected (0.18 sec)
mysql> insert into valueAsColumn values(0,'Carol','B');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(0,'Sam','C');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(1,'John','D');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','A');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','C');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from valueAsColumn;
The following is the output −
+--------+-------------+-------------+
| UserId | UserColumn1 | UserColumn2 |
+--------+-------------+-------------+
|      0 | John        | A+          |
|      0 | Carol       | B           |
|      0 | Sam         | C           |
|      1 | John        | D           |
|      1 | Carol       | A           |
|      1 | Carol       | C           |
+--------+-------------+-------------+
6 rows in set (0.00 sec)
Here is the query to set column value as column names −
mysql> select UserId,
   -> max(case when (UserColumn1='John') then UserColumn2 else NULL end) as 'John',
   -> max(case when (UserColumn1='Carol') then UserColumn2 else NULL end) as 'Carol',
   -> max(case when (UserColumn1='Sam') then UserColumn2 else NULL end) as 'Sam'
   -> from valueAsColumn
   -> group by UserId
   -> order by UserId;
The following is the output −
+--------+------+-------+------+
| UserId | John | Carol | Sam  |
+--------+------+-------+------+
|      0 | A+   | B     | C    |
|      1 | D    | C     | NULL |
+--------+------+-------+------+
2 rows in set (0.00 sec)
Python - Dictionary items in value range - GeeksforGeeks

01 Aug, 2020
Given a range of values, extract all the items whose keys lie in range of values.
Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 9, 12Output : {‘best’ : 9, ‘geeks’ : 11}Explanation : Keys within 9 and 11 range extracted.
Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 14, 18Output : {}Explanation : No values in range.
Method #1 : Using loop 
This is brute way in which this task can be performed. In this, we run a loop for all the keys with conditional checks for range of values.  
Python3
# Python3 code to demonstrate working of # Dictionary items in value range# Using loop  # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing range i, j = 8, 12  # using loop to iterate through all keysres = dict()for key, val in test_dict.items():    if int(val) >= i and int(val) <= j:        res[key] = val  # printing result print("The extracted dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Method #2 : Using filter() + lambda + dictionary comprehension 
The combination of above functions can be used to solve this problem. In this, we perform task of filtering using filter() and lambda is used for conditional checks.
Python3
# Python3 code to demonstrate working of # Dictionary items in value range# Using filter() + lambda + dictionary comprehension   # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing range i, j = 8, 12  # using dictionary comprehension to compile result in one res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and                                   int(sub[1]) <= j, test_dict.items())}  # printing result print("The extracted dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
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 print without newline in Python?
Disable a button with Bootstrap

Use the .disabled class in Bootstrap to disable a button.
You can try to run the following code to implement the .disabled class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   <body>
      <div class = "container">
         <h2>Rank of Cricketers</h2>
         <p>The following are the rank of cricketers:</p>
         <button type = "button" class = "btn btn-primary">Enabled</button>
         <button type = "button" class = "btn btn-primary disabled">Disabled</button>
      </div>
   </body>
</html>
Templates and Static variables in C++

In this tutorial, we will be discussing a program to understand templates and static variables in C++.
In case of function and class templates, each instance of the templates has its own local copy of the variables.
 Live Demo
#include <iostream>
using namespace std;
template <typename T>
void fun(const T& x){
   static int i = 10;
   cout << ++i;
   return ;
}
int main(){
   fun<int>(1); //printing 11
   cout << endl;
   fun<int>(2); //printing 12
   cout << endl;
   fun<double>(1.1); //printing 11 again
   cout << endl;
   getchar();
   return 0;
}
11
12
11
Print a HTML5 canvas element

The following is the code snippet to display an HTML5 canvas element.
<a href = "javascript:print_voucher()">PRINT CANVAS</a>
function print_canvas()
{
   $("#canvas_voucher").printElement();
}
Here canvas_voucher is ID of canvas element.To make this start functioning we need to convert the canvas into .png image URL and open it in a new browser window. Print dialog is triggered to let user print the page.
function print_canvasr(){
   var win1 = window.open();
   win1.document.write("<br><img src = '"+canvas.toDataURL()+"'/>");
   win1.print();
   win1.location.reload();
}
Convert HashSet to TreeSet in Java

At first, create a HashSet with string values −
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("Bradley");
hashSet.add("Katie");
hashSet.add("Brad");
hashSet.add("Amy");
hashSet.add("Ryan");
hashSet.add("Jamie");
Now, convert the HashSet to TreeSet −
Set<String> set = new TreeSet<String>(hashSet);
Following is the program to convert HashSet to TreeSet in Java −
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class Demo {
   public static void main(String[] args) {
      HashSet<String> hashSet = new HashSet<String>();
      hashSet.add("Bradley");
      hashSet.add("Katie");
      hashSet.add("Brad");
      hashSet.add("Amy");
      hashSet.add("Ryan");
      hashSet.add("Jamie");
      hashSet.add("Kevin");
      hashSet.add("David");
      System.out.println("HashSet = "+ hashSet);
      Set<String> set = new TreeSet<String>(hashSet);
      System.out.println("TreeSet = "+set);
   }
}
HashSet = [Kevin, Jamie, Ryan, Bradley, Katie, David, Brad, Amy]
TreeSet = [Amy, Brad, Bradley, David, Jamie, Katie, Kevin, Ryan]
C++ Fstream Library - Swap Function

It is used to exchanges all internal data between x and *this.
Following is the declaration for fstream::swap.
void swap (basic_fstream& x);
x − Another basic_fstream object of the same type (i.e., with the same template parameters charT and traits).
none
No-throw guarantee − this member function never throws exceptions.
It modifies both stream objects (*this and x).
In below example explains about fstream swap function.
#include <fstream>

int main () {
   std::fstream foo;
   std::fstream bar ("test.txt");

   foo.swap(bar);

   foo << "lorem ipsum";

   foo.close();

   return 0;
}
 Print
 Add Notes
 Bookmark this page
How to identify composite primary key in any MySQL database table?

You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key.
Let us first create a table −
mysql> create table DemoTable1324
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentAge int,
   -> StudentCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)
Here is the query to add composite primary key −
mysql> alter table DemoTable1324 ADD CONSTRAINT constr_IdAgeCountry PRIMARY KEY (StudentId, StudentAge,StudentCountryName);
Query OK, 0 rows affected (1.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
Following is the query to identify composite primary key in any MySQL database table −
mysql> select count(*) AS Total
   -> from information_schema.KEY_COLUMN_USAGE
   -> where table_name='DemoTable1324' and table_schema=database();
This will produce the following output −
+-------+
| Total |
+-------+
|     3 |
+-------+
1 row in set, 2 warnings (0.76 sec)