code-rag-bench/online-tutorials huggingface dataset:
Node.js MySQL Select from Table

07 Oct, 2021
Introduction: Learn about Selecting data from MySQL database using node.js. We are going to use standard SELECT FROM SQL Query.
Syntax:
SELECT [column] FROM [table_name]
Example:
1) SELECT * FROM customers
selecting all columns from customers table.

2) SELECT name, address FROM customers
SQL users Table Preview:
Example 1: select all columns from users table
index.js
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // This query will be used to select columns    let query = 'SELECT * FROM users';      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log(rows);    });});
Output:
Example 2: select name column from users table
index.js
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // notice the name column below    let query = 'SELECT name FROM users';      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log(rows);    });});
Output:
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
wxPython – SetBackgroundColour() function in wx.StaticText

18 Jun, 2020
In this article we are going to learn about SetBackgroundColour() function associated with wx.StaticText class of wxPython. SetBackgroundColour() function is simply used to set background of a static text to a different colour.
It takes wx.Colour argument to set the background colour.
Syntax: wx.StaticText.SetBackgroundColour(self, colour)
Parameters:
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()      def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)        self.pnl = wx.Panel(self)          bmp = wx.Bitmap('right.png')        # CREATE STATICTEXT AT POINT (20, 20)        self.st = wx.StaticText(self.pnl, id = 1, label ="This is the Label.",                                 pos =(20, 20), size = wx.DefaultSize,                                 style = wx.ST_ELLIPSIZE_MIDDLE, name ="statictext")          # SET BACKGROUND COLOUR TO YELLOW        self.st.SetBackgroundColour((215, 252, 3, 255))        self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre()  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output Window:
Python wxPython-StaticText
Python-gui
Python-wxPython
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
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to Install SQL Workbench For MySQL on Linux?

06 Dec, 2021
MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation, and maintenance into a single integrated development environment for the MySQL database system. It was first released in 2014. It is owned by Oracle Corporation. It supports Windows, Linux, and Mac OS operating systems. In this article, We will know how can we install SQL Workbench on our Linux systems. 
Follow the below steps to install SQL 
Step 1: Open your browser and download SQL Workbench for your Linux system from here. You will see a screen as shown below then click on the Download button.
Step 2: After clicking on download you will get a confirmation screen, click on No thanks, just start my download on the left side of your screen.
Step 3: Open your terminal and navigate to that folder in which you have downloaded that workbench file using cd FolderName.
Step 4: Run installation command
After navigating to that folder, run the following command in your terminal to install MySQL Workbench.
sudo apt-get install ./fileNameOfInstallationPackage
After running the above command you will get a prompt screen. Choose Debian buster using your keyboard arrow buttons and press enter.
After that choose ok and press enter.
Step 5: On your terminal update your packages using the following command.
sudo apt-get update
Step 6: Install SQL workbench community. Now, we have to install MySQL Workbench Community. For this, I have used snap. You can also install this using the following command. You can learn more about snap from here.
snap install mysql-workbench-community
That’s it, Now SQL Workbench is now installed on your Linux system. To verify You can search MySQL Workbench on your app drawer.
Output:
To run click on the icon of MySQL Workbench.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
Java Examples - Validate email address format

How to validate an email address format?
Following example demonstrates how to validate e-mail address using matches() method of String class.
public class Main {
   public static void main(String[] args) {
      String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
      String email1 = "user@domain.com";
      Boolean b = email1.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email1+" :Valid = " + b);
      String email2 = "user^domain.co.in";
      b = email2.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email2+" :Valid = " + b);
   }
}
The above code sample will produce the following result.
is e-mail: user@domain.com :Valid = true
is e-mail: user^domain.co.in :Valid = false

The following is an example to validate an email address format.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) {
      List emails = new ArrayList();
      emails.add("sairamkrishna@tutorialspoint.com");
      emails.add("kittuprasad700@gmail.com");
      emails.add("sairamkrishna_mammahe%google-india.com");
      emails.add("sairam.krishna@gmail-indai.com");
      emails.add("sai#@youtube.co.in");
      emails.add("kittu@domaincom");
      emails.add("kittu#gmail.com");
      emails.add("@pindom.com");
      
      String regex = "^(.+)@(.+)$";
      Pattern pattern = Pattern.compile(regex);
      
      for (Object email : emails) {
         Matcher matcher = pattern.matcher((CharSequence) email);
         System.out.println(email + " : " + matcher.matches());
      } 
   }
}
The above code sample will produce the following result.
sairamkrishna@tutorialspoint.com : true
kittuprasad700@gmail.com : true
sairamkrishna_mammahe%google-india.com : false
sairam.krishna@gmail-indai.com : true
sai#@youtube.co.in : true
kittu@domaincom : true
kittu#gmail.com : false
@pindom.com : false
How to Compile, Decompile and Run C# Code in Linux?

