code-rag-bench/online-tutorials huggingface dataset:
Java Program to reverse a given String with preserving the position of space.

You can reverse the contents of a given String using leaving the spaces using the reverse() method of the StringBuffer class.
public class Test {
   public static void main(String args[]) {
      String str = "hi welcome to Tutorialspoint";
      String strArray[] = str.split(" ");
      StringBuffer sb= new StringBuffer(str);
      sb.reverse();
      for(int i=0 ; i<str.length(); i++){
      if(str.charAt(i)== ' '){
         sb.insert(i, " ");
      }
   }
   sb.append("");
   System.out.println(sb);
}
tn iopslai ro tuT ot emoclew ih
Redis - Scripting

Redis scripting is used to evaluate scripts using the Lua interpreter. It is built into Redis starting from version 2.6.0. The command used for scripting is EVAL command.
Following is the basic syntax of EVAL command.
redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]

Following example explains how Redis scripting works.
redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 
key2 first second  
1) "key1" 
2) "key2" 
3) "first" 
4) "second"

Following table lists some basic commands related to Redis Scripting.
Executes a Lua script.
Executes a Lua script.
Checks the existence of scripts in the script cache.
Removes all the scripts from the script cache.
Kills the script currently in execution.
Loads the specified Lua script into the script cache.

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Python Dictionary update() method - GeeksforGeeks

04 Oct, 2021
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Syntax: dict.update([other])
Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters.
Returns: It doesn’t return any value but updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs.
Python3
# Python program to show working# of update() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', }Dictionary2 = {'B': 'Geeks'} # Dictionary before Updationprint("Original Dictionary:")print(Dictionary1) # update the value of key 'B'Dictionary1.update(Dictionary2)print("Dictionary after updation:")print(Dictionary1)
Output: 
Original Dictionary:
{'A': 'Geeks', 'B': 'For'}

Dictionary after updation:
{'A': 'Geeks', 'B': 'Geeks'}
Python3
# Python program to show working# of update() method in Dictionary # Dictionary with single itemDictionary1 = {'A': 'Geeks'} # Dictionary before Updationprint("Original Dictionary:")print(Dictionary1) # update the Dictionary with iterableDictionary1.update(B='For', C='Geeks')print("Dictionary after updation:")print(Dictionary1)
Output: 
Original Dictionary:
{'A': 'Geeks'}

Dictionary after updation:
{'C': 'Geeks', 'B': 'For', 'A': 'Geeks'}
Python3
def checkKey(dict, key):           if key in dict.keys():        print("Key exist, ", end =" ")        dict.update({'m':600})        print("value updated =", 600)    else:        print("Not Exist")dict = {'m': 700, 'n':100, 't':500}   key = 'm'checkKey(dict, key)print(dict)
Output:
Key exist,  value updated = 600
{'m': 600, 'n': 100, 't': 500}
kumar_satyam
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
List Methods in Python?

