code-rag-bench/online-tutorials huggingface dataset:
Which MySQL type is most suitable for “price” column?

The best type for price column should be DECIMAL. The type DECIMAL stores the value precisely.
For Example - DECIMAL(10,2) can be used to store price value. It means the total digit will be 10 and two digits will be after decimal point.
To understand the type DECIMAL, let us create a table.
mysql> create table PriceDemo
   −> (
   −> ProductPrice DECIMAL(10,2)
   −> );
Query OK, 0 rows affected (0.60 sec)
Now insert some records in the table in the form of price. The query to insert records is as follows −
mysql> insert into PriceDemo values(12345.67);
Query OK, 1 row affected (0.12 sec)

mysql> insert into PriceDemo values(99999999.67);
Query OK, 1 row affected (0.17 sec)

mysql> insert into PriceDemo values(123456.67);
Query OK, 1 row affected (0.17 sec)

mysql> insert into PriceDemo values(4444444.50);
Query OK, 1 row affected (0.18 sec)
Display all records which we have inserted above. The query to display all records −
mysql> select *from PriceDemo;
The following is the output −
+--------------+
| ProductPrice |
+--------------+
|     12345.67 |
|  99999999.67 |
|    123456.67 |
|   4444444.50 |
+--------------+
4 rows in set (0.00 sec)
Tryit Editor v3.7

Tryit: Center with line-height
How to create horizontal histogram in R?

Generally, the histogram is a graph that is displayed in vertical form and it helps us to analyze the distribution of a variable, mainly to understand whether the distribution is normal or not. The horizontal histogram can be also created by using coord_flip function of ggplot2 package. Check out the below example to understand how it works.
Consider the below data frame.
Live Demo
> x<-rnorm(10000,5,0.97)
> df<-data.frame(x)
> head(df,20)
x
1 3.509446
2 5.075813
3 5.242884
4 5.236765
5 5.775746
6 5.331167
7 5.250956
8 5.925262
9 6.102322
10 4.045241
11 4.117635
12 4.137581
13 4.758140
14 5.311225
15 4.354592
16 4.021351
17 5.330966
18 5.376746
19 6.717059
20 5.206282
Loading ggplot2 package and creating histogram of x:
> library(ggplot2)
> ggplot(df,aes(x))+geom_histogram(bins=30)
Creating horizontal histogram of x.
> ggplot(df,aes(x))+geom_histogram(bins=30)+coord_flip()
SaltStack - Git as a File Server

Git is an open-source distributed version control system. It can be used to keep a track of changes in any files. Salt sends files from Git repositories using the Git file server. You can configure Git to the fileserver_backend list option and if you need to configure one or more repositories, you can do so by using the gitfs_remotes option.
This chapter explains about how to install and configure the Git file server. Before moving towards the installation, you must have the following prerequisites.
The minimal requirement for the salt server to use Git as the file server is as follows −
pygit2
Dulwich
Pygit2 and Dulwich are configured using the gitfs_provider parameter in the master config file. If gitfs_provider is not configured in the master file then Salt will prefer pygit2, if the suitable version is available, followed by GitPython and Dulwich.
The following commands are used to install pygit2 in the Fedora and Ubuntu based systems −
Fedora-based system
Fedora-based system
yum install python-pygit2

Ubuntu-based system
Ubuntu-based system
apt-get install python-pygit2

Here, the minimum supported version of pygit2 is 0.20.3.
GitPython can be easily installed on the master using the yum / apt command as shown below.
Fedora-based system
Fedora-based system
yum install GitPython

Ubuntu-based system
Ubuntu-based system
apt-get install python-git

Dulwich can be easily installed on the master using the yum command.
Fedora-based system
Fedora-based system
yum install python-dulwich

Ubuntu-based system
Ubuntu-based system
apt-get install python-dulwich

Now, we have installed all the dependencies for the Git file server. Let us now configure this Git file server using the fileserver_backend section in the master config file.
In order to use the Git file server, you need to add Git in the fileserver_backend list in the master config file. It is described as follows −
fileserver_backend:
   - git

Let us further understand how to configure the Git file server in a remote configuration.
You can specify any one or all of the URLs such as git://, https://, file://, or ssh:// for the gitfs_remotes configuration in the master file. This is used to search for the requested files.
The simple https URL specification is defined below.
gitfs_remotes:
   - https://github.com

The ssh configuration can be done as shown below.
gitfs_remotes:
   - git@github.com:user1/sample.git
   - ssh://user@domain.tld/path/to/sample.git