23 Sep, 2021
C# is a modern multi-paradigm programming language developed by Microsoft and released in the year 2000. By multi-paradigm we mean that it includes static typing, strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented, and component-oriented programming disciplines. The syntax of C# is highly inspired from the JAVA syntax, therefore, it is easier to understand for most the developer what have some basic knowledge of C, C++, and JAVA. It was designed by  Anders Hejlsberg and developed by Mads Torgersen.
Firstly, we need to install mono-complete, to run software for Mono or Microsoft. NET.
Step 1: To Install mono-complete, open up your Linux terminal and type the following command, and hit enter.
Run the following command to set up the system before installing the mono.
sudo apt install gnupg ca-certificates
sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo “deb https://download.mono-project.com/repo/ubuntu stable-focal main” | sudo tee /etc/apt/sources.list.d/mono-official-stable.list
sudo apt update
Then run the following to install mono.
sudo apt install mono-complete
Step 2: Write a simple hello world program in C# and save the code in a file called geeks.cs.
C#
using System;  public class GFG {      static public void Main()    {        Console.WriteLine("Hello World!");        Console.ReadKey();           }}
Hello World!
Step 3: Now make this C# file an executable file. Navigate to the file and run the following command.
making executable
chmod +x geeks.cs
Here, +x means executable.
Step 4: Now we will be using the mcs compiler and create a Windows executable named geeks.exe from the source geeeks.cs.
mcs -out:geeks.exe geeks.cs
Output:
compiling c# code
After this, an executable file, geeks.cs, will be generated.
Step 5: Now to run this geeks.exe executable file, run the following command.
mono geeks.exe
Output:
Running c# code
Step 5: Press Enter to exit back to a default terminal prompt.
Step 6: To decompile this executable file run the following command:
monodis –output=geeks.txt geeks.exe
Output:
Decompiled c# code
The decompiled code will be saved in the newly generated file, geeks.txt. To view the decompiled file in the terminal, run the following command:
cat geeks.txt
Output should look like this:
Output of decompiled code
Blogathon-2021
Picked
Blogathon
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
WLAN Full Form

11 Sep, 2021
WLAN stands for Wireless Local Area Network. WLAN is a local area network that uses radio communication to provide mobility to the network users, while maintaining the connectivity to the wired network. A WLAN basically, extends wired local area network. WLAN’s are built attaching a device called the access point(AP) to the edge of the wired network. Clients communicate with the AP using a wireless network adapter which is similar in function to a ethernet adapter. It is also called a LAWN that is Local area wireless network. 
The performance of WLAN is high compared to other wireless networks. The coverage of WLAN is within a campus or building or that tech parks. It is used in the mobile propagation of wired networks. The standards of WLAN are HiperLAN, Wi-Fi, and IEEE 802.11. It offers service to the desktop laptop, mobile application and all the devices works on the Internet. WLAN is an affordable method and can be set up in 24 hours. WLAN gives users the mobility to move around within a local coverage area and still be connected to the network. Most latest brands are based on IEE 802.11 standards, which are the WI-FI brand name. 
History : A professor at University of Hawaii who’s name was Norman Abramson, developed the world’s first wireless computer communication network. In 1979, Gfeller and u.Bapst published a paper in the IEE proceedings reporting an experimental wireless local area network using diffused infrared communications. The first of the IEEE workshops on Wireless LAN was held in 1991. 
Characteristics :  
Seamless operation.
Low power for battery use.
Simple management, easy to use for everyone.
Protection of investment in wired networks.
Robust transmission technology
Advantages :  
Installation speed and simplicity.
Installation flexibility.
Reduced cost of ownership.
Reliability.
Mobility.
Robustness.
Disadvantages :  
Slower bandwidth.
Security for wireless LAN’s is the prime concern.
Less capacity.
Wireless networks cost four times more than wired network cards.
Wireless devices emit low levels of RF which can be harmful to our health.
 