Python provides some very useful list methods that we can use to perform list operation very easily.
Below are the list of python built-in methods which we can use on list:
Adds an element at the end of the list
#Append
lst = ['Hello', 'Python']
print(lst)
lst.append('Tutorialspoint')
print(lst)
['Hello', 'Python']
['Hello', 'Python','Tutorialspoint']
Removes all the elements from the list
#clear
lst = ['Hello','Python','Tutorialspoint']
print(lst)
lst.clear()
print(lst)
['Hello', 'Python', 'Tutorialspoint']
[]
Returns a shallow copy of the list.
#COPY()
#Without copy
lst = ['Hello', 'Python', 'Tutorialspoint']
lst1 = lst
lst1.append('Java')
print(lst)
print(lst1)
#With copy
lst = ['Hello', 'Python', 'Tutorialspoint']
lst1 = lst.copy()
lst1.append("Java")
print(lst)
print(lst1)
['Hello', 'Python', 'Tutorialspoint', 'Java']
['Hello', 'Python', 'Tutorialspoint', 'Java']
['Hello', 'Python', 'Tutorialspoint']
['Hello', 'Python', 'Tutorialspoint', 'Java']
Returns the number of elements with the specified value.
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst.count("Python"))
print(lst.count("Tutorialspoint"))
print(lst.count(" "))
2
1
0
Add the elements of a list (or any iterable), to the end of the current list
#extend(iterables)
lst = ['Hello', 'Python']
print(lst)
lst.extend(['Java', 'CSharp'])
print(lst)
['Hello', 'Python']
['Hello', 'Python', 'Java', 'CSharp']
Returns the index of the first element with the specified value
#index()
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst.index('Python'))
print(lst.index("Python", 2))
1
3
Adds an element at the specified position
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst)
lst.insert(0, "CPlusPlus")
print(lst)
lst.insert(3, "Java")
print(lst)
['Hello', 'Python', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
Removes the element at the specified position
#pop()
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
#Without index
lst.pop()
print(lst)
#With Index
lst.pop(3)
print(lst)
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint']
['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint']
Removes the first item with the specified value
#Remove
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
lst.remove('Python')
print(lst)
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Java', 'Tutorialspoint', 'Python']
Reverses the order of the list
#reverse()
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
lst.reverse()
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['Python', 'Tutorialspoint', 'Java', 'Python', 'Hello', 'CPlusPlus']
Sorts the list
#sort()
lst = [2, 3, 7, 1, 13, 8, 49]
print(lst)
#default
lst.sort()
print(lst)
#reverse = True
lst.sort(reverse = True)
print(lst)
[2, 3, 7, 1, 13, 8, 49]
[1, 2, 3, 7, 8, 13, 49]
[49, 13, 8, 7, 3, 2, 1]
SQLite - DETACH Database

SQLite DETACH DATABASE statement is used to detach and dissociate a named database from a database connection which was previously attached using ATTACH statement. If the same database file has been attached with multiple aliases, then DETACH command will disconnect only the given name and rest of the attachment will still continue. You cannot detach the main or temp databases.
If the database is an in-memory or temporary database, the database will be destroyed and the contents will be lost.
Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement.
DETACH DATABASE 'Alias-Name';

Here, 'Alias-Name' is the same alias, which you had used while attaching the database using ATTACH statement.
Consider you have a database, which you created in the previous chapter and attached it with 'test' and 'currentDB' as we can see using .database command.
sqlite>.databases
seq  name             file
---  ---------------  ----------------------
0    main             /home/sqlite/testDB.db
2    test             /home/sqlite/testDB.db
3    currentDB        /home/sqlite/testDB.db
Let's try to detach 'currentDB' from testDB.db  using the following command.
sqlite> DETACH DATABASE 'currentDB';
Now, if you will check the current attachment, you will find that testDB.db is still connected with 'test' and 'main'.
sqlite>.databases
seq  name             file
---  ---------------  ----------------------
0    main             /home/sqlite/testDB.db
2    test             /home/sqlite/testDB.db
How to get client_id and client_secret for Python Reddit API registration ?

26 May, 2020
Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them.A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what content the users post. It can be triggered by certain key phrases and also depends on various subreddits regarding their content.In order to implement a Reddit bot, we will use the Python Reddit API Wrapper (PRAW). It allows us to login to the Reddit API to directly interact with the backend of the website. More information about this library can be found here – PRAW – Python Reddit API Wrapper.
reddit = praw.Reddit(client_id ='my client id',                      client_secret ='my client secret',                      user_agent ='my user agent',                      username ='my username',                      password ='my password') 
In order to get the information for these fields:
Create a Reddit account.
The username of the reddit account will go to the username field.
The password of the reddit account will go to the password field.
user_agent is a unique identifier that helps Reddit determine the source of network requests.
client_id and client_secret are needed to access Reddit’s API as a script application. We can find them by:Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret.
Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret.
Login to your Reddit account.
Open the link: https://www.reddit.com/prefs/apps
The following will open up:
Click on “create an app...”. The following fields will be requested:
Give an appropriate name to the application and fill rest of the fields:
Click on “create app”.
The text in the green box is the client_id.
Click on “edit”. The text in the green box is the client_secret.
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
PHP | Basics of File Handling

08 Nov, 2017
File handling is needed for any application. For some tasks to be done file needs to be processed. File handling in PHP is similar as file handling is done by using any programming language like C. PHP has many functions to work with normal files. Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name of the file which is to be opened and second parameter tells about mode in which file needs to be opened, e.g.,
<?php$file = fopen(“demo.txt”,'w');?>
Files can be opened in any of the following modes :
“w” – Opens a file for write only. If file not exist then new file is created and if file already exists then contents of file is erased.
“r” – File is opened for read only.
“a” – File is opened for write only. File pointer points to end of file. Existing data in file is preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if file already exists then contents of file is erased.
“r+” – File is opened for read/write.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is preserved. If file is not there then new file is created.
“x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes two arguments. One is file pointer and another is file size in bytes, e.g.,
<?php$filename = "demo.txt";$file = fopen( $filename, 'r' );$size = filesize( $filename );$filedata = fread( $file, $size );?>
3) fwrite() – New file can be created or text can be appended to an existing file using fwrite() function. Arguments for fwrite() function are file pointer and text that is to written to file. It can contain optional third argument where length of text to written is specified, e.g.,
<?php$file = fopen("demo.txt", 'w');$text = "Hello world\n";fwrite($file, $text);?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed, e.g.,
<?php$file = fopen("demo.txt", 'r');//some code to be executedfclose($file);?>
Reference –Wikipedia
This article is contributed by Swasthik. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b}