Now, we have configured the Git file server using the two options fileserver_backend and gitfs_remotes.
After making all the changes in the master file, now restart the master to load all the configurations in the Git file server.
The following command is used for multiple configuration in gitfs_remotes in the master file.
gitfs_remotes:
   - git://github.com/sample/sample1.git
   - https://github.com/sample/sample2.git
   - file:///root/user/sample

Here, the repositories sample1.git, sample2.git, and sample.doc may have the following files.
sample1.git:
   top.sls
   
sample2.git
   edit/vimrc
   
sample.doc
   edit/vimrc

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Form elements
Tryit: HTML style textarea
Display numbers with leading zeroes in Java

To display numbers with leading zeros in Java, useDecimalFormat("000000000000").
Let us first set the format with DecimalFormat class −
DecimalFormat decFormat = new DecimalFormat("000000000000");
Now, let us display some numbers with leading zeros −
String res = decFormat.format(298989);
System.out.println(res);
res = decFormat.format(565);
System.out.println(res);
The following is an example −
 Live Demo
import java.text.DecimalFormat;
public class Demo {
   public static void main(String args[]) {
      DecimalFormat decFormat = new DecimalFormat("000000000000");
      String res = decFormat.format(298989);
      System.out.println(res);
      res = decFormat.format(565);
      System.out.println(res);
      res = decFormat.format(38989);
      System.out.println(res);
      res = decFormat.format(78768768);
      System.out.println(res);
      res = decFormat.format(298989);
      System.out.println(res);
   }
}
000000298989
000000000565
000000038989
000078768768
000000298989
VB.Net - With... End With Statement

It is not exactly a looping construct. It executes a series of statements that repeatedly refers to a single object or structure.
The syntax for this loop construct is −
With object
   [ statements ]
End With

Module loops
   Public Class Book
      Public Property Name As String
      Public Property Author As String
      Public Property Subject As String
   End Class
   Sub Main()
      Dim aBook As New Book
      With aBook
         .Name = "VB.Net Programming"
         .Author = "Zara Ali"
         .Subject = "Information Technology"
      End With
      With aBook
         Console.WriteLine(.Name)
         Console.WriteLine(.Author)
         Console.WriteLine(.Subject)
      End With
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result −
VB.Net Programming
Zara Ali
Information Technology


    63 Lectures 
     4 hours 

 Frahaan Hussain

    103 Lectures 
     12 hours 

 Arnold Higuit

    60 Lectures 
     9.5 hours 

 Arnold Higuit

    97 Lectures 
     9 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Git - Move Operation

As the name suggests, the move operation moves a directory or a file from one location to another. Tom decides to move the source code into src directory. The modified directory structure will appear as follows −
[tom@CentOS project]$ pwd
/home/tom/project

[tom@CentOS project]$ ls
README string string.c

[tom@CentOS project]$ mkdir src

[tom@CentOS project]$ git mv string.c src/

[tom@CentOS project]$ git status -s
R string.c −> src/string.c
?? string

To make these changes permanent, we have to push the modified directory structure to the remote repository so that other developers can see this.
[tom@CentOS project]$ git commit -m "Modified directory structure"

[master 7d9ea97] Modified directory structure
1 files changed, 0 insertions(+), 0 deletions(-)
rename string.c => src/string.c (100%)

[tom@CentOS project]$ git push origin master
Counting objects: 4, done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 320 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
e86f062..7d9ea97 master −> master

In Jerry’s local repository, before the pull operation, it will show the old directory structure.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project

[jerry@CentOS project]$ ls
README string string.c

But after the pull operation, the directory structure will get updated. Now, Jerry can see the src directory and the file present inside that directory.
[jerry@CentOS project]$ git pull
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From git.server.com:project
e86f062..7d9ea97 master −> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 7d9ea97683da90bcdb87c28ec9b4f64160673c8a.

[jerry@CentOS project]$ ls
README src string

[jerry@CentOS project]$ ls src/
string.c


    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    23 Lectures 
     2 hours 

 Asif Hussain

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    125 Lectures 
     9 hours 

 John Shea

    13 Lectures 
     2.5 hours 

 Raghu Pandey

    13 Lectures 
     3 hours 

 Sebastian Sulinski
 Print
 Add Notes
 Bookmark this page
Impala - Having Clause