anikakapoor
Picked
Computer Networks
Full Form
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get array dimensions and size of a dimension in Julia – size() Method

26 Mar, 2020
The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.
Syntax:size(A::AbstractArray)orsize(A::AbstractArray, Dim)
Parameters:
A: Specified array
Dim: Specified dimension
Returns: It returns a tuple containing the dimensions of the specified array.
Example 1:
# Julia program to illustrate # the use of Array size() method  # Finding a tuple containing the dimension of# the specified 1D array A.A = [5, 10, 15, 20]println(size(A))  # Finding a tuple containing the dimension of# the specified 2D array B of size 2*2B = [5 10; 15 20]println(size(B))  # Finding a tuple containing the dimension of# the specified 3D array C of size 2*2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims=3)println(size(C))
Output:Example 2:
# Julia program to illustrate # the use of Array size() method     # Finding a tuple containing the dimension of# the specified 1D array A.A = [1, 2, 3];println(size(A, 3))     # Finding a tuple containing the dimension of# the specified 2D array B of size 3*2B = [2 4; 6 8; 10 12];println(size(B, 2))     # Finding a tuple containing the dimension of# the specified 3D array C of size 2*2*4C = cat([10 15; 20 25], [30 35; 40 45],        [50 55; 60 65], [70 75; 80 85], dims=3);println(size(C, 2))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tournament Selection (GA)

11 Jul, 2022
Tournament Selection is a Selection Strategy used for selecting the fittest candidates from the current generation in a Genetic Algorithm. These selected candidates are then passed on to the next generation. In a K-way tournament selection, we select k-individuals and run a tournament among them. Only the fittest candidate amongst those selected candidates is chosen and is passed on to the next generation. In this way many such tournaments take place and we have our final selection of candidates who move on to the next generation. It also has a parameter called the selection pressure which is a probabilistic measure of a candidate’s likelihood of participation in a tournament. If the tournament size is larger, weak candidates have a smaller chance of getting selected as it has to compete with a stronger candidate. The selection pressure parameter determines the rate of convergence of the GA. More the selection pressure more will be the Convergence rate. GAs are able to identify optimal or near-optimal solutions over a wide range of selection pressures. Tournament Selection also works for negative fitness values.
Algorithm --
1.Select k individuals from the population and perform a tournament amongst them
2.Select the best individual from the k individuals
3. Repeat process 1 and 2 until you have the desired amount of population

Let us have a 3-way tournament selection and our desired population size is 6 and the initial population with their fitness scores is [1, 2, 3, 4, 5, 6]. Our first tournament will look something like this (see the diagram) and the winner candidate with fitness value 6 moves on to the next generation.
Tournament Selection
If the best candidate is selected with probability pthen the next best candidate will be selected with a probability of p*(1-p)and the next one with p*(1-p)2and so on ...
References —1.http://wpmedia.wolfram.com/uploads/sites/13/2018/02/09-3-2.pdf2.https://en.wikipedia.org/wiki/Tournament_selection
Genetic Algorithms
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Importance of transferTo() method of InputStream in Java 9?

The transferTo() method has been added to the InputStream class in Java 9. This method has been used to copy data from input streams to output streams in Java. It means it reads all bytes from an input stream and writes the bytes to an output stream in the order in which they are reading.
public long transferTo(OutputStream out) throws IOException
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TransferToMethodTest {
   public void testTransferTo() throws IOException {
      byte[] inBytes = "tutorialspoint".getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(inBytes);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try {
         bis.transferTo(bos);
         byte[] outBytes = bos.toByteArray();
         System.out.println(Arrays.equals(inBytes, outBytes));
      } finally {
         try {
            bis.close();
         } catch(IOException e) {
            e.printStackTrace();
         }
         try {
            bos.close();
         } catch(IOException e) {
              e.printStackTrace();
         }
      }
   }
   public static void main(String args[]) throws Exception {
      TransferToMethodTest test = new TransferToMethodTest();
      test.testTransferTo();
   }
}
true
How do I set the default value for a column in MySQL?