23 Jul, 2021
In this article, we will discuss the LEX Code that accepts the string ending with ‘abb’ over input alphabet  {a,b} and will see the implementation using LEX code and will understand the approach. Let’s discuss it one by one. 
Problem Overview :LEX Code that accepts the string ending with ‘abb’ over input alphabet  {a,b}.
Example –
Input  : abb
Output : Accepted

Input  : abababb
Output : Accepted

Input  : 23ab
Output : Invalid

Input  : ab345
Output : Invalid

Input  : bbabaa
Output : Not Accepted
Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define four more states: A, B, C, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at C then display the message “Accepted”. Else if the input string ends at state INITIAL, A, or B then displays the message “Not Accepted”.
Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.
Example – 
filename.l
Then after saving the program closes the lex file and then open the terminal and write the following commands as follows.
lex filename.l
cc lex.yy.c
./a.out
Implementation- LEX Code :
%{
%}
 
%s A B C DEAD

// not accepted state after visiting A 
%%
<INITIAL>a BEGIN A;
<INITIAL>b BEGIN INITIAL;
<INITIAL>[^ab\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}

// not accepted state after visiting A and B state
<A>a BEGIN A;
<A>b BEGIN B;
<A>[^ab\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}
 
// // not accepted state after visiting A and C state  
<B>a BEGIN A;
<B>b BEGIN C;
<B>[^ab\n] BEGIN DEAD;
<B>\n BEGIN INITIAL; {printf("Not Accepted\n");}

// Accepted case
<C>a BEGIN A;
<C>b BEGIN INITIAL;
<C>[^ab\n] BEGIN DEAD;
<C>\n BEGIN INITIAL; {printf("Accepted\n");}

// Invalid Case 
<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}
 
%%
// yywrap method
int yywrap()
{
return 1;
}  

// main method 
int main()
{
   printf("Enter String\n");
   // called yylex
   yylex();
return 0;
}
Output :
DFA
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Decidable and Undecidable problems in Theory of Computation
Halting Problem in Theory of Computation
Post Correspondence Problem
Undecidability and Reducibility in TOC
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Pushdown Automata Acceptance by Final State
Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}
Arden's Theorem in Theory of Computation
How to work Date query with ISODate in MongoDB?