The Having clause in Impala enables you to specify conditions that filter which group results appear in the final results.
In general, the Having clause is used along with group by clause; it places conditions on groups created by the GROUP BY clause.
Following is the syntax of the Havingclause.
select * from table_name ORDER BY col_name [ASC|DESC] [NULLS FIRST|NULLS LAST]

Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers; 
Query: select * from customers 
+----+----------+-----+-------------+--------+ 
| id | name     | age | address     | salary | 
+----+----------+-----+-------------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad   | 20000  |
| 2  | Khilan   | 25  | Delhi       | 15000  | 
| 3  | kaushik  | 23  | Kota        | 30000  | 
| 4  | Chaitali | 25  | Mumbai      | 35000  | 
| 5  | Hardik   | 27  | Bhopal      | 40000  | 
| 6  | Komal    | 22  | MP          | 32000  | 
| 7  | ram      | 25  | chennai     | 23000  | 
| 8  | rahim    | 22  | vizag       | 31000  | 
| 9  | robert   | 23  | banglore    | 28000  | 
+----+----------+-----+-----------+--------+ 
Fetched 9 row(s) in 0.51s

Following is an example of using Having clause in Impala −
[quickstart.cloudera:21000] > select max(salary) from customers group by age having max(salary) > 20000;

This query initially groups the table by age and selects the maximum salaries of each group and displays those salaries, which are greater than 20000 as shown below.
20000 
+-------------+ 
| max(salary) |
+-------------+ 
| 30000       |
| 35000       | 
| 40000       | 
| 32000       | 
+-------------+ 
Fetched 4 row(s) in 1.30s

 Print
 Add Notes
 Bookmark this page
Sublime Text - Developing Plugin

Every editor includes plugin for the development, that triggers set of activities and default packages. Sublime Text editor includes a feature for developing your own customized plugin. This chapter discusses in detail about developing your own plugin in Sublime Text.
The following steps show you in detail how to develop a plugin in Sublime Text −
Step 1 − Select the New Plugin option by navigating through Tools → Developer → New Plugin as shown below −
Step 2 − The basic code of a plugin includes import of two main libraries: sublime and sublime_plugin.
The code for the plugin is −
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
   def run(self, edit):
      self.view.insert(edit, 0, "Hello, World!")
Step 3 − The customized plugins are saved in Packages → User folder. Refer to the following screenshot that gives you the complete understanding of the plugins saved in Sublime Text editor.
When you have created a plugin and saved it, open the console using the shortcut key Ctrl+` on Windows and Cmd+` on OSX, and execute the command shown here −
view.run_command(plugin-name)

This command will execute the plugin defined by the user with the list of activities included in it.
 Print
 Add Notes
 Bookmark this page
PHP Static Properties and Methods

In a PHP class, properties and methods declared with static keyword cannot be accessed by its object with the help of -> operator. In fact, object is not required to access any instance of class. Default visibility of static items in a class is public
To access a static property from outside class, we need to use scope resolution operator (::) along with name of class. A string variable evaluating to name of class can also provide to static property
<?php
class testclass{
   static $name="test";
}
echo testclass::$name;
$var="testclass";
echo $var::$name;
?>
to use static propery inside any method of the same class, use self keyword instead of -> operator that is used for accessing instance properties.
<?php
class testclass{
   static $name="test";
   public function test(){
      echo self::$name;
   }
}
$obj=new testclass();
$obj->test();
?>
Any static property declared in parent class can be referred to inside a child class method, by using parent keyword along with scope resolution operator
<?php
class testclass{
   static $name="test";
   public function test(){
      echo self::$name;
   }
}
class myclass extends testclass{
   public function mytest(){
      echo parent::$name;
   }
}
$obj=new myclass();
$obj->mytest();
?>
When a method is declared as static, the pseudo-variable $this is not available to it. Hence, instance attributes of a class cannot be accessed in it. The static method is called by name of class along with scope resolution operator
In following example, the class has a static property $count that increnments every time constructor is executed (i.e. for each object). Inside the class, there is a static function that retrieves value of static property
 Live Demo
<?php
class testclass{
   static $count=0;
   function __construct(){
      self::$count++;
   }
   static function showcount(){
      echo "count = " . self::$count;
   }
}
$a=new testclass();
$b=new testclass();
$c=new testclass();
testclass::showcount();
?>
This will produce following output −
count = 3
Create Dot Charts in R Programming - dotchart () Function - GeeksforGeeks