To set the default value, use the DEFAULT keyword.
Let us first create a table −
mysql> create table DemoTable758 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.66 sec)
Following is the query to set default value for a column −
mysql> alter table DemoTable758 add column Colors ENUM('RED','GREEN','BLUE','ORANGE','YELLOW') DEFAULT 'YELLOW';
Query OK, 0 rows affected (0.44 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again −
mysql> desc DemoTable758;
This will produce the following output -
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Field     | Type                                         | Null | Key | Default | Extra          |
+-----------+----------------------------------------------+------+-----+---------+----------------+
| Id        | int(11)                                      | NO   | PRI | NULL    | auto_increment |
| FirstName | varchar(100)                                 | YES  |     | NULL    |                |
| Colors    | enum('RED','GREEN','BLUE','ORANGE','YELLOW') | YES  |     | YELLOW  |                |
+-----------+----------------------------------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Insert some records in the table using insert command. Here, we haven’t inserted the value for 2nd column with FirstName “John”. The default value “YELLOW” will get placed there −
mysql> insert into DemoTable758(FirstName) values('John');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable758(FirstName,Colors) values('Carol','RED');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable758;
This will produce the following output -
+----+-----------+--------+
| Id | FirstName | Colors |
+----+-----------+--------+
|  1 | John      | YELLOW |
|  2 | Carol     | RED    |
+----+-----------+--------+
2 rows in set (0.00 sec)
Groovy - Dates & Times equals()

Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
public boolean equals(Object obj)

obj - the object to compare with.
True if the objects are the same; false otherwise.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      Date olddate = new Date("05/11/2015");
      Date newdate = new Date("05/11/2015");
      Date latestdate = new Date();
		
      System.out.println(olddate.equals(newdate));
      System.out.println(latestdate.equals(newdate));
   } 
}   
When we run the above program, we will get the following result −
true 
false


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to show all X-axis labels in a bar graph created by using barplot function in R?

In base R, the barplot function easily creates a barplot but if the number of bars is large or we can say that if the categories we have for X-axis are large then some of the X-axis labels are not shown in the plot. Therefore, if we want them in the plot then we need to use las and cex.names.
Consider the below data and bar graph −
 Live Demo
> x<-sample(1:5,20,replace=TRUE)
> names(x)<-rep(c("IN","CO","LA","NY"),times=5)
> barplot(x)
Showing all the X-axis labels −
> barplot(x,las=2,cex.names=0.5)
What is 3-way merge or merge commit in Git?

Let us look at an example of a 3-way merge. In this example, the Feature branch is two commits ahead of the Master branch.
Diagram 1
Before we merge it with Master, let us say we have added an additional commit to the Master as shown in the below diagram.
Diagram 2
Due to the commit performed on the Master branch, both our branches Master and Feature are now diverged.
This means we have some changes in the Master branch that is not present in the Feature branch. If we perform a merge in this case, Git cannot move the master pointer towards the Feature branch.
If git simply moves the Master pointer to the Feature pointer, then the latest commit C6 performed on the Master branch will be lost.
So how do we perform a merge if the branches are diverged?
When we want to merge the branches that are diverged, Git creates a new commit (Merge Commit) and combines the changes of these two branches as shown in the below diagram.
Diagram 3
The reason it is called a 3-way merge is because the Merge Commit is based on 3 different commits.
The common ancestor of our branches, in this case commit number C3. This commit contains code before we diverge into different branches.
The common ancestor of our branches, in this case commit number C3. This commit contains code before we diverge into different branches.
The tip of the Master branch, that is the last commit performed on the Master branch - C6
The tip of the Master branch, that is the last commit performed on the Master branch - C6
The tip of the Feature branch, the last commit performed on the Feature branch - C5
The tip of the Feature branch, the last commit performed on the Feature branch - C5
To merge the changes from both the branches, Git looks at the three different snapshots - the before snapshot and the after snapshots. Based on these snapshots, Git combines the changes by creating the new commit called the Merge Commit.
$ git init
$ echo one>1.txt
$ git add .
$ git commit -m 'c1'
$ echo two>2.txt
$ git add .
$ git commit -m 'c2'
$ echo three>3.txt
$ git add .
$ git commit -m 'C3'
$ git branch feature
$ git switch feature
$ echo four>4.txt
$ git add .
$ git commit -m 'c4'
$ echo five>5.txt
$ git add .
$ git commit -m 'c5'
$ git switch master
$echo six>6.txt
$ git add .
$ git commit -m 'c6'
$ git merge feature
$ git log --oneline --all --graph
hint: Waiting for your editor to close the file... unix2dos: converting file E:/git_clone/test_repo/.git/MERGE_MSG to DOS format...
dos2unix: converting file E:/git_clone/test_repo/.git/MERGE_MSG to Unix format...
Merge made by the 'recursive' strategy.
4.txt | 1 +
5.txt | 1 +
2 files changed, 2 insertions(+)
create mode 100644 4.txt
create mode 100644 5.txt