Use $gte operator along with ISODate() to work Date query with ISODate in MongoDB.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.dateDemo.insertOne({"StudentName":"John","StudentAge":26,"AdmissionDate":new ISODate("2013-06-07")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a65799064dcd4a68b70ea")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.dateDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a65799064dcd4a68b70ea"),
   "StudentName" : "John",
   "StudentAge" : 26,
   "AdmissionDate" : ISODate("2013-06-07T00:00:00Z")
}
Here is the date query with ISODate in MongoDB −
> db.dateDemo.find({"AdmissionDate":{"$gte": ISODate("2013-06-07T00:00:00Z")}}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a65799064dcd4a68b70ea"),
   "StudentName" : "John",
   "StudentAge" : 26,
   "AdmissionDate" : ISODate("2013-06-07T00:00:00Z")
}
Showing data values on stacked bar chart in ggplot2 in R

29 Jun, 2021
In this article, you’ll learn how to show data values on a stacked bar chart in ggplot2 in R Programming Language. 
To show the data into the Stacked bar chart you have to use another parameter called geom_text().
Syntax:
 geom_text(size, position = position_stack(vjust = value), colour)
Here the size represents the size of the font that will appear on the plot and position_stack() will automatically add values to the plot at their respective positions.
Example 1:
R
# Creating the DataSubject = c(rep(c("Hindi", "English", "Math", "Science",                  "Computer Science"), times = 4))  Year = c(rep(c("2017-18", "2018-19", "2019-20",               "2020-21"), each = 5))  Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,73,                    45,76,88,99,77,86,56,77)  # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed)  # loading the Librarylibrary(ggplot2)  # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed,                           fill = Subject, label = Students_Passed)) +geom_bar(stat = "identity") + geom_text(  size = 3, position = position_stack(vjust = 0.5))   
Output:
It is also possible to change the color of data values using geom_text() itself. For this just pass the font color to the color attribute.
Example 2:
R
# Creating the DataSubject = c(rep(c("Hindi", "English", "Math", "Science",                  "Computer Science"), times = 4))Year = c(rep(c("2017-18", "2018-19", "2019-20",               "2020-21"), each = 5))Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,                    73,45,76,88,99,77,86,56,77)  # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed)  # loading the Librarylibrary(ggplot2)  # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed,                           fill = Subject, label = Students_Passed)) +geom_bar(stat = "identity") + geom_text(  size = 5, position = position_stack(vjust = 0.5),colour = "white")   
Output
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame
Single Side Band (SSB) Modulation and Demodulation using MATLAB

06 Jun, 2022
Single sideband (SSB) modulation might be a sort of modulation used to send data, which includes an audio signal. Amplitude modulation produces an output signal in which the bandwidth is two times the most frequency of the original baseband signal. SSB modulation neglects this bandwidth increase, and also the power wasted on a carrier, at the price of more device complexity and tougher tuning at the receiver side.
 
Figure: Block Diagram of Modulation
 