28 Jul, 2020
dotchart() function in R Language is used to create a dot chart of the specified data. A dot chart is defined as a plot which is used to draw a Cleveland dot plot.
Syntax:dotchart(x, labels = NULL, groups = NULL,gcolor = par(“fg”),color = par(“fg”))
Parameters:x: it is defined as numeric vector or matrixlabels: a vector of labels for each point.groups: a grouping variable indicating how the elements of x are grouped.gcolor: color to be used for group labels and values.color: the color(s) to be used for points and labels.
Example 1:
# Dot chart of a single numeric vectordotchart(mtcars$mpg, labels = row.names(mtcars),         cex = 0.9, xlab = "mpg")
Output:
Example 2:
# Plot and color by groups cylgrps <- as.factor(mtcars$cyl)my_cols <- c("blue", "darkgreen", "orange")dotchart(mtcars$mpg, labels = row.names(mtcars),         groups = grps, gcolor = my_cols,         color = my_cols[grps],         cex = 0.9,  pch = 22, xlab = "mpg")
Output:
R Plot-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to change the order of bars in bar chart in R ?
R - if statement
Replace Specific Characters in String in R
GATE | GATE-CS-2005 | Question 77 - GeeksforGeeks

28 Jun, 2021
The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list?
  select title
  from book as B
  where (select count(*)
     from book as T
     where T.price > B.price) < 5 
(A) Titles of the four most expensive books(B) Title of the fifth most inexpensive book(C) Title of the fifth most expensive bookTitles of the five most expensive books(D) Titles of the five most expensive booksAnswer: (D)Explanation: See Question 3 of https://www.geeksforgeeks.org/database-management-systems-set-8/Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33
How do I set the timezone of MySQL?

To know the current time, we can use the now() function with SELECT statement. The query is
as follows −
mysql> SELECT now();
After executing the above query, we will get the current time. The following is the output −
+---------------------+
| now()               |
+---------------------+
| 2018-10-06 12:57:25 |
+---------------------+
1 row in set (0.02 sec)
To set the time zone, we can use the command SET. The syntax is as follows −
mysql> SET time_zone = "Some value";

Now I am applying the above query to set the time zone. The query is as follows −
mysql> SET time_zone = "+9:50";
Query OK, 0 rows affected (0.00 sec)
We can set globally as well with the help of SET command −
mysql> set global time_zone="+9:00";
Query OK, 0 rows affected (0.00 sec)
CRC32() Function in MySQL - GeeksforGeeks

05 Oct, 2020
CRC32() function in MySQL is used to compute cyclic redundancy value. It returns NULL if the argument is NULL otherwise, it returns a 32-bit unsigned value after computing the redundancy.
Syntax :
CRC32(expr)

Parameter :This method accepts only one parameter.
expr –It is a string whose CRC32 value is to be retrieved.
Returns :It returns cyclic redundancy value.
Example-1 :Finding cyclic redundancy value for a string using CRC32 Function.
SELECT CRC32('geeksforgeeks') 
AS CRC_Value;

Output :
Example-2 :Finding cyclic redundancy value for a number using CRC32 Function.
SELECT CRC32( 2020 ) 
AS CRC_Value;

Output :
Example-3 :Finding cyclic redundancy value for a NULL argument using CRC32 Function.
SELECT CRC32(NULL) 
AS CRC_Value;

Output :
Example-4 :Using CRC32 Function to find cyclic redundancy value for a column data. To demonstrate, let us create a table named Player.
CREATE TABLE Player
(
Player_id INT AUTO_INCREMENT,  
Player_name VARCHAR(100) NOT NULL,
Playing_team VARCHAR(20) NOT NULL,
PRIMARY KEY(Player_id )
);

Now, insert some data to the Player table.
INSERT INTO  
Player(Player_name, Playing_team)
VALUES
('Virat Kohli', 'RCB' ),
('Rohit Sharma', 'MI' ),
('Dinesh Karthik', 'KKR'  ),
('Shreyash Iyer', 'DC'  ),
('David Warner', 'SRH' ),
('Steve Smith', 'RR'  ),
('Andre Russell', 'KKR' ),
('Jasprit Bumrah', 'MI' ),
('Risabh Panth', 'DC'  ) ;

So, the Player Table is as follows.
SELECT * FROM Player;

Output :
Now, we will find cyclic redundancy value for Player_name and Playing_team column using CRC32 Function.
SELECT 
*, CRC32(Player_name),
CRC32(Playing_team)
FROM Player;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
Convert a Map to JSON using the Gson library in Java?