* e1ce060 (HEAD -> master) Merge branch 'feature'
|\
| * 3435c89 (feature) c5
| * 7e7761b c4
* | 5618675 c6
|/
* 6ad93bf C3
* 9031c20 c2
* 3f68f83 c1
MongoDB query to convert string to int?

To convert string to int, use parseInt() in MongoDB. Let us first create a collection with documents −
> db.demo369.insertOne({"Price":"1000000"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2e32ae06a1609a00aed")
}
> db.demo369.insertOne({"Price":"1747864"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2e92ae06a1609a00aee")
}
> db.demo369.insertOne({"Price":"19548575"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2ee2ae06a1609a00aef")
}
Display all documents from a collection with the help of find() method −
> db.demo369.find();
This will produce the following output −
{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : "1000000" }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : "1747864" }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : "19548575" }
Following is the query to convert string to int −
> db.demo369.find().forEach( function (d) {
...    d.Price= parseInt(d.Price);
...    db.demo369.save(d);
... });
Display all documents from a collection with the help of find() method −
> db.demo369.find();
This will produce the following output −
{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : 1000000 }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : 1747864 }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : 19548575 }
How to convert hex string into int in Python?

Hex strings generally have a "0x" prefix. If you have this prefix and a valid string, you can use int(string, 0) to get the integer. The 0 is provided to tell the function to automatically interpret the base from prefix. For example:
>>> int("0xfe43", 0)
65091
If you don't have a "0x" prefix, you can pass 16 instead of 0 to specify the base of the number. For example:
>>> int("fe43", 16)
65091
8085 program to find the sum of first n natural numbers - GeeksforGeeks

24 May, 2019
Problem – Write an assembly language program for calculating the sum of first n natural numbers using 8085 microprocessor.
Example –
Input : 04H
Output : 0AH
as 01+02+03+04 = 10 in decimal => 0AH

The formula for calculating the sum of first n natural numbers is .
Algorithm –
With n as the input, increment it to obtain n+1.Multiply n with n+1.Divide the product obtained by 2.
With n as the input, increment it to obtain n+1.
Multiply n with n+1.
Divide the product obtained by 2.
In 8085 microprocessor, no direct instruction exists to multiply two numbers, so multiplication is done by repeated addition as 4×5 is equivalent to 4+4+4+4+4 (i.e., 5 times).Input: 04HAdd 04H 5 timesProduct: 14H(2010)
Similarly, in 8085 microprocessor, no direct instruction exists to divide two numbers, so division is done by repeated subtraction.Input: 14HKeep subtracting 2 from the input till it reduces to 0.Since subtraction has to be performed 1010 times before 14H becomes 0, the quotient is 1010 => 0AH.
Steps –
Load the data from the memory location (201BH, arbitrary choice) into the accumulatorMove this data into BIncrement the value in the accumulator by one and move it to the register CInitialise the accumulator with 0Multiplication: Keep adding B to accumulator. The number of times B has to be added is equal to the value of CInitialise B with 00H. B will store the quotient of the divisionInitialise C with 02H. This is the divisor for the divisionDivision: Keep subtracting C from A till A becomes 0. For each subtraction, increment B by oneThe final answer is in B. Move it to A. Then store the value of A in 201CH (arbitrary choice again)
Load the data from the memory location (201BH, arbitrary choice) into the accumulator
Move this data into B
Increment the value in the accumulator by one and move it to the register C
Initialise the accumulator with 0
Multiplication: Keep adding B to accumulator. The number of times B has to be added is equal to the value of C
Initialise B with 00H. B will store the quotient of the division
Initialise C with 02H. This is the divisor for the division
Division: Keep subtracting C from A till A becomes 0. For each subtraction, increment B by one
The final answer is in B. Move it to A. Then store the value of A in 201CH (arbitrary choice again)
201CH contains the final answer.
Store the value of n in 201BH. The sum can be found at 201CH.
nidhi_biet
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Addressing modes in 8085 microprocessor
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Computer Organization | RISC and CISC
Interrupts
Architecture of 8085 microprocessor
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Difference between Von Neumann and Harvard Architecture
How to clear all values from the Hash table in PowerShell?