Figure: Spectrum 
The Expression for Single Side Band with Upper Side Band : here, m is the cosine wave with time duration of ‘t’, fc is the carrier frequency, t is the time duration and mh s the Hilbert transform of baseband.Example: 
MATLAB
% MATLAB code for modulation% carrier frequencyfc = 200; % baseband frequencyfm = 30; % sampling frequencyfs= 4000; % time durationt = (0 : 1 / fs :1 );t = linspace(0, 1, 1000); % cosine wave with time duration of 't'm = cos(2 * pi * fm * t); % Hilbert transform of basebandmh = imag(hilbert(m)); % Single Side Band with Upper Side Bandsb = m .* cos(2 * pi * fc * t) - mh .* sin(2 * pi * fc * t); %Demodulation by Synchronous methodem = sb.*m; %Filtering High Frequemcies[ n,w ] = buttord(2/1000,4/1000, .5, 5);[ a,b ] = butter(n,w,'low');dem = filter(a,b,em);   % displaying the modulationfigure;plot(t, sb);title('Single SideBand Modulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the demodulationfigure;plot(t, em);title('Single SideBand Demodulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the filtered signalfigure;plot(t, dem);title('Filtered Signal');xlabel('Time(sec)');ylabel('Amplitude');
Output:
Demodulated Signal
Filtered Signal
roytanupriya1
sumitgumber28
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
ML | Introduction to Data in Machine Learning
Fuzzy Logic | Introduction
Convert CSV to JSON using Python

21 Jan, 2021
CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature variable.
On the other hand, JSON (or JavaScript Object Notation) is a dictionary-like notation that can be used by importing the JSON package in Python. Every record (or row) is saved as a separate dictionary, with the column names as Keys of the dictionary. All of these records as dictionaries are saved in a nested dictionary to compose the entire dataset. It is stored with the extension .json, for example, geeksforgeeks.json
Refer to the below articles to understand the basics of JSON and CSV.
Working With JSON Data in Python
Working with CSV file in Python.
We will create a JSON file that will have several dictionaries, each representing a record (row) from the CSV file, with the Key as the column specified. 
Sample CSV File used:
Python3
import csvimport json  # Function to convert a CSV to JSON# Takes the file paths as argumentsdef make_json(csvFilePath, jsonFilePath):         # create a dictionary    data = {}         # Open a csv reader called DictReader    with open(csvFilePath, encoding='utf-8') as csvf:        csvReader = csv.DictReader(csvf)                 # Convert each row into a dictionary        # and add it to data        for rows in csvReader:                         # Assuming a column named 'No' to            # be the primary key            key = rows['No']            data[key] = rows     # Open a json writer, and use the json.dumps()    # function to dump data    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:        jsonf.write(json.dumps(data, indent=4))         # Driver Code # Decide the two file paths according to your# computer systemcsvFilePath = r'Names.csv'jsonFilePath = r'Names.json' # Call the make_json functionmake_json(csvFilePath, jsonFilePath)
  
Output:
 
 
mezdylan
Python json-programs
python-csv
Python-json
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Display MongoDB explain query plan?

For information on query plan, use explain() in MongoDB. Let us create a collection with documents −
> db.demo202.insertOne({"StudentFirstName":"Chris","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c3bd103d395bdc21346e8")
}
> db.demo202.insertOne({"StudentFirstName":"David","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c3bd803d395bdc21346e9")
}
> db.demo202.insertOne({"StudentFirstName":"Bob","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c3bde03d395bdc21346ea")
}
Display all documents from a collection with the help of find() method −
> db.demo202.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c3bd103d395bdc21346e8"), "StudentFirstName" : "Chris", "StudentAge" : 21 }
{ "_id" : ObjectId("5e3c3bd803d395bdc21346e9"), "StudentFirstName" : "David", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3c3bde03d395bdc21346ea"), "StudentFirstName" : "Bob", "StudentAge" : 22 }
Following is the query to display explain query plan −
> db.demo202.find({"StudentFirstName":"David"}).explain();
This will produce the following output −
{
   "queryPlanner" : {
      "plannerVersion" : 1,
      "namespace" : "test.demo202",
      "indexFilterSet" : false,
      "parsedQuery" : {
         "StudentFirstName" : {
            "$eq" : "David"
         }
      },
      "winningPlan" : {
         "stage" : "COLLSCAN",
         "filter" : {
            "StudentFirstName" : {
               "$eq" : "David"
            }
         },
         "direction" : "forward"
         },
      "rejectedPlans" : [ ]
   },
   "serverInfo" : {
      "host" : "DESKTOP-QN2RB3H",
      "port" : 27017,
      "version" : "4.0.5",
      "gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
   },
   "ok" : 1
}
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a hash table with 100 slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what is the probability that the first 3 slots are unfilled after the first 3 insertions?(A) (97 × 97 × 97)/1003(B) (99 × 98 × 97)/1003(C) (97 × 96 × 95)/1003(D) (97 × 96 × 95)/(3! × 1003)Answer: (A)Explanation: Simple Uniform hashing function is a hypothetical hashing function that evenly distributes items into the slots of a hash table. Moreover, each item to be hashed has an equal probability of being placed into a slot, regardless of the other elements already placed. (Source: https://en.wikipedia.org/wiki/SUHA_%28computer_science%29).
Probability that the first 3 slots are unfilled after the first 3 insertions = 
                (probability that first item doesn't go in any of the first 3 slots)*
                (probability that second item doesn't go in any of the first 3 slots)*
                (probability that third item doesn't go in any of the first 3 slots)

                 = (97/100) * (97/100) * (97/100) 
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2001 | Question 48
Find the Symmetric difference between two arrays - JavaScript

In Mathematics, the symmetric difference of two sets, say A and B is represented by A △ B
And it is defined as the set of all those elements which belongs either to A or to B but not to both.
For example −
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
Then the symmetric difference of A and B will be −
const diff = [2, 4, 9]
Following is the code −
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      if(arr2.indexOf(arr1[i]) !== -1){
         continue;
      };
      res.push(arr1[i]);
   }
   for(let i = 0; i < arr2.length; i++){
      if(arr1.indexOf(arr2[i]) !== -1){
         continue;
      };
      res.push(arr2[i]);
   };
   return res;
};
console.log(symmetricDifference(A, B));
This will produce the following output in console −
[2, 4, 9]
Decimal to any base conversion | Practice | GeeksforGeeks

Given a decimal number N and the base B to which it should be converted. Convert the given number to the given base.
Example 1:
Input:
B = 2
N = 12 

Output:
1100

Explanation:
If the number 12 is converted to a 
number with base 2 we get the binary 
representation of 12 = 1100.
Example 2:
Input:
B = 16
N = 282

Output:
11A

Explanation:
If the number 282 is converted to a 
number with base 16 we get the hexadecimal 
representation of 282 = 11A.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function getNumber() which takes two integer B and N representing the base and the decimal number and returns the number in the given base.
Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)
Constraints:
2 <= B <= 16
1 <= N <= 999999999
0
kollinagavenkatapavan20001 month ago
 Can anyone tell me why is it showing output difference , even though expected output and my code's output both were same .  
 
And it is not showing output difference when I run this test case alone in custom input . 
 
Thank You . 
0
Aman Nigam9 months ago
Aman Nigam
Very Easy C++ Solution
https://uploads.disquscdn.c...
0
insane_banda1 year ago
insane_banda
Very irritating that java testcase is broken. I've observed that you guys don't pay much importance to java testcases. Faced same issue many times. Same logic gets accepted in c++ but throws error in java due to some input/output errors.
0
Shreyansh Kumar Singh1 year ago
Shreyansh Kumar Singh
Java SolutionOne Liner > return Integer.toString(N, B).toUpperCase();Another approach https://uploads.disquscdn.c...
0
Shreyansh Kumar Singh
This comment was deleted.
0
Shreyansh Kumar Singh
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
SQLAlchemy Core - Using Textual SQL

SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged.
It constructs a new TextClause, representing a textual SQL string directly as shown in the below code −
from sqlalchemy import text
t = text("SELECT * FROM students")
result = connection.execute(t)
The advantages text() provides over a plain string are −
backend-neutral support for bind parameters
per-statement execution options
result-column typing behaviour
The text()function requires Bound parameters in the named colon format. They are consistent regardless of database backend. To send values in for the parameters, we pass them into the execute() method as additional arguments.
The following example uses bound parameters in textual SQL −
from sqlalchemy.sql import text
s = text("select students.name, students.lastname from students where students.name between :x and :y")
conn.execute(s, x = 'A', y = 'L').fetchall()
The text() function constructs SQL expression as follows −
select students.name, students.lastname from students where students.name between ? and ?
The values of x = ’A’ and y = ’L’ are passed as parameters. Result is a list of rows with names between ‘A’ and ‘L’ −
[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]
The text() construct supports pre-established bound values using the TextClause.bindparams() method. The parameters can also be explicitly typed as follows −
stmt = text("SELECT * FROM students WHERE students.name BETWEEN :x AND :y")

stmt = stmt.bindparams(
   bindparam("x", type_= String), 
   bindparam("y", type_= String)
)

result = conn.execute(stmt, {"x": "A", "y": "L"})

The text() function also be produces fragments of SQL within a select() object that 
accepts text() objects as an arguments. The “geometry” of the statement is provided by 
select() construct , and the textual content by text() construct. We can build a statement 
without the need to refer to any pre-established Table metadata. 

from sqlalchemy.sql import select
s = select([text("students.name, students.lastname from students")]).where(text("students.name between :x and :y"))
conn.execute(s, x = 'A', y = 'L').fetchall()
You can also use and_() function to combine multiple conditions in WHERE clause created with the help of text() function.
from sqlalchemy import and_
from sqlalchemy.sql import select
s = select([text("* from students")]) \
.where(
   and_(
      text("students.name between :x and :y"),
      text("students.id>2")
   )
)
conn.execute(s, x = 'A', y = 'L').fetchall()
Above code fetches rows with names between “A” and “L” with id greater than 2. The output of the code is given below −
[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]


    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Calculate the area of an image using Matplotlib - GeeksforGeeks

31 Jul, 2021
Let us see how to calculate the area of an image in Python using Matplotlib. 
Algorithm: 
Import the matplotlib.pyplot module.Import an image using the imread() method.Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.Calculate the area as, area = height * width.Display the area.
Import the matplotlib.pyplot module.
Import an image using the imread() method.
Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.
Calculate the area as, area = height * width.
Display the area.
Example 1: Consider the following image :  
“GFG.jpg”
Python3
# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread("GFG.jpg") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint("Area of the image is : ", area)
Output : 
Area of the image is : 50244
Example 2: Consider the following image : 
“image.jpg”
Python3
# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread("image.jpg") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint("Area of the image is : ", area)
Output : 
Area of the image is : 213200
 
gulshankumarar231
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Character.hashCode() in Java with examples - GeeksforGeeks

06 Dec, 2018
Java.lang.Character.hashCode() is a built-in method in Java which returns a hash code for this Character. The returned hash code is equal to the result of invoking charValue().
Syntax:
public int hashCode()

This function does not accepts any parameter.

Return Value: This method returns a hash code value for this Character.
Below programs illustrate the Java.lang.Character.hashCode() function:
Program 1:
// Java program to demonstrate the// function when the value passed in the parameter// is a character import java.lang.*;  public class Gfg {      public static void main(String[] args)    {        // parameter ch        char ch = 'B';        // assigns character values        Character c = Character.valueOf(ch);                       // assign hashcodes of c1, c2 to i1, i2        int i = c.hashCode();                  // prints the character values        System.out.println("Hashcode of " + ch + " is " + i);    }}
Hashcode of B is 66

Program 2:
// Java program to demonstrate the// function when the value passed in the parameter// is a number import java.lang.*;  public class Gfg {      public static void main(String[] args)    {        // parameter ch        char ch = '6';        // assigns character values        Character c = Character.valueOf(ch);                       // assign hashcodes of ch         int i = c.hashCode();                  // prints the character values        System.out.println("Hashcode of " + ch + " is " + i);    }}
Hashcode of 6 is 54

Java-Character
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
How to create a folder if it does not exist in C#?

For creating a directory, we must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories.
It is always recommended to check if the Directory exist before doing any file operation in C# because the complier will throw exception if the folder does not exist.
using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}
The above code will create a Demo Folder in the D: directory.
Directory.CreateDirectory can also be used to create subfolders.
using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder\Sub Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}
The above code will create a Demo Folder with a Sub Folder in the D: directory.
Find the element that appears once in sorted array - JavaScript

Suppose, we have a sorted array of literals like this −
const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false.
For this array, the output should be 6
Following is the code −
const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
const firstNonDuplicate = arr => {
   let appeared = false;
   for(let i = 0; i < arr.length; i++){
      if(appeared){
         if(arr[i+1] !== arr[i]){
            appeared = false;
         };
      }else{
         if(arr[i+1] === arr[i]){
            appeared = true;
            continue;
         };
         return arr[i];
      };
   };
   return false;
};
console.log(firstNonDuplicate(arr));
Following is the output in the console −
6
Tryit Editor v3.7

HTML Web Storage
Tryit: HTML count the clicks
How to create a scroll pane using JavaFX?

A scroll pane holds a UI element and provides a scrollable view of it. In JavaFX, you can create a scroll pane by instantiating the javafx.scene.control.ScrollPane class. You can set content to the scroll pane using the setContent() method.
To add a scroll pane to a node −
To add a scroll pane to a node −
Instantiate the ScrollPane class.
Instantiate the ScrollPane class.
Create the desired node.
Create the desired node.
Set the node to the scroll pane using the setContent() method.
Set the node to the scroll pane using the setContent() method.
Set the dimensions of the scroll pane using the setter methods.
Set the dimensions of the scroll pane using the setter methods.
Add the scroll pane to the layout pane or group.
Add the scroll pane to the layout pane or group.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ScrollPaneActionExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\\images\\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting image to the image view
      imageView.setImage(image);
      //Setting the image view parameters
      imageView.setX(5);
      imageView.setY(0);
      imageView.setFitWidth(595);
      imageView.setPreserveRatio(true);
      //Creating the scroll pane
      ScrollPane scroll = new ScrollPane();
      scroll.setPrefSize(595, 200);
      //Setting content to the scroll pane
      scroll.setContent(imageView);
      //Setting the stage
      Group root = new Group();
      root.getChildren().addAll(scroll);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Scroll Pane Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Convert Image to Data URI with JavaScript

To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.
This will return the base64 encoded data URI of the image. For example,
if you have an image with id my-image, you can use the following −
function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
   const dataUrl = getDataUrl(event.currentTarget);
   console.log(dataUrl);
});
This will give the output −
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB
Machine Learning: Handling the missing values in Data: The Easy Way | by Akash Panchal | Towards Data Science