A Gson is a library that can be used to parse Java objects to JSON and vice-versa. It can also be used to convert a JSON string to an equivalent Java object. In order to parse java object to JSON or JSON to java object, we need to import com.google.gson package in our Java program.
We can create a Gson instance in two ways
By using new Gson().
By creating a GsonBuilder instance and calling with the create() method.
In the below program, we can convert a Map to a JSON object.
import java.lang.reflect.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class ConverMapToJsonTest {
   public static void main(String args[]) {
      SortedMap<String, String> data= new TreeMap<String, String>();
      data.put("Raja", "Java");
      data.put("Ravi", "SAP");
      data.put("Surya", "Python");
      data.put("Kiran", "Scala");
      data.put("Vamsi", "Selenium");
      Gson gson = new Gson();
      Type gsonType = new TypeToken(){}.getType();
      String gsonString = gson.toJson(data, gsonType);
      System.out.println(gsonString);
   }
}
{"Kiran":"Scala","Raja":"Java","Ravi":"SAP","Surya":"Python","Vamsi":"Selenium"}
Text Summarization for Topic modeling and clustering | by Gaurika Tyagi | Towards Data Science

This is a part 2 of the series analyzing healthcare chart notes using Natural Language Processing (NLP)
In the first part, we talked about cleaning the text and extracting sections of the chart notes which might be useful for further annotation by analysts. Hence, reducing their time in manually going through the entire chart note if they are only looking for “allergies” or “social history”.
Pre-processing and CleaningText Summarization — We are hereTopic Modeling using Latent Dirichlet allocation (LDA)Clustering
Pre-processing and Cleaning
Text Summarization — We are here
Topic Modeling using Latent Dirichlet allocation (LDA)
Clustering
If you want to try the entire code yourself or follow along, go to my published jupyter notebook on GitHub: https://github.com/gaurikatyagi/Natural-Language-Processing/blob/master/Introdution%20to%20NLP-Clustering%20Text.ipynb
Source: https://mimic.physionet.org/about/mimic/
Doctors take notes on their computer and 80% of what they capture is not structured. That makes the processing of information even more difficult. Let’s not forget, interpretation of healthcare jargon is not an easy task either. It requires a lot of context for interpretation. Let’s see what we have:
Spacy isn’t great at identifying the “Named Entity Recognition” of healthcare documents. See below:
doc = nlp(notes_data["TEXT"][178])text_label_df = pd.DataFrame({"label":[ent.label_ for ent in doc.ents],                                   "text": [ent.text for ent in doc.ents]                                 })    display(HTML(text_label_df.head(10).to_html()))
But, that does not mean it can not be used to summarize our text. It is still great at identifying the dependency in the texts using “Parts of Speech tagging”. Let’s see:
# Process the textdoc = nlp(notes_data["TEXT"][174][:100])print(notes_data["TEXT"][174][:100], "\n")# Iterate over the tokens in the docfor token in doc:    if not (token.pos_ == 'DET' or token.pos_ == 'PUNCT' or token.pos_ == 'SPACE' or 'CONJ' in token.pos_):        print(token.text, token.pos_)        print("lemma:", token.lemma_)        print("dependency:", token.dep_, "- ", token.head.orth_)        print("prefix:", token.prefix_)        print("suffix:", token.suffix_)
So, we can summarize the text; based on the dependency tracking. YAYYYYY!!!
Here are the results for the summary! (btw, I tried zooming out my jupyter notebook to show you the text difference, but still failed to capture the chart notes in its entirety. I’ll paste these separately as well or you can check my output on the Github page(mentioned at the top).
Isn’t it great how we could get the gist of the entire document into concise and crisp phrases? These summaries will be used in topic modeling (in section 3) and the clustering of documents in section 4.
Java.util.concurrent.Executor interface with Examples

24 Sep, 2021
The concurrent API in Java provides a feature known as an executor that initiates and controls the execution of threads. As such, an executor offers an alternative to managing threads using the thread class. At the core of an executor is the Executor interface. It refers to the objects that execute submitted Runnable tasks. 
Class hierarchy: 
java.util.concurrent
  ↳ Interface Executor
Implementing Sub-Interfaces:  
ExecutorService
ScheduledExecutorService
Implementing Classes:  
AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor
Methods in Executor interface: 
execute(): This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.Syntax: 
execute(): This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.Syntax: 
void execute(Runnable task)
Example to demonstrate an Executor. 
Java
import java.util.concurrent.Executor;import java.util.concurrent.RejectedExecutionException; public class ExecutorDemo {    public static void main(String[] args)    {        ExecutorImp obj = new ExecutorImp();        try {            obj.execute(new NewThread());        }        catch (RejectedExecutionException               | NullPointerException exception) {            System.out.println(exception);        }    }} class ExecutorImp implements Executor {    @Override    public void execute(Runnable command)    {        new Thread(command).start();    }} class NewThread implements Runnable {    @Override    public void run()    {        System.out.println("Thread executed under an executor");    }}
Thread executed under an executor
 
Reference:https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Executor.html 
sagartomar9927
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find who tweeted the most

26 Aug, 2019
Given a list of tweets, the task is to find the user who has tweeted the most.
Note:If multiple users are having the same number of tweets, then print all the users in alphabetical order of user names.
Input format:
Read the input from the console.
The first line of input should be the number of test cases
Remaining lines of input should contain each test case input. 

For each test case input:
First-line should contain the number of tweets.
Followed by N lines, each containing the user name
and tweet id separated by a space.

Output format:
Find the user with max number of tweets. 
Print user name and the total number of tweets.

Examples:
Input : 
1
4
sachin tweet_id_1
sehwag tweet_id_2
sachin tweet_id_3
sachin tweet_id_4

Output :
sachin 3

Input :
1
6
sachin tweet_id_1
sehwag tweet_id_2
sachin tweet_id_3
sehwag tweet_id_4
kohli tweet_id_5
kohli tweet_id_6


Output : 
kohli 2
sachin 2
sehwag 2


Code: Python Implementation for finding who tweeted the most
# Write Python3 code here# collection module used counting in dic for value and keys from collections import Counter  tweet_names = ["sachin tweet_id_1",                "sehwag tweet_id_2",               "sachin tweet_id_3",               "sachin tweet_id_4"]     uniq_names = [pref_names.split()[0] for              pref_names in tweet_names]  times = Counter(uniq_names)repeat = times.values()  for element in set(repeat):    dupl = ([(key, value) for             key, value in sorted(times.items()) if             value == element])          if len(dupl) > 1:        for (key, value) in dupl:            print (key,'',value)    max_value = max(times.values())    temp_max_result = [(key, value) for                        key, value in sorted(times.items()) if                       value == max_value]          if temp_max_result != dupl:        for (key,value) in temp_max_result:            print (key,'',value)             
Output :
sachin  3
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
GATE | GATE CS 2013 | Question 48

17 Sep, 2021
The following code segment is executed on a processor which allows only register operands in its instructions. Each instruction can have atmost two source operands and one destination operand. Assume that all variables are dead after this code segment.
   c = a + b;
   d = c * a;
   e = c + a;
   x = c * c;
   if (x > a) {
      y = a * a;
   }
   else {
     d = d * d;
     e = e * e;
  }
Suppose the instruction set architecture of the processor has only two registers. The only allowed compiler optimization is code motion, which moves statements from one place to another while preserving correctness. What is the minimum number of spills to memory in the compiled code?
(A) 0(B) 1(C) 2(D) 3Answer: (B)Explanation:
r1......r2
a.......b......c = a + b
a.......c......x = c * c
a.......x......but we will have to store c in mem as we don't know if x > a
................. or not
y.......x......y = a * a
choosing the best case of x > a , min spills = 1 
GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0012:13 / 38:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mNG-F-8t3a4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Numpy.prod() in Python

12 Apr, 2021
numpy.prod() returns the product of array elements over a given axis. Syntax:  
numpy.prod(a, axis=None, dtype=None, out=None, keepdims=)
Parameters a : array_like Its the input data. axis : None or int or tuple of ints, its optional It is theAxis or axes along which a product is performed. The default axis is None, it will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. dtype : dtype, its optional It is the type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. out : ndarray, its optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.Example 1  
Python
# Python Program illustrating# working of prod() import numpy as nparray1 = [1, 2] # applying functionarray2 = np.prod(array1) print("product", array2)
Output:  
2.0
Example 2 A 2d array  
Python
import numpy as nparray1 = [[1., 2.], [3., 4.]] # applying functionarray2 = np.prod(array1) print("product", array2)
Output:  
24.0
Example 3 The product of an empty array will be neutral element 1:  
Python
import numpy as nparray1 = [] # applying functionarray2 = np.prod(array1) print("product", array2)
Output:  
1
Example 4 By specifying the axis over which we are multiplying  
Python
import numpy as nparray1 =[[1, 2], [3, 4]] # applying functionarray2 = np.prod(array1, axis = 1) print("product", array2)
Output:  
[2, 12]
Example 5 If the type of x is unsigned, then the output type will the unsigned platform integer  
Python
import numpy as npx = np.array([1, 2, 3], dtype = np.uint8) # applying function np.prod(x).dtype == np.uint
Output:  
True
 
MartinEarnest
arorakashish0911
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set Legend Alpha of ggplot2 Plot in R

31 Aug, 2021
In this article, we are going to see how to set the legend alpha of the ggplot2 Plot in R Programming Language.
Setting the legend alpha of the plot using the alpha argument of the guide_legend function from the ggplot2 package.
Syntax: guide_legend(override.aes = list(alpha))
Parameters:
override.aes:  allows the user to change only the legend appearance without affecting the rest of the plot.
Note:
The alpha value of the legend of the plot is used to set the transparency index of the legend symbol, In other words, the alpha value nearer to zero will make the legend transparent, and closer to value 1 will make the legend symbol opaque.
Alpha values are any numbers from 0 (transparent) to 1 (opaque). The default alpha value usually is 1.
The alpha can be set to a constant value or it can be mapped via a scale.
In this example, we will be setting up the alpha value of the legend of the ggplot2 plot to a value using the alpha argument of the guide_legend function of the ggplot2 package in the R programming language.
R
library("ggplot2")  gfg<-data.frame(x =c(4,9,5,6,10,2,3,7,8,1),                 y = c(9,4,3,1,5,2,8,10,7,6),                group = c('A','B','C','D','E'))gfg_plot <- ggplot(gfg, aes(x, y, col = group)) + geom_point()gfg_plot
Output:
Here we are going to set the legend alpha value.
Example 1: In this example, we will use the alpha value of 0.5 which will set the opaque of the legend.
R
library("ggplot2")  gfg<-data.frame(x =c(4,9,5,6,10,2,3,7,8,1),                y = c(9,4,3,1,5,2,8,10,7,6) ,                group = c('A','B','C','D','E'))  gfg_plot <- ggplot(gfg, aes(x, y, col = group)) + geom_point()gfg_plot+guides(colour = guide_legend                (override.aes = list(alpha = 0.5)))
Output:
Example 2: In this example, we will be setting up the alpha value of the legend of the ggplot2 plot to a value equal to 0.1 using the alpha argument of the guide_legend function of the ggplot2 package in the R programming language.
R
library("ggplot2")  gfg<-data.frame(x = c(4,9,5,6,10,2,3,7,8,1),                y = c(9,4,3,1,5,2,8,10,7,6),                group = c('A','B','C','D','E'))gfg_plot <- ggplot(gfg, aes(x, y, col = group)) + geom_point()gfg_plot+guides(colour = guide_legend                (override.aes = list(alpha = 0.1)))
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
GATE | GATE-CS-2004 | Question 20

28 Jun, 2021
Which of the following addressing modes are suitable for program relocation at run time ?
(i)   Absolute addressing
(ii)  Based addressing
(iii) Relative addressing
(iv)  Indirect addressing
(A) (i) and (iv)(B) (i) and (ii)(C) (ii) and (iii)(D) (i), (ii) and (iv)Answer: (C)Explanation: Explanation:
Program relocation at run time transfer complete block to some memory locations. This requires as base address and block should be relatively addressed through this base address .This require both base address and relative address. So( C)  is correct option.
Absolute addressing mode and indirect addressing modes is used for one instruction at one time, not for whole block So both are not suitable for program relocation at run time.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
How to Automatically Install Required Packages From a Python Script?

06 Dec, 2021
When working in python having to use libraries you don’t know or using a new pc, it is a hectic job to install all the libraries one by one. Each time you have to find out the name of the library and install it one by one. But if we know libraries like pipreqs which automatically installs all the required libraries to run the program, it will make our job so easy and we can focus on the code rather than wasting time installing the libraries one by one.
It is a python library that Generates pip requirements.txt file based on imports of any project and then you can install all of them in one go.
Run this command on your PC to install the pipreqs library.
pip install pipreqs
Step 1: Go to the directory in which your python script is present for example assume if we take this code in our directory.
Python3
import osimport requestsimport urllib.requestfrom bs4 import BeautifulSoupprint('GFG is the best')
Step 2:In this directory run the following command that will create a requirement file.
pipreqs
The requirement file will look like this in our case.
This shows that request and beautifulesoup4 library are not present in our system and we must install them to run our program.
Step 3: Now run this command to install all the libraries required to run the program
pip install -r requirements.txt
installing all the libraries
Now if we run the code it will successfully run the code.
how-to-install
Picked
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – os.replace() method

21 Oct, 2021
Prerequisite: OS module in Python.
os.replace() method in Python is used to rename the file or directory. If destination is a directory, OSError will be raised. If the destination exists and is a file, it will be replaced without error if the action performing user has permission. This method may fail if the source and destination are on different filesystems.
Syntax: os.replace(source, destination, *, src_dir_fd=None, dst_dir_fd=None2)
Parameter:
source: Name of file or directory which we want to rename.
destination: Name which we want to give in destination.
src_dir_id : This parameter stores the source directory’s or file,            file descriptor referring to a directory.
dst_dir_fd: It is a file descriptor referring to a directory,             and the path to operate. It should be relative,             path will then be relative to that directory. If             the path is absolute, dir_fd is ignored.
Return Type: This method does not return any value.
Code #1: Use of os.replace() method to rename a file.
Python3
# Python program to explain os.replace() method # importing os moduleimport os # file namefile = "f.txt" # File location which to renamelocation = "d.txt" # Pathpath = os.replace(file, location) # renamed the file f.txt to d.txtprint("File %s is renamed successfully" % file)
Output:
File f.txt is renamed successfully
Code #2: Handling possible errors. (If necessary permissions are given then output will be as shown in below) 
Python
# Python program to explain os.replace() method # importing os moduleimport os # Source file pathsource = './file.txt' # destination file pathdest = './da'  # try renaming the source path# to destination path# using os.rename() method try:    os.replace(source, dest)    print("Source path renamed to destination path successfully.") # If Source is a file# but destination is a directoryexcept IsADirectoryError:    print("Source is a file but destination is a directory.") # If source is a directory# but destination is a fileexcept NotADirectoryError:    print("Source is a directory but destination is a file.") # For permission related errorsexcept PermissionError:    print("Operation not permitted.") # For other errorsexcept OSError as error:
Output:
Source is a file but destination is a directory.
coder36
gabaa406
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Selecting rows in pandas DataFrame based on conditions
What is the practical use for a closure in JavaScript?

14 Dec, 2021
In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned. The below examples show the practical use of closures:
Example: In this example, a variable mult is defined that is local to the function multFn and is only accessible inside this function. When an inner function is declared, JavaScript creates a closure where the inner function has access to the variable and its parameters.
javascript
// Define the closurefunction multFn() {  var mult = 9;  return function(val) {    mult = mult * val;    return mult;  }}  // Use the closurevar mult = multFn();console.log(mult(18));
Output:
162
1. Using private variables and methods: In JavaScript, we can use private variables and methods using closures. The example below shows the use of private variables with closure.
Example: In this example, the rentPrice() function returns an object with three methods: getRent(), incRent(), and decRent(). These three methods has access to the private variable rent. However, the code outside its scope cannot directly access this variable. Hence, we can mimic object oriented programming in JavaScript.
javascript
// Define the closurevar rentPrice = function(initialRent) {   var rent = initialRent;      // Define private variables for    // the closure    return {      getRent: function() {        return console.log(rent);      },      incRent: function(amount) {        rent += amount;        console.log(rent);      },      decRent: function(amount) {         rent -= amount;         console.log(rent);      }    }}  var Rent = rentPrice(8000);  // Access the private methodsRent.incRent(2000);Rent.decRent(1500);Rent.decRent(1000); Rent.incRent(2000); Rent.getRent();
Output:
10000
8500
7500
9500
9500
2. Maintaining state between each function call: Suppose there is a function and one would like it to multiply multiple values together. This could be done with the help of a global variable as they are accessible throughout the program. However, a drawback is that they are prone to change from anywhere in the code. This can be done alternatively using closures. Closures help in maintaining the state between function calls without using a global variable.
Example:
javascript
(function() {    var multFn = function multiply() {    // This variable is local to    // the closure and holds    // its value inbetween    // multiple calls   var mult = 9;   return function(val) {     mult = mult * val;     return mult;   }  };    var mult = multFn();      // Call the method  // multiple times  console.log(mult(2));  console.log(mult(3));  console.log(mult(5));}());
Output:
18
54
270
kashishsoda
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calculate nCr value in R Programming – choose() Function

01 Jun, 2020
R Language offers a direct function that can compute the nCr value without writing the whole code for computing nCr value.
Syntax: choose(n, r)
Parameters:n: Number of elementsr: Number of combinations
Returns: The number of r combinations from a total of n elements, i.e, nCr value.
Example 1:
# R program to calculate nCr value     # Using choose() method answer1 <- choose(3, 2) answer2 <- choose(3, 7)  answer3 <- choose(7, 3)  print(answer1) print(answer2) print(answer3) 
Output:
3
0
35

Example 2: If we provide the value of n and r such that n < r then choose(n, r) will return 0.
# R program to calculate nCr value      # Using choose() method answer1 <- choose(2, 3) answer2 <- choose(3, 6)  answer3 <- choose(3, 7)   print(answer1) print(answer2) print(answer3) 
Output:
0
0
0

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.