Hash table in the PowerShell session is created temporarily. It is like a variable, when the session is closed, hash table is deleted automatically. If you want to delete all the values from the hash table at once but retaining the hash table variable, you need to use the Clear() method.
We have the hash table below created already.
$htable = [Ordered]@{EmpName="Charlie";City="New York";EmpID="001"}
PS C:\WINDOWS\system32> $htable
Name       Value
----       -----
EmpName    Charlie
City       New York
EmpID      001
To clear the above hashtable,
$htable.Clear()
If you check the hash table data, it won’t display anything now but it is still the OrderedDictionary and not converted into any variable data type.
Set conditions for columns with values 0 or 1 in MySQL

To set conditions, use CASE WHEN statement in MySQL. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int,
   -> Value3 int,
   -> Value4 int
   -> );
Query OK, 0 rows affected (0.98 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1,0,1,1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(1,0,1,0);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(1,1,1,1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(0,0,0,0);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------+--------+--------+--------+
| Value1 | Value2 | Value3 | Value4 |
+--------+--------+--------+--------+
|     1 |       0 |      1 |      1 |
|     1 |       0 |      1 |      0 |
|     1 |       1 |      1 |      1 |
|     0 |       0 |      0 |      0 |
+--------+--------+--------+--------+
4 rows in set (0.00 sec)
Here is the query to set conditions for columns with values 0 or 1 in MySQL−
mysql> select case when Value1+Value2+Value3+Value4 < 2 then 'NotGood' else 'Good' end as Status from DemoTable;
This will produce the following output −
+---------+
| Status  |
+---------+
| Good    |
| Good    |
| Good    |
| NotGood |
+---------+
4 rows in set (0.00 sec)
Python program to find the maximum of three numbers

In this tutorial, we are going to write a program which finds the max amount from the three figures. We will have three number, and our goal is to find out the maximum number from those three numbers.
Let's see some sample test cases for better understanding.
Input:
a, b, c = 2, 34, 4
Output:
34
Input:
a, b, c = 25, 3, 12
Output:
25
Input:
a, b, c = 5, 5, 5
Output:
5
Follow the below steps to find out the max number among three numbers.
1. Initialise three numbers a, b, c.
2. If a is higher than b and c then, print a.
3. Else if b is greater than c and a then, print b.
4. Else if c is greater than a and b then, print c.
5. Else print any number.
Let's see the code for the above algorithm.
## initializing three numbers
a, b, c = 2, 34, 4
## writing conditions to find out max number
## condition for a
if a > b and a > c:
   ## printing a
   print(f"Maximum is {a}")
## condition for b
elif b > c and b > a:
   ## printing b
   print(f"Maximum is {b}")
## condition for c
elif c > a and c > b:
   ## printing
   print(f"Maximum is {c}")
## equality case
else:
   ## printing any number among three
   print(a)
If you run the above program, you will get the following output.
Maximum is 34
Let's execute the code once again for different test case
## initializing three numbers
a, b, c = 5, 5, 5
## writing conditions to find out max number
## condition for a
if a > b and a > c:
   ## printing a
   print(f"Maximum is {a}")
## condition for b
elif b > c and b > a:
   ## printing b
   print(f"Maximum is {b}")
## condition for c
elif c > a and c > b:
   ## printing
   print(f"Maximum is {c}")
## equality case
else:
   ## printing any number among three
   print(f"Maximum is {a}")
If you run the above program, you will get the following output.
Maximum is 5
If you have any doubts regarding the tutorial, mention them in the comment section.
getopt() function in C to parse command line arguments - GeeksforGeeks

10 Sep, 2018
The getopt() function is a builtin function in C and is used to parse command line arguments.
Syntax:
getopt(int argc, char *const argv[], const char *optstring)

optstring is simply  a list of characters, 
each representing a single character option.

Return Value: The getopt() function returns different values:
If the option takes a value, that value is pointer to the external variable optarg.
‘-1’ if there are no more options to process.
‘?’ when there is an unrecognized option and it stores into external variable optopt.
If an option requires a value (such as -f in our example) and no value is given, getopt normally returns ?.By placing a colon as the first character of the options string, getopt returns: instead of ? when no value is given.
Generally, the getopt() function is called from inside of a loop’s conditional statement. The loop terminates when the getopt() function returns -1. A switch statement is then executed with the value returned by getopt() function.
A second loop is used to process the remaining extra arguments that cannot be processed in the first loop.
Below program illustrate the getopt() function in C:
// Program to illustrate the getopt()// function in C  #include <stdio.h> #include <unistd.h>   int main(int argc, char *argv[]) {    int opt;          // put ':' in the starting of the    // string so that program can     //distinguish between '?' and ':'     while((opt = getopt(argc, argv, “:if:lrx”)) != -1)     {         switch(opt)         {             case ‘i’:             case ‘l’:             case ‘r’:                 printf(“option: %c\n”, opt);                 break;             case ‘f’:                 printf(“filename: %s\n”, optarg);                 break;             case ‘:’:                 printf(“option needs a value\n”);                 break;             case ‘?’:                 printf(“unknown option: %c\n”, optopt);                break;         }     }           // optind is for the extra arguments    // which are not parsed    for(; optind < argc; optind++){             printf(“extra arguments: %s\n”, argv[optind]);     }          return 0;}
Output:
C-Functions
C-Library
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Strings in C
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to clear the global variables in Postman?

We can clear the Global variables in Postman at runtime with the help of scripts. This is done with the help of the pm.* function. The script to clear the Global variables can be incorporated either in the Tests or Pre-Request Script tab
To clear the Global variable, the script should be −To clear the Global variable, the script should be −
pm.globals.unset('<name of Global variable>')
Let us try to clear the Global variable url.
Step1 − Add the below script in the Pre-request Script tab −
pm.globals.unset('url')
Step2 − Click on Send to execute a request.
Step3 − After the Response is received, click on the eye icon to the right upper corner of the Postman application. Now, it no longer shows the Global variable url which was previously available.
Different ways to format long with Java System.out.format

The System.out.format is used in Java to format output. Here, let’s say the following is our long.
long val = 787890;

To format, we have considered the following that justifies the output.
System.out.format("%d%n", val);
System.out.format("%9d%n", val);
System.out.format("%+9d%n", val);
System.out.format("%08d%n", val);
System.out.format("%,9d%n", val);

The following is the complete example that displays the difference in output as well.
 Live Demo
import java.util.Locale;
public class Demo {
   public static void main(String []args) {
      long val = 787890;
      System.out.format("%d%n", val);
      System.out.format("%9d%n", val);
      System.out.format("%+9d%n", val);
      System.out.format("%08d%n", val);
      System.out.format("%,9d%n", val);
   }
}
Here is the output. You can easily notice the differences in format.
787890
   787890
  +787890
00787890
  787,890
Static blocks in Java with example

The static block executes when classloader loads the class. A static block is invoked before main()
method. Let us see an example −
 Live Demo
class Demo{
   static int val_1;
   int val_2;
   static{
      val_1 = 67;
      System.out.println("The static block has been called.");
   }
}
public class Main{
   public static void main(String args[]){
      System.out.println(Demo.val_1);
   }
}
The static block has been called.
67
A class named Demo contains a static integer value and a normal integer value. In a static block, a
value is defined, and in the main class, an instance of the Demo class is created and the static integer
is accessed from there.
How to download any file and save it to the desired location using Selenium Webdriver?

We can download any file and save it to the desired location with Selenium. This can be done by creating an instance of the FirefoxOptions class. Then with the help of the addPreference method, we have to set the browser preferences.
We shall also specify the path where the file has to be downloaded with the help of the addPreference method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class FileDwnload{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      // create object of FirefoxOptions class
      FirefoxOptions profile = new FirefoxOptions();
      // adding browser preferences with addPreference method
      profile.addPreference("browser.download.folderList", 2);
      // location of downloaded file
      profile.addPreference("browser.download.dir", "C:\\Users\\ghs6kor\\Documents\\Download");
      profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel," + "application/x-excel,application/vnd.ms-excel," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml");
      profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/vnd.ms- excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml");
      profile.addPreference("browser.helperApps.alwaysAsk.force", false);
      profile.addPreference
      ("browser.download.manager.alertOnEXEOpen", false);
      profile.addPreference("browser.download.manager.focusWhenStarting", false);
      profile.addPreference("browser.download.manager.useWindow", false);
      profile.addPreference("browser.download.manager.showAlertOnComplete", false);
      profile.addPreference("browser.download.manager.closeWhenDone", false);
      // connecting browser options to webdriver
      WebDriver driver = new FirefoxDriver(profile);
      driver.get("https://the-internet.herokuapp.com/download");
      //maximize window
      driver.manage().window().maximize();
      // identify element and start download
      driver.findElement(By.linkText("xls-sample1.xls")).click();
   }
}
Also, the file gets downloaded at the specified location.
How to return an array from a method in Java?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
 Live Demo