Most of the Machine Learning Algorithms cannot work with missing values in the features. See the below example of the Melbourne Housing Data.
Here, BuildingArea has 7130 rows with values while most of the features have 13580 rows with values.
Now, A few things you can do to deal with missing values
melbourne_data.dropna(subset=["BuildingArea"])
This will drop all the rows with the missing values. You can see that the number of rows has decreased now.
melbourne_data.drop("BuildingArea", axis=1)
This will drop the entire feature/attribute. See below, BuildingArea column is dropped now.
Approach A
If you think that the attribute is important enough and you must include for the training. You can fill the missing values.
Fill the missing values with what???
Well, you can replace the missing values with median, mean or zeros.
median = melbourne_data["BuildingArea"].median()melbourne_data["BuildingArea"].fillna(median, inplace=True)
This will replace all the missing values with the calculated median. Also, one thing you will notice now that the mean value of the attribute is changed as we’ve filled the missing values.
You may want to follow a similar process for “YearBuilt” attribute as well. And you will have to save the value of the median, as it will be needed later to fill the missing values in the Test-Set and the new data(Oh yes, didn’t think that).
Approach B: Introducing Imputer
SciKit-Learn provides Imputer class to use the above task with ease. You can use it following way:
First, you need to decide the strategy, it can be one of these: mean, median, most_frequent
Second, create the imputer instance using the decided strategy
# 1. Remove categorial melbourne_data = melbourne_data.select_dtypes(exclude=                    ["object"]).copy()# 2. Fit the numerical data to Imputerfrom sklearn.impute import SimpleImputerimputer = SimpleImputer(strategy="median")imputer.fit(melbourne_data)# 3.X = imputer.transform(melbourne_data)melbourne_data_tr = pd.DataFrame(X, columns=melbourne_data.columns,                     index=melbourne_data.index)
Now, this will calculate the median of all the attributes and fill the missing values of an attribute with the respective mean values.
Note: Not focusing on the Categorial values as they are not in the scope of this tutorial.
Python code: Full python code with all the three ways explained.
Streamlit code: Oh..you love streamlit too. Find the streamlit code here.
Data: Used Melbourne housing data.