import java.util.Arrays;
import java.util.Scanner;

public class ReturningAnArray {
   public int[] createArray() {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created:: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      return myArray;
   }

   public static void main(String args[]) {
      ReturningAnArray obj = new ReturningAnArray();
      int arr[] = obj.createArray();
      System.out.println("Array created is :: "+Arrays.toString(arr));
   }
}
Enter the size of the array that is to be created::
5
Enter the elements of the array ::
23
47
46
58
10
Array created is :: [23, 47, 46, 58, 10]
Extract the month and year in the following format: “mm-yyyy” (month year) along with all columns in MySQL?

For month and year in a specific format, use DATE_FORMAT() along with STR_TO_DATE(). Let us first create a table −
mysql> create table DemoTable1931
   (
   ShippingDate varchar(40)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1931 values('10-11-2017');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('31-01-2019');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('02-02-2018');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1931 values('10-06-2013');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1931;
This will produce the following output −
+--------------+
| ShippingDate |
+--------------+
| 10-11-2017   |
| 31-01-2019   |
| 02-02-2018   |
| 10-06-2013   |
+--------------+
4 rows in set (0.00 sec)
Following is the query to extract the month and year in the format “mm-yyyy”, along with all columns −
mysql> select date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') from DemoTable1931;
This will produce the following output −
+-----------------------------------------------------------+
| date_format(str_to_date(ShippingDate,'%d-%m-%Y'),'%m-%Y') |
+-----------------------------------------------------------+
| 11-2017                                                   |
| 01-2019                                                   |
| 02-2018                                                   |
| 06-2013                                                   |
+-----------------------------------------------------------+
4 rows in set (0.00 sec)
PHP | DateTime modify() Function - GeeksforGeeks

10 Oct, 2019
The DateTime::modify() function is an inbuilt function in PHP which is used to modify or can alter the timestamp of a DateTime object.
Syntax:
Object oriented style:DateTime DateTime::modify( string $modify )
DateTime DateTime::modify( string $modify )
Procedural style:DateTime date_modify( DateTime $object, string $modify )
DateTime date_modify( DateTime $object, string $modify )
Parameters: This function uses two parameters as mentioned above and described below:
$object: It specifies the DateTime object returned by date_create() function. This object is modified by DateTime::modify() function.
$modify: It specifies the date/time string. It is incremented or decremented to modify the DateTime object.
Return Value: This function returns the modified DateTime object on success or False on failure.
Below programs illustrate the DateTime::modify() function in PHP:
Program 1 :
<?php// PHP program to illustrate // DateTime::modify() function    // Creating a DateTime object$datetime = new DateTime('2019-09-30');  // Calling of date DateTime::modify() function// with the increment of 5 days as parameters$datetime->modify('+5 day');  // Getting the modified date in "y-m-d" formatecho $datetime->format('Y-m-d');  ?>
2019-10-05

Program 2:
<?php// PHP program to illustrate the// DateTime::modify() function    // Creating a DateTime object$datetime = new DateTime('2019-09-30');  // Calling of date DateTime::modify() function// with the increment of 5 months as parameters$datetime->modify('+5 month');  // Getting the modified date in "y-m-d" formatecho $datetime->format('Y-m-d');  ?>
2020-03-01

Reference: https://www.php.net/manual/en/datetime.modify.php
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?