title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
How to Retrieve PDF File From Firebase Realtime Database in Android? | 09 Mar, 2021
When we are creating an android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from firebase. Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is its Firebase Realtime Database. By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. We will be creating our storage bucket and we can insert our pdf there and get it directly into our app.
We will be creating two Activities in this project. In one activity there will e a single Button and in another activity, we are viewing the pdf file. So when the user will click on the Button an AlertBox will be shown with there options “Download“, “View“, and “Cancel“. So the user will choose whether he/she want to View or Download the pdf. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.
After completing this process you will get to see the below screen.
Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section.
implementation ‘com.google.firebase:firebase-database:19.6.0’
If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app. Also, add the following dependency.
implementation ‘com.github.barteksc:android-pdf-viewer:2.8.2’
Now sync the project from the top right corner option of Sync now.
Step 3: Add Internet permission in the AndroidManifest.xml file
Navigate to the AndroidManifest.xml file and add the below permission for getting internet permission in the app.
<uses-permission android:name=”android.permission.INTERNET”/>
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!--We will click on it to view pdf--> <Button android:id="@+id/view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@color/black" android:padding="10dp" android:text="Click here to View pdf " android:textSize="10dp" /> </LinearLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class MainActivity extends AppCompatActivity { Button view; DatabaseReference database; String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view = findViewById(R.id.view); // Initialising the reference to database database = FirebaseDatabase.getInstance().getReference().child("pdf"); database.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // getting a DataSnapshot for the location at the specified // relative path and getting in the link variable message = dataSnapshot.getValue(String.class); } // this will called when any problem // occurs in getting data @Override public void onCancelled(@NonNull DatabaseError databaseError) { // we are showing that error message in toast Toast.makeText(MainActivity.this, "Error Loading Pdf", Toast.LENGTH_SHORT).show(); } }); // After clicking here alert box will come view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { CharSequence options[] = new CharSequence[]{ "Download", "View", "Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); builder.setTitle("Choose One"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // we will be downloading the pdf if (which == 0) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(message)); startActivity(intent); } // We will view the pdf if (which == 1) { Intent intent = new Intent(v.getContext(), ViewPdfActivity.class); intent.putExtra("url", message); startActivity(intent); } } }); builder.show(); } }); }}
Step 6: Create a new ViewpdfActivity class
Please refer to How to Create New Activity in Android Studio and name the activity as ViewpdfActivity. This activity is used for viewing the pdf file.
Step 7: Working with the activity_view_pdf.xml file
Navigate to the app > res > layout > activity_view_pdf.xml and add the below code to that file. Below is the code for the activity_view_pdf.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ViewPdfActivity"> <com.github.barteksc.pdfviewer.PDFView android:id="@+id/abc" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
Step 8: Working with the ViewpdfActivity.java file
Go to the ViewpdfActivity.java file and refer to the following code. Below is the code for the ViewpdfActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog;import android.os.AsyncTask;import android.os.Bundle; import com.github.barteksc.pdfviewer.PDFView; import java.io.BufferedInputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL; public class ViewPdfActivity extends AppCompatActivity { String urls; PDFView pdfView; ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_pdf); pdfView = findViewById(R.id.abc); // Firstly we are showing the progress // dialog when we are loading the pdf dialog = new ProgressDialog(this); dialog.setMessage("Loading.."); dialog.show(); // getting url of pdf using getItentExtra urls = getIntent().getStringExtra("url"); new RetrivePdfStream().execute(urls); } // Retrieving the pdf file using url class RetrivePdfStream extends AsyncTask<String, Void, InputStream> { @Override protected InputStream doInBackground(String... strings) { InputStream inputStream = null; try { // adding url URL url = new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // if url connection response code is 200 means ok the execute if (urlConnection.getResponseCode() == 200) { inputStream = new BufferedInputStream(urlConnection.getInputStream()); } } // if error return null catch (IOException e) { return null; } return inputStream; } @Override // Here load the pdf and dismiss the dialog box protected void onPostExecute(InputStream inputStream) { pdfView.fromStream(inputStream).load(); dialog.dismiss(); } }}
Step 9: Adding pdf on firebase storage and copy the link of that pdf
In firebase go to the Storage option then click on Get Started button
After that click on the Upload file option to insert a pdf on firebase storage.
After that click on the pdf that you inserted then the from pdf details come in the right section then click on the access token and copy the pdf URL.
Step 10: Add that pdf URL to the real-time database
Go to the Realtime database option then add these values to the database. Inside that screen click on Realtime Database in the left window.
After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.
In this project, we are adding our rules as true for reading as well as a write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself. Inside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the “+” option on the right side and click on that option. After clicking on that option. Add the data as added in the below image. Make sure to add “pdf” in the Name field because we are setting our reference for Firebase as “pdf”. So we have to set it to “pdf”. You can change your reference and also change it in the Database. Inside the value field, paste the copied pdf url. This will be the string which we are going to display inside our pdfview. After adding data click on the add button and your data will be added in Firebase and this data will be displayed in your app.
Output:
Firebase
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 736,
"s": 54,
"text": "When we are creating an android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from firebase. Firebase Realtime Database is the back... |
How to catch OSError Exception in Python? | OSError serves as the error class for the os module, and is raised when an error comes back from an os-specific function.
We can re-write the given code as follows to handle the exception and know its type.
#foobar.py
import os
import sys
try:
for i in range(5):
print i, os.ttyname(i)
except Exception as e:
print e
print sys.exc_type
If we run this script at linux terminal
$ python foobar.py
We get the following output
OUTPUT
0 /dev/pts/0
1 /dev/pts/0
2 /dev/pts/0
3 [Errno 9] Bad file descriptor
<type 'exceptions.OSError'> | [
{
"code": null,
"e": 1309,
"s": 1187,
"text": "OSError serves as the error class for the os module, and is raised when an error comes back from an os-specific function."
},
{
"code": null,
"e": 1394,
"s": 1309,
"text": "We can re-write the given code as follows to handle the exce... |
Python – PyTorch numel() method | 26 May, 2020
PyTorch torch.numel() method returns the total number of elements in the input tensor.
Syntax: torch.numel(input)
Arguments
input: This is input tensor.
Return: It returns the length of the input tensor.
# Importing the PyTorch library import torch # A constant tensor of size na = torch.randn(4, 6)print(a) # Applying the numel function and # storing the result in 'out'out = torch.numel(a)print(out)
Output:
-0.8263 0.9807 -1.4688 0.2117 -0.8356 -0.0228
-0.8815 1.3652 -0.1892 -1.1241 0.2755 1.3006
0.0559 0.2389 0.7944 2.6587 -2.0908 1.2973
-0.2056 0.4110 0.2163 0.3091 0.5559 -0.2468
[torch.FloatTensor of size 4x6]
24
Example 2:
# Importing the PyTorch library import torch # A constant tensor of size na = torch.FloatTensor([1, 4, 6, 8])print(a) # Applying the numel function and # storing the result in 'out'out = torch.numel(a)print(out)
Output:
1
4
6
8
[torch.FloatTensor of size 4]
4
Python-PyTorch
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "PyTorch torch.numel() method returns the total number of elements in the input tensor."
},
{
"code": null,
"e": 142,
"s": 115,
"text": "Syntax: torch.numel... |
How to Append a Character to a String in C | 22 Jun, 2021
Given a string str and a character ch, this article tells about how to append this character ch to this string str at the end.Examples:
Input: str = "Geek", ch = 's'
Output: "Geeks"
Input: str = "skee", ch = 'G'
Output: "skeeG"
Approach:
Get the string str and character chUse the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.h is the header file required for string functions.Syntax:
Get the string str and character ch
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.h is the header file required for string functions.Syntax:
char *strncat(char *dest, const char *src, size_t n)
Parameters: This method accepts the following parameters:
dest: the string where we want to append.
src: the string from which ‘n’ characters are going to append.
n: represents the maximum number of character to be appended. size_t is an unsigned integral type.
3. Print or return the appended string str.
Below is the implementation of the above approach:
C
// C program to Append a Character to a String #include <stdio.h>#include <string.h> int main(){ // declare and initialize string char str[6] = "Geek"; // declare and initialize char char ch = 's'; // print string printf("Original String: %s\n", str); printf("Character to be appended: %c\n", ch); // append ch to str strncat(str, &ch, 1); // print string printf("Appended String: %s\n", str); return 0;}
Original String: Geek
Character to be appended: s
Appended String: Geeks
bohmann2
C-String
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 190,
"s": 52,
"text": "Given a string str and a character ch, this article tells about how to append this character ch to this string str at the end.Examples: "
},
{
"code": null,
"e":... |
SQLite - Indexes | Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index.
Following is the basic syntax of CREATE INDEX.
CREATE INDEX index_name ON table_name;
A single-column index is one that is created based on only one table column. The basic syntax is as follows −
CREATE INDEX index_name
ON table_name (column_name);
Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows −
CREATE UNIQUE INDEX index_name
on table_name (column_name);
A composite index is an index on two or more columns of a table. The basic syntax is as follows −
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice.
Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.
Example
Following is an example where we will create an index in COMPANY table for salary column −
sqlite> CREATE INDEX salary_index ON COMPANY (salary);
Now, let's list down all the indices available in COMPANY table using .indices command as follows −
sqlite> .indices COMPANY
This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index which got created when the table itself was created.
salary_index
sqlite_autoindex_COMPANY_1
You can list down all the indexes database wide as follows −
sqlite> SELECT * FROM sqlite_master WHERE type = 'index';
An index can be dropped using SQLite DROP command. Care should be taken when dropping an index because performance may be slowed or improved.
Following is the basic syntax is as follows −
DROP INDEX index_name;
You can use the following statement to delete previously created index.
sqlite> DROP INDEX salary_index;
Although indexes are intended to enhance the performance of a database, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered.
Indexes should not be used in −
Small tables.
Tables that have frequent, large batch update or insert operations.
Columns that contain a high number of NULL values.
Columns that are frequently manipulated. | [
{
"code": null,
"e": 3002,
"s": 2772,
"text": "Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book."
},
{
"code": n... |
Adding Labels to Method and Functions in Java - GeeksforGeeks | 29 Oct, 2020
The concept of labels in Java is being taken from assembly language. In Java break and continue are the control statements that control the flow of the program. Labels too can be considered as the control statement, but there is one mandatory condition, that within the loop, the label can only be used with break and continue keyword.
Usage of Labels:
The break statement is helpful for coming out of the inner loop after the occurrence of some conditions, and the label is used to come out of the outer loop using the break statement in the inner loop.
The label is defined with a colon (:) after the name of the label, and before the loop.
Below is the demo syntax of the code using labels and without a label.
Without Using Label
while (condition)
{
if (specific condition )
{
break;
// when control will reach to this break
// statement,the control will come out of while loop.
}
else
{
// code that needs to be executed
// if condition in if block is false.
}
}
With Labels
// labelName is the name of the label
labelName:
while (condition)
{
if (specific condition )
{
break labelName;
// it will work same as if break is used here.
}
else
{
// code that needs to be executed
// if condition in if block is false.
}
}
Below are some programs using the main function which will help to understand how the label statements work, and where they can be used.
Use Of Label In Single For Loop
Java
// Java program to demonstrate // the use of label in for loop import java.io.*; class GFG { public static void main(String[] args) { label1: for (int i = 0; i < 5; i++) { if (i == 3) break label1; System.out.print(i + " "); } }}
0 1 2
Java
// Java program to demonstrate the use // of label in nested for loopimport java.io.*; class GFG { public static void main(String[] args) { outerLoop: for (int i = 0; i < 5; i++) { innerLoop: for (int j = 0; j < 5; j++) { if (i != j) { System.out.println("If block values " + i); break outerLoop; } else { System.out.println("Else block values " + i); continue innerLoop; } } } }}
Else block values 0
If block values 0
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 23893,
"s": 23557,
"text": "The concept of labels in Java is being taken from assembly language. In Java break and continue are the control statements that control the flow of the program. La... |
Pandigital Product - GeeksforGeeks | 16 Oct, 2020
A Pandigital Number is number which makes the use of all digits 1 to 9 exactly once. We are given a number, we need to find if there are two numbers whose multiplication is given number and given three numbers together are pandigital.
Examples:
Input : 7254
Output : Yes
39 * 186 = 7254. We can notice that
the three numbers 39, 186 and 7254
together have all digits from 1 to 9.
Input : 6952
Output : Yes
The idea is to consider all pairs that multiply to given number. For every pair, create a string containing three numbers (given number and current pair). We sort the created string and check if sorted string is equal to “123456789”.
C++
Java
Python3
C#
PHP
// C++ code to check the number// is Pandigital Product or not#include <bits/stdc++.h>using namespace std; // To check the string formed// from multiplicand, multiplier// and product is pandigitalbool isPandigital(string str){ if (str.length() != 9) return false; char ch[str.length()]; strcpy(ch, str.c_str()); sort(ch, ch + str.length()); string s = ch; if(s.compare("123456789") == 0) return true; else return true;} // calculate the multiplicand,// multiplier, and product// eligible for pandigitalbool PandigitalProduct_1_9(int n){ for (int i = 1; i * i <= n; i++) if (n % i == 0 && isPandigital(to_string(n) + to_string(i) + to_string(n / i))) return true; return false;} // Driver Codeint main(){ int n = 6952; if (PandigitalProduct_1_9(n) == true) cout << "yes"; else cout << "no"; return 0;} // This code is contributed by// Manish Shaw(manishshaw1)
// Java code to check the number// is Pandigital Product or notimport java.io.*;import java.util.*;class GFG { // calculate the multiplicand, multiplier, and product // eligible for pandigital public static boolean PandigitalProduct_1_9(int n) { for (int i = 1; i*i <= n; i++) if (n % i == 0 && isPandigital("" + n + i + n / i)) return true; return false; } // To check the string formed from multiplicand // multiplier and product is pandigital public static boolean isPandigital(String str) { if (str.length() != 9) return false; char ch[] = str.toCharArray(); Arrays.sort(ch); return new String(ch).equals("123456789"); } // Driver function public static void main(String[] args) { int n = 6952; if (PandigitalProduct_1_9(n) == true) System.out.println("yes"); else System.out.println("no"); }}
# Python3 code to check the number# is Pandigital Product or not # Calculate the multiplicand,# multiplier, and product# eligible for pandigitaldef PandigitalProduct_1_9(n): i = 1 while i * i <= n: if ((n % i == 0) and bool(isPandigital(str(n) + str(i) + str(n // i)))): return bool(True) i += 1 return bool(False) # To check the string formed from# multiplicand multiplier and# product is pandigitaldef isPandigital(Str): if (len(Str) != 9): return bool(False) ch = "".join(sorted(Str)) if (ch == "123456789"): return bool(True) else: return bool(False) # Driver coden = 6952if (bool(PandigitalProduct_1_9(n))): print("yes")else: print("no") # This code is contributed by divyeshrabadiya07
// C# code to check the number// is Pandigital Product or not.using System; class GFG { // calculate the multiplicand, // multiplier, and product // eligible for pandigital public static bool PandigitalProduct_1_9(int n) { for (int i = 1; i*i <= n; i++) if (n % i == 0 && isPandigital("" + n + i + n / i)) return true; return false; } // To check the string formed from multiplicand // multiplier and product is pandigital public static bool isPandigital(String str) { if (str.Length != 9) return false; char []ch = str.ToCharArray(); Array.Sort(ch); return new String(ch).Equals("123456789"); } // Driver function public static void Main() { int n = 6952; if (PandigitalProduct_1_9(n) == true) Console.Write("yes"); else Console.Write("no"); }} // This code is contributed by nitin mittal.
<?php// PHP code to check the number// is Pandigital Product or not // To check the string formed// from multiplicand, multiplier// and product is pandigitalfunction isPandigital($str){ if (strlen($str) != 9) return false; $x = str_split($str); sort($x); $x = implode($x); return strcmp($x, "123456789");} // calculate the multiplicand,// multiplier, and product// eligible for pandigitalfunction PandigitalProduct_1_9($n){ for ($i = 1; $i * $i <= $n; $i++) if ($n % $i == 0 && isPandigital(strval($n) . strval($i) . strval((int)($n / $i)))) return true; return false;} // Driver Code$n = 6050;if (PandigitalProduct_1_9($n)) echo "yes";else echo "no"; // This code is contributed// by mits?>
Output:
yes
nitin mittal
manishshaw1
Mithun Kumar
divyeshrabadiya07
Java-Strings
number-digits
Java
Mathematical
Sorting
Java-Strings
Mathematical
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 23970,
"s": 23942,
"text": "\n16 Oct, 2020"
},
{
"code": null,
"e": 24205,
"s": 23970,
"text": "A Pandigital Number is number which makes the use of all digits 1 to 9 exactly once. We are given a number, we need to find if there are two numbers whose multipli... |
15 ways to create a Pandas DataFrame | by Joyjit Chowdhury | Towards Data Science | While doing EDA (exploratory data analysis) or developing / testing models, it is very common to use the powerful yet elegant pandas DataFrame for storing and manipulating data. And usually, it starts with “creating a dataframe”.
I usually encounter the following scenarios while starting some EDA or modeling with pandas:
I need to quickly create a dataframe of a few records to test a code.
I need to load a csv or json file into a dataframe.
I need to read an HTML table into a dataframe from a web page
I need to load json-like records into a dataframe without creating a json file
I need to load csv-like records into a dataframe without creating a csv file
I need to merge two dataframes, vertically or horizontally
I have to transform a column of a dataframe into one-hot columns
Each of these scenarios made me google the syntax or lookup the documentation every single time, until I slowly memorized them with practice of months and years.
Understanding the pain it took to lookup, I thought a quick lookup sheet for the multiple ways to create a dataframe in pandas may save some time. This may help learners until they become seasoned data analysts or data scientists.
So here are a few ways we can create a dataframe. If anyone reading this finds other elegant ways or methods, please feel free to comment or message me; I would love to add them in this page with your reference.
The pandas DataFrame() constructor offers many different ways to create and initialize a dataframe.
Method 0 — Initialize Blank dataframe and keep adding records. The columns attribute is a list of strings which become columns of the dataframe. DataFrame rows are referenced by the loc method with an index (like lists). For example, the first record in dataframe df will be referenced by df.loc[0], second record by df.loc[1]. A new row at position i can be directly added by setting df.loc[i] = <record attributes as a list>
# method 0# Initialize a blank dataframe and keep addingdf = pd.DataFrame(columns = ['year','make','model'])# Add records to dataframe using the .loc functiondf.loc[0] = [2014,"toyota","corolla"] df.loc[1] = [2018,"honda","civic"] df
Method 1 — using numpy array in the DataFrame constructor. Pass a 2D numpy array — each array is the corresponding row in the dataframe
# Pass a 2D numpy array - each row is the corresponding row required in the dataframedata = np.array([[2014,"toyota","corolla"], [2018,"honda","civic"], [2020,"hyndai","accent"], [2017,"nissan","sentra"]]) # pass column names in the columns parameter df = pd.DataFrame(data, columns = ['year', 'make','model'])df
Method 2 — using dictionary in the DataFrame constructor. Dictionary Keys become Column names in the dataframe. Dictionary values become the values of columns. Column values are combined in a single row according to the order in which they are specified
data = {'year': [2014, 2018,2020,2017], 'make': ["toyota", "honda","hyndai","nissan"], 'model':["corolla", "civic","accent","sentra"] }# pass column names in the columns parameter df = pd.DataFrame(data)df
Method 3 — using a list of dictionaries in the DataFrame constructor. Each dictionary is a record. Dictionary Keys become Column names in the dataframe. Dictionary values become the values of columns
data = [{'year': 2014, 'make': "toyota", 'model':"corolla"}, {'year': 2018, 'make': "honda", 'model':"civic"}, {'year': 2020, 'make': "hyndai", 'model':"nissan"}, {'year': 2017, 'make': "nissan" ,'model':"sentra"} ]# pass column names in the columns parameter df = pd.DataFrame(data)df
Method 4 — using dictionary in the from_dict method. Dictionary Keys become Column names in the dataframe. Dictionary values become the vaues of columns. Column values are combined in a single row according to the order in which they are specified.
data = {'year': [2014, 2018,2020,2017], 'make': ["toyota", "honda","hyndai","nissan"], 'model':["corolla", "civic","accent","sentra"] }# pass column names in the columns parameter df = pd.DataFrame.from_dict(data)df
Note: There is a difference between methods 2 and 4 even though both are dictionaries. Using from_dict, we have the ability to chose any column as an index of the dataframe. What if the column names we used above need to be indexes — like a transpose of the earlier data ? Specify orient = “index” and pass column names for the columns generated after the transpose
df = pd.DataFrame.from_dict(data, orient='index',columns=['record1', 'record2', 'record3', 'record4'])df
Method 5 — From a csv file using read_csv method of pandas library. This is one of the most common ways of dataframe creation for EDA. Delimiter (or separator) , header and the choice of index column from the csv file is configurable. By default, separator is comma, header is inferred from first line if found, index column is not taken from the file. Here is how the file looks like:
df = pd.read_csv('data.csv' , sep = ',', header = 'infer', index_col = None)df
Method 6 — From a string of csv records using read_csv method of pandas library. This is particularly useful when we dont want to create a file but we have record structures handy- all we do is convert a csv record “string” to a file handle using StringIO library function.
from io import StringIO# f is a file handle created from a csv like stringf = StringIO('year,make,model\n2014,toyota,corolla\n2018,honda,civic\n2020,hyndai,accent\n2017,nissan,sentra')df = pd.read_csv(f)df
Method 7 — From a json file using read_json method of pandas library when the json file has a record in each line. Setting lines=True mean Read the file as a json object per line. Here is how the json file looks like:
df = pd.read_json('data.json',lines=True)df
Method 8 — From a string of json records using read_json method of pandas library. This is particularly useful when we dont want to create a file but we have json record structures handy.
from io import StringIO# f is a file handle created from json like stringf = StringIO('{"year": "2014", "make": "toyota", "model": "corolla"}\n{"year": "2018", "make": "honda", "model": "civic"}\n{"year": "2020", "make": "hyndai", "model": "accent"}\n{"year": "2017", "make": "nissan", "model": "sentra"}')df = pd.read_json(f,lines=True)df
Method 9 — One of the most interesting ones — read tables from an HTML page using the pandas library built in read_html. This generates a list of dataframes; behind the scenes it scrapes the html page for any <table> tags and tries to capture the table into a dataframe. Even if there is only one table in the page, a list of dataframes is created — so it needs to be accessed using list subscript. The example below shows how to capture an HTML page and then load the tables — this uses the requests library to get the HTML content.
import requestsurl = 'https://www.goodcarbadcar.net/2020-us-vehicle-sales-figures-by-brand'r = requests.get(url)#if the response status is OK (200)if r.status_code == 200: # from the response object, pass the response text # to read_html and get list of tables as list of dataframes car_data_tables = pd.read_html(r.text)# display the first tablecar_data_tables[0]
Method 10 — As a copy of another dataframe.
df_copy = df.copy() # copy into a new dataframe objectdf_copy = df # make an alias of the dataframe(not creating # a new dataframe, just a pointer)
Note: The two methods shown above are different — the copy() function creates a totally new dataframe object independent of the original one while the variable copy method just creates an alias variable for the original dataframe — no new dataframe object is created. If there is any change to the original dataframe, it is also reflected in the alias as shown below:
# as a new object using .copy() method - new dataframe object created independent of old onea = pd.DataFrame({'year': [2019],'make': ["Mercedes"],'model':["C-Class"]})b = a.copy()# change old onea['year'] = 2020# new copy does not reflect the changeb
# as variable copy - new variable is just an alias to the old onea = pd.DataFrame({'year': [2019],'make': ["Mercedes"],'model':["C-Class"]})b = a# change old onea['year'] = 2020# alias reflects the changeb
Method 11 — Vertical concatenation — one on top of the other
data1 = [{'year': 2014, 'make': "toyota", 'model':"corolla"}, {'year': 2018, 'make': "honda", 'model':"civic"}, {'year': 2020, 'make': "hyndai", 'model':"nissan"}, {'year': 2017, 'make': "nissan" ,'model':"sentra"} ]df1 = pd.DataFrame(data1)data2 = [{'year': 2019, 'make': "bmw", 'model':"x5"}]df2 = pd.DataFrame(data2)# concatenate vertically# NOTE: axis = 'index' is same as axis = 0, and is the default # The two statements below mean the same as the one abovedf3 = pd.concat([df1,df2], axis = 'index') #ORdf3 = pd.concat([df1,df2], axis = 0)# ORdf3 = pd.concat([df1,df2])df3
In the above example, the index of the 2nd dataframe is preserved in the concatenated dataframe. To reset the indexes to match with the entire dataframe, use the reset_index() function of the dataframe
df3 = pd.concat([df1,df2]).reset_index()#ORdf3 = pd.concat([df1,df2], ignore_index = True)df3
Method 12 — Horizontal concatenation — append side by side, not joined by any key
data1 = [{'year': 2014, 'make': "toyota", 'model':"corolla"}, {'year': 2018, 'make': "honda", 'model':"civic"}, {'year': 2020, 'make': "hyndai", 'model':"nissan"}, {'year': 2017, 'make': "nissan" ,'model':"sentra"} ]df1 = pd.DataFrame(data1)data2 = [{'year': 2019, 'make': "bmw", 'model':"x5"}]df2 = pd.DataFrame(data2)df3 = pd.concat([df1,df2], axis = 'columns')#ORdf3 = pd.concat([df1,df2], axis = 1)df3
NOTE: For horizontal concatenation,
The rows of the dataframes are concatenated by order of their position (index)
If there is any record missing in one of the dataframes, the corresponding records in concatenated dataframe are NaN. This is same as doing a left outer join on index (see merge below)
Method 13 — Horizontal concatenation — equivalent of SQL join.
Inner join
data1 = [{'year': 2014, 'make': "toyota", 'model':"corolla"}, {'year': 2018, 'make': "honda", 'model':"civic"}, {'year': 2020, 'make': "hyndai", 'model':"nissan"}, {'year': 2017, 'make': "nissan" ,'model':"sentra"} ]df1 = pd.DataFrame(data1)data2 = [{'make': 'honda', 'Monthly Sales': 114117}, {'make': 'toyota', 'Monthly Sales': 172370}, {'make': 'hyndai', 'Monthly Sales': 54790} ]df2 = pd.DataFrame(data2)# inner join on 'make'# default is inner joindf3 = pd.merge(df1,df2,how = 'inner',on = ['make'])df3 = pd.merge(df1,df2,on = ['make'])df3
Left join
# for a left join , use how = 'left'df3 = pd.merge(df1,df2,how = 'left',on = ['make'])df3
Method 14 — As a transpose of another dataframe
# To transpose a dataframe - use .T methoddf4 = df3.T# To rename columns to anything else after the transposedf4.columns = (['column1','column2','column3','column4'])df4
Method 15 — Conversion to one-hot columns (used for modeling with learning algorithms) using pandas get_dummies function.
One-Hot is basically a conversion of a column value into a set of derived columns like Binary Representation Any one of the one-hot column set is 1 and rest is 0.
If we know that a car has body types = SEDAN, SUV, VAN, TRUCK, then a Toyota corolla with body = ‘SEDAN’ will become one-hot encoded to
body_SEDAN body_SUV body_VAN body_TRUCK1 0 0 0
Each one hot column is basically of the format <original_column_name>_<possible_value>
Below is an example:
data1 = [{ 'make': "toyota", 'model':"corolla", 'body':"sedan"}, {'make': "honda", 'model':"crv", 'body':"suv"}, {'make': "dodge", 'model':"caravan", 'body':"van"}, {'make': "ford" ,'model':"f150", 'body':"truck"} ]df1 = pd.DataFrame(data1) df2 = pd.get_dummies(df1,columns = ['body'])df2
I hope this “cheat-sheet” helps in the initial phases of learning EDA or modeling. For sure, with time and constant practice, all these will be memorized.
All the best then :)
Do share your valuable inputs if you have any other elegant ways of dataframe creation or if there is any new function that can create a dataframe for some specific purpose.
The git link for this notebook is here. | [
{
"code": null,
"e": 402,
"s": 172,
"text": "While doing EDA (exploratory data analysis) or developing / testing models, it is very common to use the powerful yet elegant pandas DataFrame for storing and manipulating data. And usually, it starts with “creating a dataframe”."
},
{
"code": nul... |
Implementation of One Time Pad Cipher | Python includes a hacky implementation module for one-time-pad cipher implementation. The package name is called One-Time-Pad which includes a command line encryption tool that uses encryption mechanism similar to the one-time pad cipher algorithm.
You can use the following command to install this module −
pip install onetimepad
If you wish to use it from the command-line, run the following command −
onetimepad
The following code helps to generate a one-time pad cipher −
import onetimepad
cipher = onetimepad.encrypt('One Time Cipher', 'random')
print("Cipher text is ")
print(cipher)
print("Plain text is ")
msg = onetimepad.decrypt(cipher, 'random')
print(msg)
You can observe the following output when you run the code given above −
Note − The encrypted message is very easy to crack if the length of the key is less than the length of message (plain text).
In any case, the key is not necessarily random, which makes one-time pad cipher as a worth tool.
10 Lectures
2 hours
Total Seminars
10 Lectures
2 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2541,
"s": 2292,
"text": "Python includes a hacky implementation module for one-time-pad cipher implementation. The package name is called One-Time-Pad which includes a command line encryption tool that uses encryption mechanism similar to the one-time pad cipher algorithm."
}... |
Decode an Encoded Base 64 String to ASCII String - GeeksforGeeks | 07 Jul, 2021
Prerequisite : What is base64 Encoding and why we encode strings to base64 formatBase64 encoding is performed at sending node before transmitting bits over a network, and receiving node decodes that encoded data back to original ASCII string. Base64 character set is
// 64 characters
char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789+/"
Examples:
Input : TUVO04= // (Encoded into base64 format)
Output : MENON // (Decoded back to ASCII string)
Input : Z2Vla3Nmb3JnZWVrcw==
Output : geeksforgeeks
Approach:
Here each character in encoded string is considered to be made of 6 bits. We will take 4 characters each from Encoded String at one time i.e 4 * 6 = 24 bits. For each 4 characters of encoded string we will produce 3 characters of original string which will be of 8 bits each i.e 3 * 8 = 24 bits.Find their respective position in char_set and store it inside a variable (num) by using ‘|’ OR operator for storing bits and (LEFT – SHIFT) by 6 to make room for another 6 bits. NOTE : We used ‘=’ in encoder to substitute for 2 missing bits, So here in decoder we have to reverse the process. Whenever we encounter a ‘=’ we have to delete 2 bits of num by using (RIGHT – SHIFT) by 2. After we have stored all the bits in num we will retrieve them in groups of 8, by using & operator with 255 (11111111), that will store the 8 bits from num and that will be our original character from ASCII string.
Here each character in encoded string is considered to be made of 6 bits. We will take 4 characters each from Encoded String at one time i.e 4 * 6 = 24 bits. For each 4 characters of encoded string we will produce 3 characters of original string which will be of 8 bits each i.e 3 * 8 = 24 bits.
Find their respective position in char_set and store it inside a variable (num) by using ‘|’ OR operator for storing bits and (LEFT – SHIFT) by 6 to make room for another 6 bits. NOTE : We used ‘=’ in encoder to substitute for 2 missing bits, So here in decoder we have to reverse the process. Whenever we encounter a ‘=’ we have to delete 2 bits of num by using (RIGHT – SHIFT) by 2.
After we have stored all the bits in num we will retrieve them in groups of 8, by using & operator with 255 (11111111), that will store the 8 bits from num and that will be our original character from ASCII string.
C++
C
Java
C#
Javascript
// C++ Program to decode a base64// Encoded string back to ASCII string#include <bits/stdc++.h>using namespace std;#define SIZE 100 /* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */char* base64Decoder(char encoded[], int len_str){ char* decoded_string; decoded_string = (char*)malloc(sizeof(char) * SIZE); int i, j, k = 0; // stores the bitstream. int num = 0; // count_bits stores current // number of bits in num. int count_bits = 0; // selects 4 characters from // encoded string at a time. // find the position of each encoded // character in char_set and stores in num. for (i = 0; i < len_str; i += 4) { num = 0, count_bits = 0; for (j = 0; j < 4; j++) { // make space for 6 bits. if (encoded[i + j] != '=') { num = num << 6; count_bits += 6; } /* Finding the position of each encoded character in char_set and storing in "num", use OR '|' operator to store bits.*/ // encoded[i + j] = 'E', 'E' - 'A' = 5 // 'E' has 5th position in char_set. if (encoded[i + j] >= 'A' && encoded[i + j] <= 'Z') num = num | (encoded[i + j] - 'A'); // encoded[i + j] = 'e', 'e' - 'a' = 5, // 5 + 26 = 31, 'e' has 31st position in char_set. else if (encoded[i + j] >= 'a' && encoded[i + j] <= 'z') num = num | (encoded[i + j] - 'a' + 26); // encoded[i + j] = '8', '8' - '0' = 8 // 8 + 52 = 60, '8' has 60th position in char_set. else if (encoded[i + j] >= '0' && encoded[i + j] <= '9') num = num | (encoded[i + j] - '0' + 52); // '+' occurs in 62nd position in char_set. else if (encoded[i + j] == '+') num = num | 62; // '/' occurs in 63rd position in char_set. else if (encoded[i + j] == '/') num = num | 63; // ( str[i + j] == '=' ) remove 2 bits // to delete appended bits during encoding. else { num = num >> 2; count_bits -= 2; } } while (count_bits != 0) { count_bits -= 8; // 255 in binary is 11111111 decoded_string[k++] = (num >> count_bits) & 255; } } // place NULL character to mark end of string. decoded_string[k] = '\0'; return decoded_string;} // Driver codeint main(){ char encoded_string[] = "TUVOT04="; int len_str = sizeof(encoded_string) / sizeof(encoded_string[0]); // Do not count last NULL character. len_str -= 1; cout <<"Encoded string : " << encoded_string << endl; cout <<"Decoded string : " << base64Decoder(encoded_string, len_str) << endl; return 0;} // This code is contributed by// shubhamsingh10
// C Program to decode a base64// Encoded string back to ASCII string #include <stdio.h>#include <stdlib.h>#define SIZE 100 /* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */ char* base64Decoder(char encoded[], int len_str){ char* decoded_string; decoded_string = (char*)malloc(sizeof(char) * SIZE); int i, j, k = 0; // stores the bitstream. int num = 0; // count_bits stores current // number of bits in num. int count_bits = 0; // selects 4 characters from // encoded string at a time. // find the position of each encoded // character in char_set and stores in num. for (i = 0; i < len_str; i += 4) { num = 0, count_bits = 0; for (j = 0; j < 4; j++) { // make space for 6 bits. if (encoded[i + j] != '=') { num = num << 6; count_bits += 6; } /* Finding the position of each encoded character in char_set and storing in "num", use OR '|' operator to store bits.*/ // encoded[i + j] = 'E', 'E' - 'A' = 5 // 'E' has 5th position in char_set. if (encoded[i + j] >= 'A' && encoded[i + j] <= 'Z') num = num | (encoded[i + j] - 'A'); // encoded[i + j] = 'e', 'e' - 'a' = 5, // 5 + 26 = 31, 'e' has 31st position in char_set. else if (encoded[i + j] >= 'a' && encoded[i + j] <= 'z') num = num | (encoded[i + j] - 'a' + 26); // encoded[i + j] = '8', '8' - '0' = 8 // 8 + 52 = 60, '8' has 60th position in char_set. else if (encoded[i + j] >= '0' && encoded[i + j] <= '9') num = num | (encoded[i + j] - '0' + 52); // '+' occurs in 62nd position in char_set. else if (encoded[i + j] == '+') num = num | 62; // '/' occurs in 63rd position in char_set. else if (encoded[i + j] == '/') num = num | 63; // ( str[i + j] == '=' ) remove 2 bits // to delete appended bits during encoding. else { num = num >> 2; count_bits -= 2; } } while (count_bits != 0) { count_bits -= 8; // 255 in binary is 11111111 decoded_string[k++] = (num >> count_bits) & 255; } } // place NULL character to mark end of string. decoded_string[k] = '\0'; return decoded_string;} // Driver functionint main(){ char encoded_string[] = "TUVOT04="; int len_str = sizeof(encoded_string) / sizeof(encoded_string[0]); // Do not count last NULL character. len_str -= 1; printf("Encoded string : %s\n", encoded_string); printf("Decoded_string : %s\n", base64Decoder(encoded_string, len_str)); return 0;}
// Java Program to decode a base64// Encoded String back to ASCII String class GFG{ static final int SIZE = 100; /* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */static String base64Decoder(char encoded[], int len_str){ char []decoded_String; decoded_String = new char[SIZE]; int i, j, k = 0; // stores the bitstream. int num = 0; // count_bits stores current // number of bits in num. int count_bits = 0; // selects 4 characters from // encoded String at a time. // find the position of each encoded // character in char_set and stores in num. for (i = 0; i < len_str; i += 4) { num = 0; count_bits = 0; for (j = 0; j < 4; j++) { // make space for 6 bits. if (encoded[i + j] != '=') { num = num << 6; count_bits += 6; } /* Finding the position of each encoded character in char_set and storing in "num", use OR '|' operator to store bits.*/ // encoded[i + j] = 'E', 'E' - 'A' = 5 // 'E' has 5th position in char_set. if (encoded[i + j] >= 'A' && encoded[i + j] <= 'Z') num = num | (encoded[i + j] - 'A'); // encoded[i + j] = 'e', 'e' - 'a' = 5, // 5 + 26 = 31, 'e' has 31st position in char_set. else if (encoded[i + j] >= 'a' && encoded[i + j] <= 'z') num = num | (encoded[i + j] - 'a' + 26); // encoded[i + j] = '8', '8' - '0' = 8 // 8 + 52 = 60, '8' has 60th position in char_set. else if (encoded[i + j] >= '0' && encoded[i + j] <= '9') num = num | (encoded[i + j] - '0' + 52); // '+' occurs in 62nd position in char_set. else if (encoded[i + j] == '+') num = num | 62; // '/' occurs in 63rd position in char_set. else if (encoded[i + j] == '/') num = num | 63; // ( str[i + j] == '=' ) remove 2 bits // to delete appended bits during encoding. else { num = num >> 2; count_bits -= 2; } } while (count_bits != 0) { count_bits -= 8; // 255 in binary is 11111111 decoded_String[k++] = (char) ((num >> count_bits) & 255); } } return String.valueOf(decoded_String);} // Driver codepublic static void main(String[] args){ char encoded_String[] = "TUVOT04=".toCharArray(); int len_str = encoded_String.length; // Do not count last null character. len_str -= 1; System.out.printf("Encoded String : %s\n", String.valueOf(encoded_String)); System.out.printf("Decoded_String : %s\n", base64Decoder(encoded_String, len_str));}} // This code is contributed by 29AjayKumar
// C# Program to decode a base64// Encoded String back to ASCII Stringusing System; class GFG{ static readonly int SIZE = 100; /* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */static String base64Decoder(char []encoded, int len_str){ char []decoded_String; decoded_String = new char[SIZE]; int i, j, k = 0; // stores the bitstream. int num = 0; // count_bits stores current // number of bits in num. int count_bits = 0; // selects 4 characters from // encoded String at a time. // find the position of each encoded // character in char_set and stores in num. for (i = 0; i < len_str; i += 4) { num = 0; count_bits = 0; for (j = 0; j < 4; j++) { // make space for 6 bits. if (encoded[i + j] != '=') { num = num << 6; count_bits += 6; } /* Finding the position of each encoded character in char_set and storing in "num", use OR '|' operator to store bits.*/ // encoded[i + j] = 'E', 'E' - 'A' = 5 // 'E' has 5th position in char_set. if (encoded[i + j] >= 'A' && encoded[i + j] <= 'Z') num = num | (encoded[i + j] - 'A'); // encoded[i + j] = 'e', 'e' - 'a' = 5, // 5 + 26 = 31, 'e' has 31st position in char_set. else if (encoded[i + j] >= 'a' && encoded[i + j] <= 'z') num = num | (encoded[i + j] - 'a' + 26); // encoded[i + j] = '8', '8' - '0' = 8 // 8 + 52 = 60, '8' has 60th position in char_set. else if (encoded[i + j] >= '0' && encoded[i + j] <= '9') num = num | (encoded[i + j] - '0' + 52); // '+' occurs in 62nd position in char_set. else if (encoded[i + j] == '+') num = num | 62; // '/' occurs in 63rd position in char_set. else if (encoded[i + j] == '/') num = num | 63; // ( str[i + j] == '=' ) remove 2 bits // to delete appended bits during encoding. else { num = num >> 2; count_bits -= 2; } } while (count_bits != 0) { count_bits -= 8; // 255 in binary is 11111111 decoded_String[k++] = (char) ((num >> count_bits) & 255); } } return String.Join("",decoded_String);} // Driver codepublic static void Main(String[] args){ char []encoded_String = "TUVOT04=".ToCharArray(); int len_str = encoded_String.Length; // Do not count last null character. len_str -= 1; Console.Write("Encoded String : {0}\n", String.Join("",encoded_String)); Console.Write("Decoded_String : {0}\n", base64Decoder(encoded_String, len_str));}} // This code is contributed by 29AjayKumar
<script> // JavaScript Program to decode a base64// Encoded String back to ASCII String let SIZE = 100; /* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */function base64Decoder(encoded,len_str){ let decoded_String; decoded_String = new Array(SIZE); let i, j, k = 0; // stores the bitstream. let num = 0; // count_bits stores current // number of bits in num. let count_bits = 0; // selects 4 characters from // encoded String at a time. // find the position of each encoded // character in char_set and stores in num. for (i = 0; i < len_str; i += 4) { num = 0; count_bits = 0; for (j = 0; j < 4; j++) { // make space for 6 bits. if (encoded[i + j] != '=') { num = num << 6; count_bits += 6; } /* Finding the position of each encoded character in char_set and storing in "num", use OR '|' operator to store bits.*/ // encoded[i + j] = 'E', 'E' - 'A' = 5 // 'E' has 5th position in char_set. if (encoded[i + j].charCodeAt(0) >= 'A'.charCodeAt(0) && encoded[i + j].charCodeAt(0) <= 'Z'.charCodeAt(0)) num = num | (encoded[i + j].charCodeAt(0) - 'A'.charCodeAt(0)); // encoded[i + j] = 'e', 'e' - 'a' = 5, // 5 + 26 = 31, 'e' has 31st position in char_set. else if (encoded[i + j].charCodeAt(0) >= 'a'.charCodeAt(0) && encoded[i + j].charCodeAt(0) <= 'z'.charCodeAt(0)) num = num | (encoded[i + j].charCodeAt(0) - 'a'.charCodeAt(0) + 26); // encoded[i + j] = '8', '8' - '0' = 8 // 8 + 52 = 60, '8' has 60th position in char_set. else if (encoded[i + j].charCodeAt(0) >= '0'.charCodeAt(0) && encoded[i + j].charCodeAt(0) <= '9'.charCodeAt(0)) num = num | (encoded[i + j].charCodeAt(0) - '0'.charCodeAt(0) + 52); // '+' occurs in 62nd position in char_set. else if (encoded[i + j] == '+') num = num | 62; // '/' occurs in 63rd position in char_set. else if (encoded[i + j] == '/') num = num | 63; // ( str[i + j] == '=' ) remove 2 bits // to delete appended bits during encoding. else { num = num >> 2; count_bits -= 2; } } while (count_bits != 0) { count_bits -= 8; // 255 in binary is 11111111 decoded_String[k++] = String.fromCharCode ((num >> count_bits) & 255); } } return (decoded_String);} // Driver codelet encoded_String = "TUVOT04=".split(""); let len_str = encoded_String.length; // Do not count last null character. len_str -= 1; document.write("Encoded String : " + (encoded_String).join("")+"<br>"); document.write("Decoded_String : "+ base64Decoder(encoded_String, len_str).join("")+"<br>"); // This code is contributed by rag2127 </script>
Output:
Encoded string : TUVO04=
Decoded string : MENON
Time Complexity: O(N) Space Complexity : O(1)This article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
29AjayKumar
SHUBHAMSINGH10
rag2127
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Vigenère Cipher
How to Append a Character to a String in C
Program to add two binary strings
Convert character array to string in C++
Return maximum occurring character in an input string
Naive algorithm for Pattern Searching
Hill Cipher
sprintf() in C
A Program to check if strings are rotations of each other or not | [
{
"code": null,
"e": 24463,
"s": 24435,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 24732,
"s": 24463,
"text": "Prerequisite : What is base64 Encoding and why we encode strings to base64 formatBase64 encoding is performed at sending node before transmitting bits over a netwo... |
How to match tab and newline but not space using Python regular expression? | The following code matches tab and newline but not space from given string using regex.
import re
print re.findall(r"[\n\t]","""I find
Tutorialspoint useful""")
This gives the output
['\n'] | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "The following code matches tab and newline but not space from given string using regex."
},
{
"code": null,
"e": 1227,
"s": 1150,
"text": "import re\nprint re.findall(r\"[\\n\\t]\",\"\"\"I find\n Tutorialspoint useful\"\"\")"
},... |
Got GAM? a flexible modeling approach that preserves interpretability | by Onyi Lam | Towards Data Science | In many social science and business problems, it is often more important to explain why a phenomenon happens than improving the model’s predictability on the event happening. Having an interpretable model is, therefore, crucial in understanding how different factors interact with the outcome of interest.
The model’s interpretability is also important in highly regulated business environments, such as loan approval decisions. Even in situations where prediction accuracy is more important than the “why”, an interpretable model can help debug more complicated models and guide new approaches to feature engineering and data preprocessing.
In this context, generalized additive models (GAM) offer a middle ground between simple models, such as those we fit with linear regression, and more sophisticated machine learning models like neural networks that usually promise superior prediction performance to simple models. GAM can also be used in various tasks: regression, classification, binary choice.
In linear regression, we model outcome y as a function of 2 inputs X1 and X2 with the following:
y = β1X1 + β2 X2 + u
In GAM, the β Xi is replaced by f(Xi), where f() can be any arbitrary nonlinear functions. In other words, GAM is composed of a sum of smooth functions f() on the input. The idea is still that each input feature makes a separate contribution to the response, and these just add up, but these contributions don’t have to be strictly proportional to the inputs. The beauty of this approach is that, similar to what β represents in linear regression, the partial response function f() still captures the change on outcome y to change the input. The change in prediction depends on the initial value of Xi.
A common approach to deal with nonlinear relationships in regression models involves creating polynomial features. For the predictor in question, Xi, we add terms e.g. quadratic (Xi2), cubic (Xi3), etc to get a better fit. GAM encompasses this idea but includes an additional aspect: penalized estimation. The idea is similar to that of a ridge or lasso regression, where penalty terms are added to help avoid overfitting.
Another way of creating transformations of a variable is to cut the variable into distinct regions, and fit those regions separately. However, the different fits could be unconnected, leading to sometimes notably different predictions for values close together. GAM allows the user to specify the number ofknots in the variable, which are used to create sections where separate cubic polynomials are fit at each section and then joined to create a continuous curve.
A number of smooths are available with the mgcv package in R, and one can learn more via the help file for smooth.terms (link). The default is thin plate regression splines (TPRS), which works well in general in terms of performance. Cubic spline is also a common basis that mirrors adding polynomial terms for the covariates.
We use the mgcv package in `R` to implement gam and use a built-in dataset medcare from the package catdata to illustrate gam and compare with the performance using logistic regression.
The medcare data was collected on 4406 individuals, aged 66 and over, that were covered by a public insurance program. The outcome variable is healthpoor, a binary variable that equals 1 if the individual reports poor health and 0 otherwise. We are interested in knowing how ofp, the number of physician office visits, might be correlated with health outcomes. One can hypothesize a nonlinear relationship between the two variables: a healthy individual will have few physician visits, but having more visits also allow the patients to return to be more healthy. So we are interested to have a more flexible modeling approach.
The mgcv treats gam as a generalized version of glm, so one can directly call thegam method to use glm methods such as linear and logistic regression.
library(catdata)library(mgcv)library(Metrics)library(ggplot2)library(visreg)data(medcare)#### logit model (same as running glm with family set to "binomial")lm <- gam(healthpoor ~ male+ age + ofp, family = binomial, data = medcare)pred <- predict(lm, type="response")lm_auc <- Metrics::auc(medcare$healthpoor, pred)lm_auc#### generalized additive modelgam <- gam(healthpoor ~ male+s(age)+s(ofp), family = binomial, data = medcare)pred <- predict(gam, type="response")gam_auc <- Metrics::auc(medcare$healthpoor, pred)gam_auc
The s() terms in the gam formula indicate which terms are to be smoothed. There are several options you can pass on to the s() terms — for example, you can specify a different smooth function bs, and a different number of knots k.
If the number of unique values is less than the number of basis (For example, when you tried to add s() to a binary variable like male), the function would return the following error:
A term has fewer unique covariate combinations than specified maximum degrees of freedom.
Using visreg to visualize the fitted terms ofofp, we can see that gam produces a much more nuanced prediction of ofp while that of the logistic regression is much more linear.
visreg(gam, "ofp", jitter=TRUE, line=list(col="red"), fill=list(col="green"))
The gam model also yields a slightly better AUC, 0.679, versus 0.673 of the logistic regression.
We are ultimately interested in estimating the change in ofp on the probability of healthpoor. To do that, we need to fix the other features’ values to their mean or mode(if the feature is a categorical variable). We then create a test dataframe that has a list of possible values of ofp.
# function to get mode of an array of valuesgetmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))]}testdata = data.frame(ofp = seq(0, 100, length = 101), male = getmode(gam$model$male), age = mean(gam$model$age))
Using the predict function, we can then extrapolate the previously fitted gam model to the test data. The plot shows that ofp has a nonlinear relationship with the likelihood of reporting poor health, holding other variables constant. Furthermore, the confidence interval less tight in regions with higher ofp.
fits = predict(gam, newdata=testdata, type='response', se=T)### create a confidence interval for the fitspredicts = data.frame(testdata, fits) %>% mutate(lower = fit - 1.96*se.fit, upper = fit + 1.96*se.fit)ggplot(aes(x=ofp,y=fit), data=predicts) + geom_ribbon(aes(ymin = lower, ymax=upper), fill='gray90') + geom_line(color='#00aaff') +theme_bw()
For more information on GAM: | [
{
"code": null,
"e": 477,
"s": 171,
"text": "In many social science and business problems, it is often more important to explain why a phenomenon happens than improving the model’s predictability on the event happening. Having an interpretable model is, therefore, crucial in understanding how differ... |
How to convert Stream to TreeSet in Java? | Let us first create a Stream:
Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
Now convert Stream to TreeSet:
Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
The following is an example to convert String to TreeSet in Java:
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
set.forEach(val -> System.out.println(val));
}
}
Armenia
Australia
Canada
India
Poland
UK
US | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a Stream:"
},
{
"code": null,
"e": 1192,
"s": 1092,
"text": "Stream<String> stream = Stream.of(\"UK\", \"US\", \"India\", \"Australia\", \"Armenia\", \"Canada\", \"Poland\");"
},
{
"code": null,
"e": 1... |
Program for Mean Absolute Deviation in C++ | Given with an array of natural numbers and the task is to calculate the mean absolute deviation and for that we must require the knowledge of mean, variance and standard deviation.
There are steps that need to be followed for calculating the mean absolute deviation
Calculate the mean
Calculate the mean
Calculate absolute deviation
Calculate absolute deviation
Add all the calculated deviations
Add all the calculated deviations
Apply the formula
Apply the formula
Input
arr[] = { 34,21,56,76,45,11}
Output
mean absolute deviation is : 18.5
Input
arr[] = {10, 15, 15, 17, 18, 21}
Output
mean absolute mean absolute deviation is : 2.66
Input the elements of an array
Input the elements of an array
Calculate the mean of an array
Calculate the mean of an array
Calculate deviation using formula
Sum = Sum + abs(arr[i] - Mean(arr, n))
Calculate deviation using formula
Sum = Sum + abs(arr[i] - Mean(arr, n))
calculate mean absolute deviation by dividing the total deviation with total
number of elements in an array
calculate mean absolute deviation by dividing the total deviation with total
number of elements in an array
(abs(arr[0] – mean) + abs(arr[1] – mean) + . . + abs(arr[n-1] – mean) / n
Start
Step 1→ declare function to calculate mean
float mean(float arr[], int size)
declare float sum = 0
Loop For int i = 0 and i < size and i++
Set sum = sum + arr[i]
End
return sum / size
Step 2→ Declare function to calculate deviation
float deviation(float arr[], int size)
declare float sum = 0
Loop For int i = 0 and i < size and i++
Set sum = sum + abs(arr[i] - mean(arr, size))
End
return sum / size
Step 3→ In main()
Declare float arr[] = { 34,21,56,76,45,11}
Declare int size = sizeof(arr) / sizeof(arr[0])
Call deviation(arr, size)
Stop
Live Demo
#include <bits/stdc++.h>
using namespace std;
//calculate mean using mean function
float mean(float arr[], int size){
float sum = 0;
for (int i = 0; i < size; i++)
sum = sum + arr[i];
return sum / size;
}
//calculate mean deviation
float deviation(float arr[], int size){
float sum = 0;
for (int i = 0; i < size; i++)
sum = sum + abs(arr[i] - mean(arr, size));
return sum / size;
}
int main(){
float arr[] = { 34,21,56,76,45,11};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"mean absolute deviation is : "<<deviation(arr, size);
return 0;
}
If run the above code it will generate the following output −
mean absolute deviation is : 18.5 | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "Given with an array of natural numbers and the task is to calculate the mean absolute deviation and for that we must require the knowledge of mean, variance and standard deviation."
},
{
"code": null,
"e": 1328,
"s": 1243,
"text": "T... |
Python 3 - Number floor() Method | The floor() method returns the floor of x i.e. the largest integer not greater than x.
Following is the syntax for floor() method −
import math
math.floor( x )
Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns the largest integer not greater than x.
The following example shows the usage of the floor() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))
When we run the above program, it produces the following result −
math.floor(-45.17) : -46
math.floor(100.12) : 100
math.floor(100.72) : 100
math.floor(math.pi) : 3
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2427,
"s": 2340,
"text": "The floor() method returns the floor of x i.e. the largest integer not greater than x."
},
{
"code": null,
"e": 2472,
"s": 2427,
"text": "Following is the syntax for floor() method −"
},
{
"code": null,
"e": 2502,
"s"... |
Phyllotaxis pattern in Python | A unit of Algorithmic Botany - GeeksforGeeks | 07 Dec, 2020
Phyllotaxis/phyllotaxy is the arrangement of leaves on a plant stem & the Phyllotactic spirals form a distinctive class of patterns in nature. The word itself comes from the Greek phullon, meaning “leaf, ” and taxis, meaning “arrangement”.The basic floral phyllotaxic arrangements include:1. Spiral Phyllotaxis – In spiral phyllotaxy, the individual floral organs are created in a regular time interval with the same divergent angle. The divergent angle in a flower with spiral phyllotaxy approximates 137.5 degrees, which is indicative of a pattern that follows a Fibonacci series.The image below shows the spiral phyllotaxy patterns having both clockwise and anticlockwise spiral patterns.
Important points to note:
Fibonacci series typically describe spirals found in nature. It is calculated as a series where the previous pair of numbers sum to the next number in the series. The series is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ... .There is actually one set of spirals in a clockwise direction and one set in a counter-clockwise direction.Floral organ spirals follow a numerator and denominator set of offset Fibonacci numbers (1/2, 1/3, 2/5, 3/8, 5/13, 8/21, 13/34 ...). The numerator is the number of times or turns around the axis to get back to the initiation origin. The denominator indicates the number of organs initiated during the turns. Therefore, a 2/5 would indicate 2 turns around the axis and 5 organs to return to the origin.e.g – In the pine we have (2, 3), (5, 3), and (5, 8) phyllotaxes, in capituli the pairs found are (21, 34), (55, 34), (55, 89), and (89, 144), and on pineapples with hexagonal scales the triplets (8, 13, 21) or (13, 21, 34) are found, depending on the size of the specimens .The prevalence of the Fibonacci sequence in phyllotaxis is often referred to as “the mystery of phyllotaxis.”
Fibonacci series typically describe spirals found in nature. It is calculated as a series where the previous pair of numbers sum to the next number in the series. The series is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ... .
There is actually one set of spirals in a clockwise direction and one set in a counter-clockwise direction.
Floral organ spirals follow a numerator and denominator set of offset Fibonacci numbers (1/2, 1/3, 2/5, 3/8, 5/13, 8/21, 13/34 ...). The numerator is the number of times or turns around the axis to get back to the initiation origin. The denominator indicates the number of organs initiated during the turns. Therefore, a 2/5 would indicate 2 turns around the axis and 5 organs to return to the origin.
e.g – In the pine we have (2, 3), (5, 3), and (5, 8) phyllotaxes, in capituli the pairs found are (21, 34), (55, 34), (55, 89), and (89, 144), and on pineapples with hexagonal scales the triplets (8, 13, 21) or (13, 21, 34) are found, depending on the size of the specimens .
The prevalence of the Fibonacci sequence in phyllotaxis is often referred to as “the mystery of phyllotaxis.”
Other types of floral phyllotaxic arrangements are:2. Whorled Phyllotaxis, 3. Simple-whorled Phyllotaxis, 4. Complex-whorled Phyllotaxis & 5. Irregular Phyllotaxis
Formation of the Pattern : Summary
The beautiful arrangement of leaves in some plants, called phyllotaxis, obeys a number of subtle mathematical relationships. For instance, the florets in the head of a sunflower form two oppositely directed spirals: 55 of them clockwise and 34 counterclockwise. Surprisingly,
These numbers are consecutive Fibonacci numbers.The ratios of alternate Fibonacci numbers are given by the convergents to φ^(-2), where φ is the golden ratio, and are said to measure the fraction of a turn between successive leaves on the stalk of a plant:e.g : 1/2 for elm and linden, 1/3 for beech and hazel, 2/5 for oak and apple, 3/8 for poplar and rose, 5/13 for willow and almond, etc.Each new leaf on a plant stem is positioned at a certain angle to the previous one and that this angle is constant between leaves: usually about 137.5 degrees.
These numbers are consecutive Fibonacci numbers.
The ratios of alternate Fibonacci numbers are given by the convergents to φ^(-2), where φ is the golden ratio, and are said to measure the fraction of a turn between successive leaves on the stalk of a plant:
e.g : 1/2 for elm and linden, 1/3 for beech and hazel, 2/5 for oak and apple, 3/8 for poplar and rose, 5/13 for willow and almond, etc.
Each new leaf on a plant stem is positioned at a certain angle to the previous one and that this angle is constant between leaves: usually about 137.5 degrees.
That is, if you look down from above on the plant and measure the angle formed between a line drawn from the stem to the leaf and a corresponding line for the next leaf, you will find that there is generally a fixed angle, called the divergence angle.Here, we are interested in Spiral phyllotaxy and we will code to form Spiral Phyllotaxy pattern in python using turtle graphics.
Designing the Code
We will code two functions, one to draw the phyllotaxy pattern and the other to draw the petals.The petals need to be drawn only after the phyllotaxis pattern is completed.So, we will call the drawPetal() function from inside the drawPhyllPattern() function with the last x & y coordinates being visited after drawing the Phyllotaxis pattern.The drawPetal() function will draw the petals with turtle functions and features, refer Turtle programming.
We will code two functions, one to draw the phyllotaxy pattern and the other to draw the petals.
The petals need to be drawn only after the phyllotaxis pattern is completed.So, we will call the drawPetal() function from inside the drawPhyllPattern() function with the last x & y coordinates being visited after drawing the Phyllotaxis pattern.
The drawPetal() function will draw the petals with turtle functions and features, refer Turtle programming.
To code the phyllotaxis pattern, we need to follow these equations:
x = r*cos(θ)
y = r*sin(θ)
r, θ can also vary - so the to form phyllotactic pattern we substitutethe cartesian form
by polar form:
r = c*sqrt(n)
θ = n*137.508°
Reduces the problem to optimal packing on a disc, so
r = c*sqrt(n) is from the area of the circle
Area = πr2 and n fills the Area in some units
c1 * n/π = r2, c is 1/sqrt(c1/π)
So, r = some constant c * sqrt(n)
PseudoCode : Phyllotaxis Pattern
IMPORT MODULES ( MATH, TURTLE )
FUNCTION - DrawPhyllotaxisPattern( turtle, t length, petalstart, angle = 137.508, size, cspread)
turtleColor("Black")
FillColor('"Orange")
Convert angle to radians (Φ)
initialize ( xcenter,ycenter ) = ( 0,0 )
Drawing the Pattern Starts:
For n in Range ( 0,t ):
r = cspread * sqrt(n)
θ = n * Φ
x = r * cos(θ) + xcenter
y = r * sin(θ) + ycenter
TURTLE POSITION(x,y)
START DRAWING():
if Drawing pattern ends:
DrawFlowerPetals()
FUNCTION - DrawFlowerPetals(Turtle, x coordinate, y coordinate)
DRAW using Turtle methods
Create Turtle = gfg
Call DrawPhyllotaxisPattern( gfg, t length, petalstart, angle = 137.508, size, cspread)
END
Python Pattern A
Python Pattern B
import math import turtle def drawPhyllPattern(turtle, t, petalstart, angle = 137.508, size = 2, cspread = 4 ): """print a pattern of circles using spiral phyllotactic data""" # initialize position # turtle.pen(outline=1, pencolor="black", fillcolor="orange") turtle.color('black') turtle.fillcolor("orange") phi = angle * ( math.pi / 180.0 ) #we convert to radian xcenter = 0.0 ycenter = 0.0 # for loops iterate in this case from the first value until < 4, so for n in range (0, t): r = cspread * math.sqrt(n) theta = n * phi x = r * math.cos(theta) + xcenter y = r * math.sin(theta) + ycenter # move the turtle to that position and draw turtle.up() turtle.setpos(x, y) turtle.down() # orient the turtle correctly turtle.setheading(n * angle) if n > petalstart-1: turtle.color("yellow") drawPetal(turtle, x, y) else: turtle.stamp() def drawPetal(turtle, x, y ): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.color('black') turtle.fillcolor('yellow') turtle.begin_fill() turtle.right(20) turtle.forward(70) turtle.left(40) turtle.forward(70) turtle.left(140) turtle.forward(70) turtle.left(40) turtle.forward(70) turtle.penup() turtle.end_fill() # this is needed to complete the last petal gfg = turtle.Turtle()gfg.shape("turtle")gfg.speed(0) # make the turtle go as fast as possibledrawPhyllPattern(gfg, 200, 160, 137.508 )gfg.penup()gfg.forward(1000)
import math import turtle def drawPhyllotacticPattern( t, petalstart, angle = 137.508, size = 2, cspread = 4 ): """print a pattern of circles using spiral phyllotactic data""" # initialize position turtle.pen(outline=1, pencolor="black", fillcolor="orange") # turtle.color("orange") phi = angle * ( math.pi / 180.0 ) xcenter = 0.0 ycenter = 0.0 # for loops iterate in this case from the first value until < 4, so for n in range (0, t): r = cspread * math.sqrt(n) theta = n * phi x = r * math.cos(theta) + xcenter y = r * math.sin(theta) + ycenter # move the turtle to that position and draw turtle.up() turtle.setpos(x, y) turtle.down() # orient the turtle correctly turtle.setheading(n * angle) if n > petalstart-1: #turtle.color("yellow") drawPetal(x, y) else: turtle.stamp() def drawPetal( x, y ): turtle.up() turtle.setpos(x, y) turtle.down() turtle.begin_fill() #turtle.fill(True) turtle.pen(outline=1, pencolor="black", fillcolor="yellow") turtle.right(20) turtle.forward(100) turtle.left(40) turtle.forward(100) turtle.left(140) turtle.forward(100) turtle.left(40) turtle.forward(100) turtle.up() turtle.end_fill() # this is needed to complete the last petal turtle.shape("turtle")turtle.speed(0) # make the turtle go as fast as possibledrawPhyllotacticPattern( 200, 160, 137.508, 4, 10 )turtle.exitonclick() # lets you x out of the window when outside of idle
YouTubeAmartya R Saikia273 subscribersAlgorithmic Botany – Phyllotaxis in PythonWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=85TXZRYsr7E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Sources :
Python and Turtle Graphics by Deborah R. Fowler
Phyllotactic Pattern by Deborah R. Fowler
Python Implementation by Deborah R. Fowler
www.sciteneg.com/PhiTaxis/
Phyllotaxis: The Fibonacci Sequence in Nature
algorithmicbotany.org papers
This article is contributed by Amartya Ranjan Saikia. 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.
GBlog
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Types of Software Testing
Top 10 Python Books for Beginners and Advanced Programmers
Working with PDF files in Python
Naive Bayes Classifiers
Linear Regression (Python Implementation)
Removing stop words with NLTK in Python
ML | Linear Regression | [
{
"code": null,
"e": 25326,
"s": 25298,
"text": "\n07 Dec, 2020"
},
{
"code": null,
"e": 26018,
"s": 25326,
"text": "Phyllotaxis/phyllotaxy is the arrangement of leaves on a plant stem & the Phyllotactic spirals form a distinctive class of patterns in nature. The word itself come... |
DateTime.Subtract() Method in C# - GeeksforGeeks | 10 Feb, 2019
This method is used to subtract the specified time or duration from this instance. There are 2 methods in the overload list of this method as follows:
Subtract(DateTime)
Subtract(TimeSpan)
This method is used to subtract the specified date and time from this instance.
Syntax: public TimeSpan Subtract (DateTime value);
Return Value: This method returns a time interval that is equal to the date and time represented by this instance minus the date and time represented by value.
Exception: This method will give ArgumentOutOfRangeException if the result is less than MinValue or greater than MaxValue.
Below programs illustrate the use of DateTime.Subtract(DateTime) Method:
Example 1:
// C# program to demonstrate the// DateTime.Subtract(DateTime)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2011, 1, 1, 4, 0, 15); // creating object of DateTime DateTime date2 = new DateTime(2010, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using Subtract() method; TimeSpan value = date1.Subtract(date2); // Display the TimeSpan Console.WriteLine("TimeSpan between date1"+ " and date2 is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
TimeSpan between date1 and date2 is 365.00:00:00
Example 2:
// C# program to demonstrate the// DateTime.Subtract(DateTime)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = DateTime.MinValue; // creating object of DateTime DateTime date2 = new DateTime(11119999, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using Subtract() method; TimeSpan value = date1.Subtract(date2); // Display the TimeSpan Console.WriteLine("TimeSpan between date1 "+ "and date2 is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.ArgumentOutOfRangeException
This method is used to subtract the specified duration from this instance.
Syntax: public DateTime Subtract (TimeSpan value);
Return Value: This method returns an object that is equal to the date and time represented by this instance minus the time interval represented by value.
Exception: This method will give ArgumentOutOfRangeException if the result is less than MinValue or greater than MaxValue.
Below programs illustrate the use of DateTime.Subtract(TimeSpan) Method:
Example 1:
// C# program to demonstrate the// DateTime.Subtract(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2011, 1, 1, 4, 0, 15); // creating object of TimeSpan TimeSpan ts = new TimeSpan(1, 12, 15, 16); // getting ShortTime from // subtracting DateTime and TimeSpan // using Subtract() method; DateTime value = date.Subtract(ts); // Display the TimeSpan Console.WriteLine("DateTime between date "+ "and ts is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
DateTime between date and ts is 12/30/2010 15:44:59
Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTime.Subtract(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = DateTime.MinValue; // creating object of TimeSpan TimeSpan ts = new TimeSpan(1, 12, 15, 16); // getting ShortTime from subtracting // DateTime and TimeSpan // using Subtract() method; DateTime value = date.Subtract(ts); // Display the TimeSpan Console.WriteLine("DateTime between date"+ " and ts is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.ArgumentOutOfRangeException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.subtract?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Abstract Classes
C# | Delegates | [
{
"code": null,
"e": 24136,
"s": 24108,
"text": "\n10 Feb, 2019"
},
{
"code": null,
"e": 24287,
"s": 24136,
"text": "This method is used to subtract the specified time or duration from this instance. There are 2 methods in the overload list of this method as follows:"
},
{
... |
Matplotlib.axes.Axes.set_ylim() in Python - GeeksforGeeks | 19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_ylim() function in axes module of matplotlib library is used to set the y-axis view limits.
Syntax: Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None)
Parameters: This method accepts the following parameters.
bottom : This parameter is the bottom ylim in data coordinates
top : This parameter is the top ylim in data coordinates
emit : This parameter is used to notify observers of limit change.
auto : This parameter is used to turn on autoscaling of the x-axis.
ymin, ymax: These parameter are equivalent to bottom and top and it is an error to pass both ymin and bottom or ymax and top.
Returns:This method returns the following
bottom, top:This returns the new y-axis limits in data coordinates.
Below examples illustrate the matplotlib.axes.Axes.set_ylim() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt np.random.seed(19680801) fig, ax = plt.subplots(facecolor ='# A0F0CC') x, y = 4*(np.random.rand(2, 100) - .5)ax.plot(x, y, 'g')ax.set_ylim(-3, 3) cursor = Cursor(ax, useblit = True, color ='red', linewidth = 2) ax.set_title('matplotlib.axes.Axes.set_ylim() Example\n', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-0.5, 1.5), ylim =(-0.5, 1.5), autoscale_on = False)ax2.set(xlim =(0.5, 0.75), ylim =(0.5, 0.75), autoscale_on = False) x, y, s, c = np.random.rand(4, 200)s *= 200 ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c) def GFG(event): if event.button != 1: return x, y = event.xdata, event.ydata ax2.set_xlim(x - 0.1, x + 0.1) ax2.set_ylim(y - 0.1, y + 0.1) fig2.canvas.draw() fig1.canvas.mpl_connect('button_press_event', GFG) ax1.set_title('matplotlib.axes.Axes.set_ylim()\ Example\n Original Window ', fontsize = 14, fontweight ='bold')ax2.set_title('Zoomed window ', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24756,
"s": 24728,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 25056,
"s": 24756,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, ... |
ggplot2 - Diverging Charts | In the previous chapters, we had a look on various types of charts which can be created using “ggplot2” package. We will now focus on the variation of same like diverging bar charts, lollipop charts and many more. To begin with, we will start with creating diverging bar charts and the steps to be followed are mentioned below −
Load the required package and create a new column called ‘car name’ within mpg dataset.
#Load ggplot
> library(ggplot2)
> # create new column for car names
> mtcars$`car name` <- rownames(mtcars)
> # compute normalized mpg
> mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)
> # above / below avg flag
> mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")
> # sort
> mtcars <- mtcars[order(mtcars$mpg_z), ]
The above computation involves creating a new column for car names, computing the normalized dataset with the help of round function. We can also use above and below avg flag to get the values of “type” functionality. Later, we sort the values to create the required dataset.
The output received is as follows −
Convert the values to factor to retain the sorted order in a particular plot as mentioned below −
> # convert to factor to retain sorted order in plot.
> mtcars$`car name` <- factor(mtcars$`car name`, levels = mtcars$`car name`)
The output obtained is mentioned below −
Now create a diverging bar chart with the mentioned attributes which is taken as required co-ordinates.
> # Diverging Barcharts
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_bar(stat='identity', aes(fill=mpg_type), width=.5) +
+ scale_fill_manual(name="Mileage",
+ labels = c("Above Average", "Below Average"),
+ values = c("above"="#00ba38", "below"="#f8766d")) +
+ labs(subtitle="Normalised mileage from 'mtcars'",
+ title= "Diverging Bars") +
+ coord_flip()
Note − A diverging bar chart marks for some dimension members pointing to up or down direction with respect to mentioned values.
The output of diverging bar chart is mentioned below where we use function geom_bar for creating a bar chart −
Create a diverging lollipop chart with same attributes and co-ordinates with only change of function to be used, i.e. geom_segment() which helps in creating the lollipop charts.
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_point(stat='identity', fill="black", size=6) +
+ geom_segment(aes(y = 0,
+ x = `car name`,
+ yend = mpg_z,
+ xend = `car name`),
+ color = "black") +
+ geom_text(color="white", size=2) +
+ labs(title="Diverging Lollipop Chart",
+ subtitle="Normalized mileage from 'mtcars': Lollipop") +
+ ylim(-2.5, 2.5) +
+ coord_flip()
Create a diverging dot plot in similar manner where the dots represent the points in scattered plots in bigger dimension.
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_point(stat='identity', aes(col=mpg_type), size=6) +
+ scale_color_manual(name="Mileage",
+ labels = c("Above Average", "Below Average"),
+ values = c("above"="#00ba38", "below"="#f8766d")) +
+ geom_text(color="white", size=2) +
+ labs(title="Diverging Dot Plot",
+ subtitle="Normalized mileage from 'mtcars': Dotplot") +
+ ylim(-2.5, 2.5) +
+ coord_flip()
Here, the legends represent the values “Above Average” and “Below Average” with distinct colors of green and red. Dot plot convey static information. The principles are same as the one in Diverging bar chart, except that only point are used.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2351,
"s": 2022,
"text": "In the previous chapters, we had a look on various types of charts which can be created using “ggplot2” package. We will now focus on the variation of same like diverging bar charts, lollipop charts and many more. To begin with, we will start with creat... |
Kurtosis, explained intuitively | by Sundaresh Chandran | Towards Data Science | Kurtosis is one of the core concepts in descriptive statistics and is also part of standardized moments in mathematics. The concept itself though easy is often misinterpreted and misunderstood because of the vague definition associated with it. In this article, I’ll try to explain the intuition behind kurtosis and its characteristics in very simple terms as I’d convey it to a 10-year-old.
If you’re hearing the words kurtosis for the first time, the story will help to grasp the core concept behind it. If you know it well and perhaps want to explain this to your niece or nephew (or someone who is non-stats-savvy), this will help with that
Imagine you’re going grocery shopping with your parents. Since they have their hands full, they ask you to carry two, five kg bags on each arm. You grudgingly agree and carry each 5KG bag in each arm.
Now, you notice something. The closer the bags are to your body, the easier they are to carry. The farther outstretched your arms are from your body, the harder it gets to manage the weights.
In this particular example, the farther you move away from your body, the harder it gets and higher the kurtosis. The distance from your center of gravity in the above example is proportional to the intuition of kurtosis (and the difficulty to manage the weights) or can be said as equal to kurtosis for the sake of simplicity.
Now if we increase the weight from 5kgs to 10kgs and then to 15kgs, the difficulty starting from easy to medium to hard also goes up rapidly and so does the kurtosis value.
Now replace yourself in the above example with a normal distribution probability density function. Since most of your weight is concentrated very close to your center of gravity, you are said to have a Pearson’s kurtosis of 3 or Fisher’s kurtosis of 0.
Kurtosis, in very simple terms, is the weight on the extremes ends of a distribution. In the above example, the weights, farther away from your center of gravity were harder to handle/manage
Fisher’s kurtosis compares how tail-heavy a distribution is with respect to a normal distribution (regardless of its mean and standard deviation). A positive Fisher’s kurtosis means the distribution has significant outliers while a negative Fisher’s kurtosis would mean that the distribution of probability density is much more uniform compared to a normal distribution
Distributions, which have 0 or very close to zero Fisher kurtosis are called Mesokurtic distributions. Normal distribution falls under this bucket.
Distributions, that are uniform or flat-topped, have negative Fisher’s kurtosis and are also called platykurtic distributions. Ex: uniform distribution
Distributions with high positive Fisher’s kurtosis are called leptokurtic distributions. Leptokurtic distributions are ‘tail-heavy distributions that suffer from outliers that may require handling or processing depending on the use case. Ex: Levy distrbution, laplace distribution etc.
The -3 component is added to the Pearson’s kurtosis to make it centered around the normal distribution and hence is also referred to as the ‘excess kurtosis’
Kurtosis can be conveniently computed via scipy package. Below is a code for reference for computing kurtosis for various important distributions
import scipy.stats as statsfrom scipy.stats import kurtosisdistribution_names = ['uniform', 'norm', 'laplace', 'levy']for distribution_name in distribution_names: if distribution_name == 'uniform': distribution = getattr(stats, distribution_name)(loc=-2, scale=4) else: distribution = getattr(stats, distribution_name) sample_data = distribution.rvs(size=1000) kurtosis_value = kurtosis(sample_data, fisher=True) # notice the fisher param print(f"kurtosis value of the {distribution_name} distribution is {round(kurtosis_value, 2)}")
As expected, the kurtosis for levy distribution, a notoriously outlier heavy distribution has a very high kurtosis value compared to other distributions. The value of the normal distribution is not exactly zero, since it is not taken from a continuous distribution. If you play around with the sample size, the larger the sample_data size, the closer you get to zero. If we increase the dataset size to 108, we get the below result
As you might’ve also noticed, the kurtosis for tail-heavy distribution explodes as the sample size increases.
Python Scipy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.htmlMoments in mathematics: https://en.wikipedia.org/wiki/Moment_(mathematics)
Python Scipy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html
Moments in mathematics: https://en.wikipedia.org/wiki/Moment_(mathematics)
If you liked the intuitiveness and simplicity of the article, you might also like some of the other simplified versions of the statistics concept below:
Eigenvectors & Eigenvalues — How to explain to a 10-year-old by Sundaresh Chandran in Towards Data ScienceEntropy, explained simply by Sundaresh Chandran in Towards Data Science
Eigenvectors & Eigenvalues — How to explain to a 10-year-old by Sundaresh Chandran in Towards Data Science
Entropy, explained simply by Sundaresh Chandran in Towards Data Science
Please leave a clap/comment in case you found it useful. | [
{
"code": null,
"e": 564,
"s": 172,
"text": "Kurtosis is one of the core concepts in descriptive statistics and is also part of standardized moments in mathematics. The concept itself though easy is often misinterpreted and misunderstood because of the vague definition associated with it. In this ar... |
Longest Common Increasing Subsequence (LCS + LIS) - GeeksforGeeks | 22 Dec, 2021
Prerequisites : LCS, LISGiven two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may exist)Suppose we consider two arrays – arr1[] = {3, 4, 9, 1} and arr2[] = {5, 3, 8, 9, 10, 2, 1}Our answer would be {3, 9} as this is the longest common subsequence which is increasing also.
The idea is to use dynamic programming here as well. We store the longest common increasing sub-sequence ending at each index of arr2[]. We create an auxiliary array table[] such that table[j] stores length of LCIS ending with arr2[j]. At the end, we return maximum value from this table. For filling values in this table, we traverse all elements of arr1[] and for every element arr1[i], we traverse all elements of arr2[]. If we find a match, we update table[j] with length of current LCIS. To maintain current LCIS, we keep checking valid table[j] values.Below is the program to find length of LCIS.
C++
Java
Python 3
C#
PHP
Javascript
// A C++ Program to find length of the Longest Common// Increasing Subsequence (LCIS)#include<bits/stdc++.h>using namespace std; // Returns the length and the LCIS of two// arrays arr1[0..n-1] and arr2[0..m-1]int LCIS(int arr1[], int n, int arr2[], int m){ // table[j] is going to store length of LCIS // ending with arr2[j]. We initialize it as 0, int table[m]; for (int j=0; j<m; j++) table[j] = 0; // Traverse all elements of arr1[] for (int i=0; i<n; i++) { // Initialize current length of LCIS int current = 0; // For each element of arr1[], traverse all // elements of arr2[]. for (int j=0; j<m; j++) { // If both the array have same elements. // Note that we don't break the loop here. if (arr1[i] == arr2[j]) if (current + 1 > table[j]) table[j] = current + 1; /* Now seek for previous smaller common element for current element of arr1 */ if (arr1[i] > arr2[j]) if (table[j] > current) current = table[j]; } } // The maximum value in table[] is out result int result = 0; for (int i=0; i<m; i++) if (table[i] > result) result = table[i]; return result;} /* Driver program to test above function */int main(){ int arr1[] = {3, 4, 9, 1}; int arr2[] = {5, 3, 8, 9, 10, 2, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); int m = sizeof(arr2)/sizeof(arr2[0]); cout << "Length of LCIS is " << LCIS(arr1, n, arr2, m); return (0);}
// A Java Program to find length of the Longest// Common Increasing Subsequence (LCIS)import java.io.*; class GFG { // Returns the length and the LCIS of two // arrays arr1[0..n-1] and arr2[0..m-1] static int LCIS(int arr1[], int n, int arr2[], int m) { // table[j] is going to store length of // LCIS ending with arr2[j]. We initialize // it as 0, int table[] = new int[m]; for (int j = 0; j < m; j++) table[j] = 0; // Traverse all elements of arr1[] for (int i = 0; i < n; i++) { // Initialize current length of LCIS int current = 0; // For each element of arr1[], traverse // all elements of arr2[]. for (int j = 0; j < m; j++) { // If both the array have same // elements. Note that we don't // break the loop here. if (arr1[i] == arr2[j]) if (current + 1 > table[j]) table[j] = current + 1; /* Now seek for previous smaller common element for current element of arr1 */ if (arr1[i] > arr2[j]) if (table[j] > current) current = table[j]; } } // The maximum value in table[] is out // result int result = 0; for (int i=0; i<m; i++) if (table[i] > result) result = table[i]; return result; } /* Driver program to test above function */ public static void main(String[] args) { int arr1[] = {3, 4, 9, 1}; int arr2[] = {5, 3, 8, 9, 10, 2, 1}; int n = arr1.length; int m = arr2.length; System.out.println("Length of LCIS is " + LCIS(arr1, n, arr2, m)); }}// This code is contributed by Prerna Saini
# Python 3 Program to find length of the # Longest Common Increasing Subsequence (LCIS) # Returns the length and the LCIS of two# arrays arr1[0..n-1] and arr2[0..m-1]def LCIS(arr1, n, arr2, m): # table[j] is going to store length of LCIS # ending with arr2[j]. We initialize it as 0, table = [0] * m for j in range(m): table[j] = 0 # Traverse all elements of arr1[] for i in range(n): # Initialize current length of LCIS current = 0 # For each element of arr1[], # traverse all elements of arr2[]. for j in range(m): # If both the array have same elements. # Note that we don't break the loop here. if (arr1[i] == arr2[j]): if (current + 1 > table[j]): table[j] = current + 1 # Now seek for previous smaller common # element for current element of arr1 if (arr1[i] > arr2[j]): if (table[j] > current): current = table[j] # The maximum value in table[] # is out result result = 0 for i in range(m): if (table[i] > result): result = table[i] return result # Driver Codeif __name__ == "__main__": arr1 = [3, 4, 9, 1] arr2 = [5, 3, 8, 9, 10, 2, 1] n = len(arr1) m = len(arr2) print("Length of LCIS is", LCIS(arr1, n, arr2, m)) # This code is contributed by ita_c
// A C# Program to find length of the Longest// Common Increasing Subsequence (LCIS)using System; class GFG { // Returns the length and the LCIS of two // arrays arr1[0..n-1] and arr2[0..m-1] static int LCIS(int []arr1, int n, int []arr2, int m) { // table[j] is going to store length of // LCIS ending with arr2[j]. We initialize // it as 0, int []table = new int[m]; for (int j = 0; j < m; j++) table[j] = 0; // Traverse all elements of arr1[] for (int i = 0; i < n; i++) { // Initialize current length of LCIS int current = 0; // For each element of arr1[], traverse // all elements of arr2[]. for (int j = 0; j < m; j++) { // If both the array have same // elements. Note that we don't // break the loop here. if (arr1[i] == arr2[j]) if (current + 1 > table[j]) table[j] = current + 1; /* Now seek for previous smaller common element for current element of arr1 */ if (arr1[i] > arr2[j]) if (table[j] > current) current = table[j]; } } // The maximum value in // table[] is out result int result = 0; for (int i = 0; i < m; i++) if (table[i] > result) result = table[i]; return result; } /* Driver program to test above function */ public static void Main() { int []arr1 = {3, 4, 9, 1}; int []arr2 = {5, 3, 8, 9, 10, 2, 1}; int n = arr1.Length; int m = arr2.Length; Console.Write("Length of LCIS is " + LCIS(arr1, n, arr2, m)); }} // This code is contributed by nitin mittal.
<?php// PHP Program to find length of// the Longest Common Increasing // Subsequence (LCIS) // Returns the length and the LCIS // of two arrays arr1[0..n-1] and // arr2[0..m-1]function LCIS($arr1, $n, $arr2, $m){ // table[j] is going to store // length of LCIS ending with // arr2[j]. We initialize it as 0, $table = Array(); //int table[m]; for ($j = 0; $j < $m; $j++) $table[$j] = 0; // Traverse all elements of arr1[] for ($i = 0; $i < $n; $i++) { // Initialize current // length of LCIS $current = 0; // For each element of // arr1[], traverse all // elements of arr2[]. for ($j = 0; $j < $m; $j++) { // If both the array have // same elements. Note that // we don't break the loop here. if ($arr1[$i] == $arr2[$j]) if ($current + 1 > $table[$j]) $table[$j] = $current + 1; /* Now seek for previous smaller common element for current element of arr1 */ if ($arr1[$i] > $arr2[$j]) if ($table[$j] > $current) $current = $table[$j]; } } // The maximum value in // table[] is out result $result = 0; for ($i = 0; $i < $m; $i++) if ($table[$i] > $result) $result = $table[$i]; return $result;} // Driver Code$arr1 = array (3, 4, 9, 1);$arr2 = array (5, 3, 8, 9, 10, 2, 1); $n = sizeof($arr1);$m = sizeof($arr2); echo "Length of LCIS is ", LCIS($arr1, $n, $arr2, $m); // This code is contributed by ajit ?>
<script> // Javascript Program to find length of the Longest// Common Increasing Subsequence (LCIS) // Returns the length and the LCIS of two // arrays arr1[0..n-1] and arr2[0..m-1] function LCIS(arr1, n, arr2, m) { // table[j] is going to store length of // LCIS ending with arr2[j]. We initialize // it as 0, let table = []; for (let j = 0; j < m; j++) table[j] = 0; // Traverse all elements of arr1[] for (let i = 0; i < n; i++) { // Initialize current length of LCIS let current = 0; // For each element of arr1[], traverse // all elements of arr2[]. for (let j = 0; j < m; j++) { // If both the array have same // elements. Note that we don't // break the loop here. if (arr1[i] == arr2[j]) if (current + 1 > table[j]) table[j] = current + 1; /* Now seek for previous smaller common element for current element of arr1 */ if (arr1[i] > arr2[j]) if (table[j] > current) current = table[j]; } } // The maximum value in table[] is out // result let result = 0; for (let i=0; i<m; i++) if (table[i] > result) result = table[i]; return result; } // Driver Code let arr1 = [3, 4, 9, 1]; let arr2 = [5, 3, 8, 9, 10, 2, 1]; let n = arr1.length; let m = arr2.length; document.write("Length of LCIS is " + LCIS(arr1, n, arr2, m)); </script>
Output :
Length of LCIS is 2
This article is contributed Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@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
nitin mittal
jit_t
AyanBanerjee
ukasp
mohit kumar 29
souravghosh0416
simranarora5sos
LCS
LIS
subsequence
Arrays
Dynamic Programming
Arrays
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25174,
"s": 24820,
"text": "Prerequisites : LCS, LISGiven two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may e... |
Count number of ways to reach destination in a maze - GeeksforGeeks | 04 Aug, 2021
Given a maze of 0 and -1 cells, the task is to find all the paths from (0, 0) to (n-1, m-1), and every path should pass through at least one cell which contains -1. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. This problem is a variation of the problem published here.Examples:
Input: maze[][] = { {0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}} Output: 16
Approach: To find all the paths which go through at least one marked cell (cell containing -1). If we find the paths that do not go through any of the marked cells and all the possible paths from (0, 0) to (n-1, m-1) then we can find all the paths that go through at least one of the marks cells. Number of paths that pass through at least one marked cell = (Total number of paths – Number of paths that do not pass through any marked cell) We will use the approach mentioned in this article to find the total number of paths that do not pass through any marked cell and the total number of paths from source to destination will be (m + n – 2)! / (n – 1)! * (m – 1)! where m and n are the number of rows and columns. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // Function to return the count of possible paths// in a maze[R][C] from (0, 0) to (R-1, C-1) that// do not pass through any of the marked cellsint countPaths(int maze[][C]){ // If the initial cell is blocked, there is no // way of moving anywhere if (maze[0][0] == -1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (int i = 1; i < C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in bottommost // row, there is no way of visiting any cell // directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { // If blockage is found, ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from maze[i-1][j] // then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from maze[i][j-1] // then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, output 0, otherwise // the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0;}// Function to return the count of all possible// paths from (0, 0) to (n - 1, m - 1)int numberOfPaths(int m, int n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Function to return the total count of paths// from (0, 0) to (n - 1, m - 1) that pass// through at least one of the marked cellsint solve(int maze[][C]){ // Total count of paths - Total paths that do not // pass through any of the marked cell int ans = numberOfPaths(R, C) - countPaths(maze); // return answer return ans;} // Driver codeint main(){ int maze[R][C] = { { 0, 0, 0, 0 }, { 0, -1, 0, 0 }, { -1, 0, 0, 0 }, { 0, 0, 0, 0 } }; cout << solve(maze); return 0;}
// Java implementation of the approachimport java.io.*; class GFG{static int R = 4;static int C = 4; // Function to return the count of possible paths// in a maze[R][C] from (0, 0) to (R-1, C-1) that// do not pass through any of the marked cellsstatic int countPaths(int maze[][]){ // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0][0] == -1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (int i = 1; i < C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in bottommost // row, there is no way of visiting any cell // directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { // If blockage is found, ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0;} // Function to return the count of all possible// paths from (0, 0) to (n - 1, m - 1)static int numberOfPaths(int m, int n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Function to return the total count of paths// from (0, 0) to (n - 1, m - 1) that pass// through at least one of the marked cellsstatic int solve(int maze[][]){ // Total count of paths - Total paths that do not // pass through any of the marked cell int ans = numberOfPaths(R, C) - countPaths(maze); // return answer return ans;} // Driver codepublic static void main (String[] args){ int maze[][] = { { 0, 0, 0, 0 }, { 0, -1, 0, 0 }, { -1, 0, 0, 0 }, { 0, 0, 0, 0 } }; System.out.println(solve(maze));}} // This code is contributed by anuj_67..
# Python3 implementation of the approachR = 4C = 4 # Function to return the count of# possible paths in a maze[R][C]# from (0, 0) to (R-1, C-1) that# do not pass through any of# the marked cellsdef countPaths(maze): # If the initial cell is blocked, # there is no way of moving anywhere if (maze[0][0] == -1): return 0 # Initializing the leftmost column for i in range(R): if (maze[i][0] == 0): maze[i][0] = 1 # If we encounter a blocked cell # in leftmost row, there is no way of # visiting any cell directly below it. else: break # Similarly initialize the topmost row for i in range(1, C): if (maze[0][i] == 0): maze[0][i] = 1 # If we encounter a blocked cell in # bottommost row, there is no way of # visiting any cell directly below it. else: break # The only difference is that if # a cell is -1, simply ignore it # else recursively compute # count value maze[i][j] for i in range(1, R): for j in range(1, C): # If blockage is found, # ignore this cell if (maze[i][j] == -1): continue # If we can reach maze[i][j] from # maze[i-1][j] then increment count. if (maze[i - 1][j] > 0): maze[i][j] = (maze[i][j] + maze[i - 1][j]) # If we can reach maze[i][j] from # maze[i][j-1] then increment count. if (maze[i][j - 1] > 0): maze[i][j] = (maze[i][j] + maze[i][j - 1]) # If the final cell is blocked, # output 0, otherwise the answer if (maze[R - 1][C - 1] > 0): return maze[R - 1][C - 1] else: return 0 # Function to return the count of# all possible paths from# (0, 0) to (n - 1, m - 1)def numberOfPaths(m, n): # We have to calculate m+n-2 C n-1 here # which will be (m+n-2)! / (n-1)! (m-1)! path = 1 for i in range(n, m + n - 1): path *= i path //= (i - n + 1) return path # Function to return the total count# of paths from (0, 0) to (n - 1, m - 1)# that pass through at least one# of the marked cellsdef solve(maze): # Total count of paths - Total paths # that do not pass through any of # the marked cell ans = (numberOfPaths(R, C) - countPaths(maze)) # return answer return ans # Driver codemaze = [[ 0, 0, 0, 0 ], [ 0, -1, 0, 0 ], [ -1, 0, 0, 0 ], [ 0, 0, 0, 0 ]] print(solve(maze)) # This code is contributed# by Mohit Kumar
// C# implementation of the approachusing System;class GFG{static int R = 4;static int C = 4; // Function to return the count of possible paths// in a maze[R][C] from (0, 0) to (R-1, C-1) that// do not pass through any of the marked cellsstatic int countPaths(int [,]maze){ // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0, 0] == -1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i, 0] == 0) maze[i, 0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (int i = 1; i < C; i++) { if (maze[0, i] == 0) maze[0, i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { // If blockage is found, ignore this cell if (maze[i, j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1, j] > 0) maze[i, j] = (maze[i, j] + maze[i - 1, j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i, j - 1] > 0) maze[i, j] = (maze[i, j] + maze[i, j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1, C - 1] > 0) ? maze[R - 1, C - 1] : 0;} // Function to return the count of all possible// paths from (0, 0) to (n - 1, m - 1)static int numberOfPaths(int m, int n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Function to return the total count of paths// from (0, 0) to (n - 1, m - 1) that pass// through at least one of the marked cellsstatic int solve(int [,]maze){ // Total count of paths - Total paths that do not // pass through any of the marked cell int ans = numberOfPaths(R, C) - countPaths(maze); // return answer return ans;} // Driver codepublic static void Main (){ int [,]maze = {{ 0, 0, 0, 0 }, { 0, -1, 0, 0 }, { -1, 0, 0, 0 }, { 0, 0, 0, 0 }}; Console.Write(solve(maze));}} // This code is contributed by anuj_67..
<script> // Javascript implementation of the approachvar R = 4var C = 4 // Function to return the count of possible paths// in a maze[R][C] from (0, 0) to (R-1, C-1) that// do not pass through any of the marked cellsfunction countPaths(maze){ // If the initial cell is blocked, there is no // way of moving anywhere if (maze[0][0] == -1) return 0; // Initializing the leftmost column for (var i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (var i = 1; i < C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in bottommost // row, there is no way of visiting any cell // directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (var i = 1; i < R; i++) { for (var j = 1; j < C; j++) { // If blockage is found, ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from maze[i-1][j] // then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from maze[i][j-1] // then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, output 0, otherwise // the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0;}// Function to return the count of all possible// paths from (0, 0) to (n - 1, m - 1)function numberOfPaths(m, n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! var path = 1; for (var i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Function to return the total count of paths// from (0, 0) to (n - 1, m - 1) that pass// through at least one of the marked cellsfunction solve(maze){ // Total count of paths - Total paths that do not // pass through any of the marked cell var ans = numberOfPaths(R, C) - countPaths(maze); // return answer return ans;} // Driver codevar maze = [ [ 0, 0, 0, 0 ], [ 0, -1, 0, 0 ], [ -1, 0, 0, 0 ], [ 0, 0, 0, 0 ] ];document.write( solve(maze)); // This code is contributed by rrrtnx.</script>
16
Time Complexity: O(R*C)Auxiliary Space: O(R*C)
mohit kumar 29
vt_m
rrrtnx
pankajsharmagfg
Algorithms
Backtracking
Matrix
Matrix
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
K means Clustering - Introduction
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7 | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 25006,
"s": 24692,
"text": "Given a maze of 0 and -1 cells, the task is to find all the paths from (0, 0) to (n-1, m-1), and every path should pass through at least one cell which contains -1... |
Communication between Activity and Service in Android? | This example demonstrates how do I communicate between Activity and Service in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<Button
android:id="@+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Start Service" />
<Button
android:id="@+id/buttonStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Stop Service" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button buttonStart, buttonStop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
}
}
}
Step 4 − Create a new Service(MyService) and add the following code to MyServices.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
MediaPlayer myPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service Created",
Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.song);
myPlayer.setLooping(false);
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started",
Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped",
Toast.LENGTH_LONG).show();
myPlayer.stop();
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how do I communicate between Activity and Service in android."
},
{
"code": null,
"e": 1279,
"s": 1150,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all require... |
Operating Systems | Set 6 - GeeksforGeeks | 27 Mar, 2017
Following questions have been asked in GATE 2011 CS exam.
1) A thread is usually defined as a ‘light weight process’ because an operating system (OS) maintains smaller data structures for a thread than for a process. In relation to this, which of the followings is TRUE?(A) On per-thread basis, the OS maintains only CPU register state(B) The OS does not maintain a separate stack for each thread(C) On per-thread basis, the OS does not maintain virtual memory state(D) On per thread basis, the OS maintains only scheduling and accounting information.
Answer (C)Threads share address space of Process. Virtually memory is concerned with processes not with Threads.
2) Let the page fault service time be 10ms in a computer with average memory access time being 20ns. If one page fault is generated for every 10^6 memory accesses, what is the effective access time for the memory?(A) 21ns(B) 30ns(C) 23ns(D) 35ns
Answer (B)
Let P be the page fault rate
Effective Memory Access Time = p * (page fault service time) +
(1 - p) * (Memory access time)
= ( 1/(10^6) )* 10 * (10^6) ns +
(1 - 1/(10^6)) * 20 ns
= 30 ns (approx)
3) An application loads 100 libraries at startup. Loading each library requires exactly one disk access. The seek time of the disk to a random location is given as 10ms. Rotational speed of disk is 6000rpm. If all 100 libraries are loaded from random locations on the disk, how long does it take to load all libraries? (The time to transfer data from the disk block once the head has been positioned at the start of the block may be neglected)(A) 0.50s(B) 1.50s(C) 1.25s(D) 1.00s
Answer (B)Since transfer time can be neglected, the average access time is sum of average seek time and average rotational latency. Average seek time for a random location time is given as 10 ms. The average rotational latency is half of the time needed for complete rotation. It is given that 6000 rotations need 1 minute. So one rotation will take 60/6000 seconds which is 10 ms. Therefore average rotational latency is half of 10 ms, which is 5ms.
Average disk access time = seek time + rotational latency
= 10 ms + 5 ms
= 15 ms
For 100 libraries, the average disk access time will be 15*100 ms
4. Consider the following table of arrival time and burst time for three processes P0, P1 and P2.
Process Arrival time Burst Time
P0 0 ms 9 ms
P1 1 ms 4 ms
P2 2 ms 9 ms
The pre-emptive shortest job first scheduling algorithm is used. Scheduling is carried out only at arrival or completion of processes. What is the average waiting time for the three processes?(A) 5.0 ms(B) 4.33 ms(C) 6.33 ms(D) 7.33 ms
Answer: – (A)Process P0 is allocated processor at 0 ms as there is no other process in ready queue. P0 is preempted after 1 ms as P1 arrives at 1 ms and burst time for P1 is less than remaining time of P0. P1 runs for 4ms. P2 arrived at 2 ms but P1 continued as burst time of P2 is longer than P1. After P1 completes, P0 is scheduled again as the remaining time for P0 is less than the burst time of P2.P0 waits for 4 ms, P1 waits for 0 ms amd P2 waits for 11 ms. So average waiting time is (0+4+11)/3 = 5.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2011
GATE CS
MCQ
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
Types of Network Topology
Computer Networks | Set 1
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 2
Operating Systems | Set 1
Database Management Systems | Set 1 | [
{
"code": null,
"e": 24018,
"s": 23990,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 24076,
"s": 24018,
"text": "Following questions have been asked in GATE 2011 CS exam."
},
{
"code": null,
"e": 24570,
"s": 24076,
"text": "1) A thread is usually defined a... |
Angular 10 getCurrencySymbol() Method - GeeksforGeeks | 24 May, 2021
In this article, we are going to see what is getCurrencySymbol in Angular 10 and how to use it. getCurrencySymbol is used to retrieve the currency symbol for a given currency code
Syntax:
getCurrencySymbol(code, locale, format)
Parameters:
code: The currency code
locale: A locale code for the locale format rule to use.
format: The format.
Return Value:
string: the formatted date string.
NgModule: Module used by getCurrencySymbol is:
CommonModule
Approach:
Create the Angular app to be used.
In app.module.ts import LOCALE_ID because we need locale to be imported for using get getCurrencySymbol.
import { LOCALE_ID, NgModule } from '@angular/core';
In app.component.ts import getCurrencySymbol and LOCALE_ID
inject LOCALE_ID as a public variable.
In app.component.html show the local variable using string interpolation
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { getCurrencySymbol } from '@angular/common'; import {Component} from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = getCurrencySymbol("USD", "wide");}
app.component.html
<h1> GeeksforGeeks</h1> <p>{{curr }} 100</p>
Output:
Example 2:
app.component.ts
import { getCurrencySymbol } from '@angular/common'; import {Component} from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = getCurrencySymbol("INR", "narrow");}
app.component.html
<h1> GeeksforGeeks</h1> <p>{{curr }} 304</p>
Output:
Reference: https://angular.io/api/common/getCurrencySymbol
Angular10
AngularJS-Function
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25289,
"s": 25109,
"text": "In this article, we are going to see what is getCurrencySymbol in Angular 10 and how to use it. getCurrencySymbol is used to retrieve the currency symbol for a giv... |
How to check similarity between two strings in MySQL? | Similarity between two strings can be checked with the help of ‘strcmp()’ function. Here are the conditions.
If both strings are equal, then it returns 0.
If both strings are equal, then it returns 0.
If first string is less than the second string, it returns -1.
If first string is less than the second string, it returns -1.
If first string is greater than the second string, it returns 1.
If first string is greater than the second string, it returns 1.
Here is an example.
Case 1 − If both strings are equal.
The following is the query.
mysql > SELECT STRCMP("demo", "demo");
The following is the output of the above query.
+------------------------+
| STRCMP("demo", "demo") |
+------------------------+
| 0 |
+------------------------+
1 row in set (0.00 sec)
Case 2 − If first string is less than the second string.
The following is the query.
mysql> SELECT STRCMP("demo", "demo1234");
The following is the output of the above query.
+----------------------------+
| STRCMP("demo", "demo1234") |
+----------------------------+
| -1 |
+----------------------------+
1 row in set (0.00 sec)
Case 3 − If first string is greater than the second string.
The following is the query.
mysql> SELECT STRCMP("demo1", "demo");
The following is the output.
+-------------------------+
| STRCMP("demo1", "demo") |
+-------------------------+
| 1 |
+-------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "Similarity between two strings can be checked with the help of ‘strcmp()’ function. Here are the conditions."
},
{
"code": null,
"e": 1217,
"s": 1171,
"text": "If both strings are equal, then it returns 0."
},
{
"code": null,... |
jQuery Effect - toggle( switch ) Method | The toggle( switch ) method toggle displaying each of the set of matched elements based upon the passed parameter. If true parameter shows all elements, false hides all elements.
Here is the simple syntax to use this method −
selector.toggle( switch );
Here is the description of all the parameters used by this method −
switch − A switch to toggle the display on.
switch − A switch to toggle the display on.
Following is a simple example a simple showing the usage of this method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#false").click(function(){
$(".target").toggle(false);
});
$("#true").click(function(){
$(".target").toggle(true);
});
});
</script>
<style>
p {background-color:#bca; width:250px; border:1px solid green;}
</style>
</head>
<body>
<p>Click on any of the following buttons:</p>
<button id = "false"> False Switch </button>
<button id = "true"> True Switch </button>
<div class = "target">
<img src = "../images/jquery.jpg" alt = "jQuery" />
</div>
</body>
</html>
This will produce following result −
Click on any of the following buttons −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2501,
"s": 2322,
"text": "The toggle( switch ) method toggle displaying each of the set of matched elements based upon the passed parameter. If true parameter shows all elements, false hides all elements."
},
{
"code": null,
"e": 2548,
"s": 2501,
"text": "Her... |
Java Program to convert array to String for one dimensional and multi-dimensional arrays | For converting array to 1D and 2D arrays, let us first create a one-dimensional and two-dimensional array −
String str[] = {"p", "q", "r", "s", "t", "u", "v", "w","x", "y", "z"};
doubled [][]= {
{1.2, 1.3, 2.1, 4.1},
{1.5, 2.3},
{2.5, 4.4},
{3.8},
{4.9},
{3.2, 2.1, 3.2, 7.2}
};
Converting array to string for one-dimensional array −
Arrays.toString(str);
Converting array to string for two-dimensional array −
Arrays.deepToString(d);
import java.util.Arrays;
public class Demo {
public static void main(String args[]) {
String str[] = {"p", "q", "r", "s", "t", "u", "v", "w","x", "y", "z"};
doubled [][]= {
{1.2, 1.3, 2.1, 4.1},
{1.5, 2.3},
{2.5, 4.4},
{3.8},
{4.9},
{3.2, 2.1, 3.2, 7.2}
};
System.out.println("One dimensional = "+Arrays.toString(str));
System.out.println("Two dimensional = "+Arrays.deepToString(d));
}
}
One dimensional = [p, q, r, s, t, u, v, w, x, y, z]
Two dimensional = [[1.2, 1.3, 2.1, 4.1], [1.5, 2.3], [2.5, 4.4], [3.8], [4.9], [3.2, 2.1, 3.2, 7.2]] | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "For converting array to 1D and 2D arrays, let us first create a one-dimensional and two-dimensional array −"
},
{
"code": null,
"e": 1241,
"s": 1170,
"text": "String str[] = {\"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\",\"x... |
std::to_string in C++ - GeeksforGeeks | 26 Jul, 2017
Convert numerical value to string
Syntax :
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Parameters :
val - Numerical value.
Return Value :
A string object containing the representation of val as a sequence of characters.
// CPP program to illustrate// std::to_string#include <bits/stdc++.h> // Driver codeint main(){ // Converting float to string std::string str1 = std::to_string(12.10); // Converting integer to string std::string str2 = std::to_string(9999); // Printing the strings std::cout << str1 << '\n'; std::cout << str2 << '\n'; return 0;}
Output:
12.100000
9999
Problem : Find a specific digit in a given integer.Example :
Input : number = 10340, digit = 3
Output : 3 is at position 3
// CPP code to find a digit in a number// using std::tostring#include <bits/stdc++.h> // Driver codeint main(){ // Converting number to string std::string str = std::to_string(9954); // Finding 5 in the number std::cout << "5 is at position " << str.find('5') + 1;}
Output :
5 is at position 3
This article is contributed by Rohit Thapliyal. 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.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Bitwise Operators in C/C++
Virtual Function in C++
Iterators in C++ STL
Constructors in C++
Copy Constructor in C++ | [
{
"code": null,
"e": 24543,
"s": 24515,
"text": "\n26 Jul, 2017"
},
{
"code": null,
"e": 24577,
"s": 24543,
"text": "Convert numerical value to string"
},
{
"code": null,
"e": 24586,
"s": 24577,
"text": "Syntax :"
},
{
"code": null,
"e": 25024,
... |
Maximum Spanning Tree using Prim’s Algorithm - GeeksforGeeks | 10 Nov, 2021
Given undirected weighted graph G, the task is to find the Maximum Spanning Tree of the Graph using Prim’s Algorithm
Prims algorithm is a Greedy algorithm which can be used to find the Minimum Spanning Tree (MST) as well as the Maximum Spanning Tree of a Graph.
Examples:
Input: graph[V][V] = {{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0}}Output:The total weight of the Maximum Spanning tree is 30.Edges Weight3 – 1 84 – 2 70 – 3 63 – 4 9Explanation:Choosing other edges won’t result in maximum spanning tree.
Maximum Spanning Tree:
Given an undirected weighted graph, a maximum spanning tree is a spanning tree having maximum weight. It can be easily computed using Prim’s algorithm. The goal here is to find the spanning tree with the maximum weight out of all possible spanning trees.
Prim’s Algorithm:
Prim’s algorithm is a greedy algorithm, which works on the idea that a spanning tree must have all its vertices connected. The algorithm works by building the tree one vertex at a time, from an arbitrary starting vertex, and adding the most expensive possible connection from the tree to another vertex, which will give us the Maximum Spanning Tree (MST).
Follow the steps below to solve the problem:
Initialize a visited array of boolean datatype, to keep track of vertices visited so far. Initialize all the values with false.
Initialize an array weights[], representing the maximum weight to connect that vertex. Initialize all the values with some minimum value.
Initialize an array parent[], to keep track of the maximum spanning tree.
Assign some large value, as the weight of the first vertex and parent as -1, so that it is picked first and has no parent.
From all the unvisited vertices, pick a vertex v having a maximum weight and mark it as visited.
Update the weights of all the unvisited adjacent vertices of v. To update the weights, iterate through all the unvisited neighbors of v. For every adjacent vertex x, if the weight of the edge between v and x is greater than the previous value of v, update the value of v with that weight.
Below is the implementation of the above algorithm:
C++
Java
Python3
C#
Javascript
// C++ program for the above algorithm
#include <bits/stdc++.h>
using namespace std;
#define V 5
// Function to find index of max-weight
// vertex from set of unvisited vertices
int findMaxVertex(bool visited[], int weights[])
{
// Stores the index of max-weight vertex
// from set of unvisited vertices
int index = -1;
// Stores the maximum weight from
// the set of unvisited vertices
int maxW = INT_MIN;
// Iterate over all possible
// nodes of a graph
for (int i = 0; i < V; i++) {
// If the current node is unvisited
// and weight of current vertex is
// greater than maxW
if (visited[i] == false
&& weights[i] > maxW) {
// Update maxW
maxW = weights[i];
// Update index
index = i;
}
}
return index;
}
// Utility function to find the maximum
// spanning tree of graph
void printMaximumSpanningTree(int graph[V][V],
int parent[])
{
// Stores total weight of
// maximum spanning tree
// of a graph
int MST = 0;
// Iterate over all possible nodes
// of a graph
for (int i = 1; i < V; i++) {
// Update MST
MST += graph[i][parent[i]];
}
cout << "Weight of the maximum Spanning-tree "
<< MST << '\n'
<< '\n';
cout << "Edges \tWeight\n";
// Print the Edges and weight of
// maximum spanning tree of a graph
for (int i = 1; i < V; i++) {
cout << parent[i] << " - " << i << " \t"
<< graph[i][parent[i]] << " \n";
}
}
// Function to find the maximum spanning tree
void maximumSpanningTree(int graph[V][V])
{
// visited[i]:Check if vertex i
// is visited or not
bool visited[V];
// weights[i]: Stores maximum weight of
// graph to connect an edge with i
int weights[V];
// parent[i]: Stores the parent node
// of vertex i
int parent[V];
// Initialize weights as -INFINITE,
// and visited of a node as false
for (int i = 0; i < V; i++) {
visited[i] = false;
weights[i] = INT_MIN;
}
// Include 1st vertex in
// maximum spanning tree
weights[0] = INT_MAX;
parent[0] = -1;
// Search for other (V-1) vertices
// and build a tree
for (int i = 0; i < V - 1; i++) {
// Stores index of max-weight vertex
// from a set of unvisited vertex
int maxVertexIndex
= findMaxVertex(visited, weights);
// Mark that vertex as visited
visited[maxVertexIndex] = true;
// Update adjacent vertices of
// the current visited vertex
for (int j = 0; j < V; j++) {
// If there is an edge between j
// and current visited vertex and
// also j is unvisited vertex
if (graph[j][maxVertexIndex] != 0
&& visited[j] == false) {
// If graph[v][x] is
// greater than weight[v]
if (graph[j][maxVertexIndex] > weights[j]) {
// Update weights[j]
weights[j] = graph[j][maxVertexIndex];
// Update parent[j]
parent[j] = maxVertexIndex;
}
}
}
}
// Print maximum spanning tree
printMaximumSpanningTree(graph, parent);
}
// Driver Code
int main()
{
// Given graph
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
// Function call
maximumSpanningTree(graph);
return 0;
}
// Java program for the above algorithm
import java.io.*;
class GFG
{
public static int V = 5;
// Function to find index of max-weight
// vertex from set of unvisited vertices
static int findMaxVertex(boolean visited[],
int weights[])
{
// Stores the index of max-weight vertex
// from set of unvisited vertices
int index = -1;
// Stores the maximum weight from
// the set of unvisited vertices
int maxW = Integer.MIN_VALUE;
// Iterate over all possible
// nodes of a graph
for (int i = 0; i < V; i++)
{
// If the current node is unvisited
// and weight of current vertex is
// greater than maxW
if (visited[i] == false && weights[i] > maxW)
{
// Update maxW
maxW = weights[i];
// Update index
index = i;
}
}
return index;
}
// Utility function to find the maximum
// spanning tree of graph
static void printMaximumSpanningTree(int graph[][],
int parent[])
{
// Stores total weight of
// maximum spanning tree
// of a graph
int MST = 0;
// Iterate over all possible nodes
// of a graph
for (int i = 1; i < V; i++)
{
// Update MST
MST += graph[i][parent[i]];
}
System.out.println("Weight of the maximum Spanning-tree "
+ MST);
System.out.println();
System.out.println("Edges \tWeight");
// Print the Edges and weight of
// maximum spanning tree of a graph
for (int i = 1; i < V; i++)
{
System.out.println(parent[i] + " - " + i + " \t"
+ graph[i][parent[i]]);
}
}
// Function to find the maximum spanning tree
static void maximumSpanningTree(int[][] graph)
{
// visited[i]:Check if vertex i
// is visited or not
boolean[] visited = new boolean[V];
// weights[i]: Stores maximum weight of
// graph to connect an edge with i
int[] weights = new int[V];
// parent[i]: Stores the parent node
// of vertex i
int[] parent = new int[V];
// Initialize weights as -INFINITE,
// and visited of a node as false
for (int i = 0; i < V; i++) {
visited[i] = false;
weights[i] = Integer.MIN_VALUE;
}
// Include 1st vertex in
// maximum spanning tree
weights[0] = Integer.MAX_VALUE;
parent[0] = -1;
// Search for other (V-1) vertices
// and build a tree
for (int i = 0; i < V - 1; i++) {
// Stores index of max-weight vertex
// from a set of unvisited vertex
int maxVertexIndex
= findMaxVertex(visited, weights);
// Mark that vertex as visited
visited[maxVertexIndex] = true;
// Update adjacent vertices of
// the current visited vertex
for (int j = 0; j < V; j++) {
// If there is an edge between j
// and current visited vertex and
// also j is unvisited vertex
if (graph[j][maxVertexIndex] != 0
&& visited[j] == false) {
// If graph[v][x] is
// greater than weight[v]
if (graph[j][maxVertexIndex]
> weights[j]) {
// Update weights[j]
weights[j]
= graph[j][maxVertexIndex];
// Update parent[j]
parent[j] = maxVertexIndex;
}
}
}
}
// Print maximum spanning tree
printMaximumSpanningTree(graph, parent);
}
// Driver Code
public static void main(String[] args)
{
// Given graph
int[][] graph = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
// Function call
maximumSpanningTree(graph);
}
}
// This code is contributed by Dharanendra L V
# Python program for the above algorithm
import sys
V = 5;
# Function to find index of max-weight
# vertex from set of unvisited vertices
def findMaxVertex(visited, weights):
# Stores the index of max-weight vertex
# from set of unvisited vertices
index = -1;
# Stores the maximum weight from
# the set of unvisited vertices
maxW = -sys.maxsize;
# Iterate over all possible
# Nodes of a graph
for i in range(V):
# If the current Node is unvisited
# and weight of current vertex is
# greater than maxW
if (visited[i] == False and weights[i] > maxW):
# Update maxW
maxW = weights[i];
# Update index
index = i;
return index;
# Utility function to find the maximum
# spanning tree of graph
def printMaximumSpanningTree(graph, parent):
# Stores total weight of
# maximum spanning tree
# of a graph
MST = 0;
# Iterate over all possible Nodes
# of a graph
for i in range(1, V):
# Update MST
MST += graph[i][parent[i]];
print("Weight of the maximum Spanning-tree ", MST);
print();
print("Edges \tWeight");
# Print Edges and weight of
# maximum spanning tree of a graph
for i in range(1, V):
print(parent[i] , " - " , i , " \t" , graph[i][parent[i]]);
# Function to find the maximum spanning tree
def maximumSpanningTree(graph):
# visited[i]:Check if vertex i
# is visited or not
visited = [True]*V;
# weights[i]: Stores maximum weight of
# graph to connect an edge with i
weights = [0]*V;
# parent[i]: Stores the parent Node
# of vertex i
parent = [0]*V;
# Initialize weights as -INFINITE,
# and visited of a Node as False
for i in range(V):
visited[i] = False;
weights[i] = -sys.maxsize;
# Include 1st vertex in
# maximum spanning tree
weights[0] = sys.maxsize;
parent[0] = -1;
# Search for other (V-1) vertices
# and build a tree
for i in range(V - 1):
# Stores index of max-weight vertex
# from a set of unvisited vertex
maxVertexIndex = findMaxVertex(visited, weights);
# Mark that vertex as visited
visited[maxVertexIndex] = True;
# Update adjacent vertices of
# the current visited vertex
for j in range(V):
# If there is an edge between j
# and current visited vertex and
# also j is unvisited vertex
if (graph[j][maxVertexIndex] != 0 and visited[j] == False):
# If graph[v][x] is
# greater than weight[v]
if (graph[j][maxVertexIndex] > weights[j]):
# Update weights[j]
weights[j] = graph[j][maxVertexIndex];
# Update parent[j]
parent[j] = maxVertexIndex;
# Print maximum spanning tree
printMaximumSpanningTree(graph, parent);
# Driver Code
if __name__ == '__main__':
# Given graph
graph = [[0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]];
# Function call
maximumSpanningTree(graph);
# This code is contributed by 29AjayKumar
// C# program for the above algorithm
using System;
class GFG
{
public static int V = 5;
// Function to find index of max-weight
// vertex from set of unvisited vertices
static int findMaxVertex(bool[] visited,
int[] weights)
{
// Stores the index of max-weight vertex
// from set of unvisited vertices
int index = -1;
// Stores the maximum weight from
// the set of unvisited vertices
int maxW = int.MinValue;
// Iterate over all possible
// nodes of a graph
for (int i = 0; i < V; i++)
{
// If the current node is unvisited
// and weight of current vertex is
// greater than maxW
if (visited[i] == false && weights[i] > maxW)
{
// Update maxW
maxW = weights[i];
// Update index
index = i;
}
}
return index;
}
// Utility function to find the maximum
// spanning tree of graph
static void printMaximumSpanningTree(int[, ] graph,
int[] parent)
{
// Stores total weight of
// maximum spanning tree
// of a graph
int MST = 0;
// Iterate over all possible nodes
// of a graph
for (int i = 1; i < V; i++)
{
// Update MST
MST += graph[i, parent[i]];
}
Console.WriteLine(
"Weight of the maximum Spanning-tree " + MST);
Console.WriteLine();
Console.WriteLine("Edges \tWeight");
// Print the Edges and weight of
// maximum spanning tree of a graph
for (int i = 1; i < V; i++) {
Console.WriteLine(parent[i] + " - " + i + " \t"
+ graph[i, parent[i]]);
}
}
// Function to find the maximum spanning tree
static void maximumSpanningTree(int[, ] graph)
{
// visited[i]:Check if vertex i
// is visited or not
bool[] visited = new bool[V];
// weights[i]: Stores maximum weight of
// graph to connect an edge with i
int[] weights = new int[V];
// parent[i]: Stores the parent node
// of vertex i
int[] parent = new int[V];
// Initialize weights as -INFINITE,
// and visited of a node as false
for (int i = 0; i < V; i++) {
visited[i] = false;
weights[i] = int.MinValue;
}
// Include 1st vertex in
// maximum spanning tree
weights[0] = int.MaxValue;
parent[0] = -1;
// Search for other (V-1) vertices
// and build a tree
for (int i = 0; i < V - 1; i++) {
// Stores index of max-weight vertex
// from a set of unvisited vertex
int maxVertexIndex
= findMaxVertex(visited, weights);
// Mark that vertex as visited
visited[maxVertexIndex] = true;
// Update adjacent vertices of
// the current visited vertex
for (int j = 0; j < V; j++) {
// If there is an edge between j
// and current visited vertex and
// also j is unvisited vertex
if (graph[j, maxVertexIndex] != 0
&& visited[j] == false) {
// If graph[v][x] is
// greater than weight[v]
if (graph[j, maxVertexIndex]
> weights[j]) {
// Update weights[j]
weights[j]
= graph[j, maxVertexIndex];
// Update parent[j]
parent[j] = maxVertexIndex;
}
}
}
}
// Print maximum spanning tree
printMaximumSpanningTree(graph, parent);
}
// Driver Code
static public void Main()
{
// Given graph
int[, ] graph = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
// Function call
maximumSpanningTree(graph);
}
}
// This code is contributed by Dharanendra L V
<script>
// Javascript program for the above algorithm
var V = 5;
// Function to find index of max-weight
// vertex from set of unvisited vertices
function findMaxVertex(visited, weights)
{
// Stores the index of max-weight vertex
// from set of unvisited vertices
var index = -1;
// Stores the maximum weight from
// the set of unvisited vertices
var maxW = -1000000000;
// Iterate over all possible
// nodes of a graph
for (var i = 0; i < V; i++) {
// If the current node is unvisited
// and weight of current vertex is
// greater than maxW
if (visited[i] == false
&& weights[i] > maxW) {
// Update maxW
maxW = weights[i];
// Update index
index = i;
}
}
return index;
}
// Utility function to find the maximum
// spanning tree of graph
function printMaximumSpanningTree(graph, parent)
{
// Stores total weight of
// maximum spanning tree
// of a graph
var MST = 0;
// Iterate over all possible nodes
// of a graph
for (var i = 1; i < V; i++) {
// Update MST
MST += graph[i][parent[i]];
}
document.write( "Weight of the maximum Spanning-tree "
+ MST + '<br>'
+ '<br>');
document.write( "Edges \tWeight<br>");
// Print the Edges and weight of
// maximum spanning tree of a graph
for (var i = 1; i < V; i++) {
document.write( parent[i] + " - " + i + " "
+ graph[i][parent[i]] + " <br>");
}
}
// Function to find the maximum spanning tree
function maximumSpanningTree(graph)
{
// visited[i]:Check if vertex i
// is visited or not
var visited = Array(V).fill(false);
// weights[i]: Stores maximum weight of
// graph to connect an edge with i
var weights = Array(V).fill(-1000000000);
// parent[i]: Stores the parent node
// of vertex i
var parent = Array(V).fill(0);
// Include 1st vertex in
// maximum spanning tree
weights[0] = 1000000000;
parent[0] = -1;
// Search for other (V-1) vertices
// and build a tree
for (var i = 0; i < V - 1; i++) {
// Stores index of max-weight vertex
// from a set of unvisited vertex
var maxVertexIndex
= findMaxVertex(visited, weights);
// Mark that vertex as visited
visited[maxVertexIndex] = true;
// Update adjacent vertices of
// the current visited vertex
for (var j = 0; j < V; j++) {
// If there is an edge between j
// and current visited vertex and
// also j is unvisited vertex
if (graph[j][maxVertexIndex] != 0
&& visited[j] == false) {
// If graph[v][x] is
// greater than weight[v]
if (graph[j][maxVertexIndex] > weights[j]) {
// Update weights[j]
weights[j] = graph[j][maxVertexIndex];
// Update parent[j]
parent[j] = maxVertexIndex;
}
}
}
}
// Print maximum spanning tree
printMaximumSpanningTree(graph, parent);
}
// Driver Code
// Given graph
var graph = [ [ 0, 2, 0, 6, 0 ],
[ 2, 0, 3, 8, 5 ],
[ 0, 3, 0, 0, 7 ],
[ 6, 8, 0, 0, 9 ],
[ 0, 5, 7, 9, 0 ] ];
// Function call
maximumSpanningTree(graph);
// This code is contributed by rutvik_56.
</script>
Weight of the maximum Spanning-tree 30
Edges Weight
3 - 1 8
4 - 2 7
0 - 3 6
3 - 4 9
Time Complexity: O(V2) where V is the number of nodes in the graph.Auxiliary Space: O(V2)
dharanendralv23
29AjayKumar
rutvik_56
khushboogoyal499
ankita_saini
Graph Minimum Spanning Tree
Prim's Algorithm.MST
Technical Scripter 2020
Graph
Mathematical
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24777,
"s": 24746,
"text": " \n10 Nov, 2021\n"
},
{
"code": null,
"e": 24894,
"s": 24777,
"text": "Given undirected weighted graph G, the task is to find the Maximum Spanning Tree of the Graph using Prim’s Algorithm"
},
{
"code": null,
"e": 25039,... |
ReactJS UI Ant Design Menu Component - GeeksforGeeks | 01 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Menu Component is used to display a versatile menu for navigation purposes. We can use the following approach in ReactJS to use the Ant Design Menu Component.
Menu Props:
defaultOpenKeys: It is used to denote the array with the keys of the default opened sub-menus.
defaultSelectedKeys: It is used to denote the array with the keys of default selected menu items.
expandIcon: It is used to pass the custom expand icon of the submenu.
forceSubMenuRender: It is used to force the render submenu into DOM before it becomes visible.
inlineCollapsed: It is used to specify the collapsed status when the menu is in an inline mode.
inlineIndent: It is used to denote the indent of inline menu items on each level in pixels.
mode: It is used to denote the type of menu.
multiple: It is used to allow the selection of multiple items.
openKeys: It is used to denote the array with the keys of the currently opened sub-menus.
overflowedIndicator: It is used to pass the customized icon when the menu is collapsed.
selectable: It is used to allow selecting menu items.
selectedKeys: It is used to denote the array with the keys of currently selected menu items.
style: It is used to define the style of the root node.
subMenuCloseDelay: It denotes the delay time in seconds to hide the submenu when the mouse leaves.
subMenuOpenDelay: It denotes the delay time in seconds to show the submenu when the mouse enters.
theme: It is used to define the color theme of the menu.
triggerSubMenuAction: It is a callback function that can trigger submenu open/close.
onClick: It is a callback function that is called when a menu item is clicked.
onDeselect: It is a callback function that is called when a menu item is deselected.
onOpenChange: It is a callback function that is called when sub-menus are opened or closed.
onSelect: It is a callback function that is called when a menu item is selected.
Menu.Item Props:
danger: It is used to display the danger style.
disabled: It is used to indicate whether the menu item is disabled or not.
icon: It is used to pass the icon of the menu item.
key: It is used to denote the unique ID of the menu item.
title: It is used to set the display title for the collapsed item.
Menu.SubMenu Props:
children: It is used to denote the sub-menus or sub-menu items.
disabled: It is used to indicate whether the sub-menu is disabled or not.
icon: It is used to pass the icon of the sub-menu.
key: It is used to denote the unique ID of the sub-menu.
popupClassName: It is used to denote the sub-menu class name.
popupOffset: It is used to denote the sub-menu offset.
title: It is used to denote the title of the sub-menu.
onTitleClick: It is a callback function that is triggered when the sub-menu title is clicked.
Menu.ItemGroup Props:
children: It is used to denote the Sub-menu items.
title: It is used to denote the title of the group.
Menu.Divider: It is used as a divider line in between menu items. This component is only used in vertical popup Menu or Dropdown Menu.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import "antd/dist/antd.css";import { Menu } from 'antd'; const { SubMenu } = Menu; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Menu Component</h4> <Menu defaultOpenKeys={['1']} defaultSelectedKeys={['1']} style={{ width: 300 }} mode="inline" > <SubMenu key="1" title="Settings"> <Menu.Item key="2">Option 1</Menu.Item> <Menu.Item key="3">Option 2</Menu.Item> <SubMenu key="4" title="Sub-Menu"> <Menu.Item key="5">Option 3</Menu.Item> <Menu.Item key="6">Option 4</Menu.Item> </SubMenu> </SubMenu> <SubMenu key="7" title="Profile"> <Menu.Item key="8">Option 5</Menu.Item> <Menu.Item key="9">Option 6</Menu.Item> <Menu.Item key="10">Option 7</Menu.Item> <Menu.Item key="11">Option 8</Menu.Item> </SubMenu> </Menu> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/menu/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
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? | [
{
"code": null,
"e": 33847,
"s": 33819,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 34097,
"s": 33847,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Menu Component is used to display a versatile menu for navigation purpos... |
How to create your first web app using Python, Plotly Dash, and Google Sheets API | by Daniel Barker | Towards Data Science | Update 09/21/2018:The app created in part one of the tutorial below is now available in this Github repository. While stripped down in terms of functionality, combining the code there with the tutorial here should get you up and running with Dash in no time. — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
I’ve written several short tutorials recently on how to create web apps using the awesome “Dash” Python library from the folks at Plotly. The power of the library for rapid prototyping of data science projects (or any project, really) cannot be understated.
However, by default Dash apps only run on your local machine. Obviously, the primary benefit of any web app is the ability to share it with an audience. Fortunately, the Dash library is built on top of the very popular ‘Flask’ library, and Dash apps can be deployed to serve content in the same manner. Rather than configure a server from scratch, we’ll take advantage of the simple deployment process obtained through the use of Heroku. Once we have some sample code up-and-running on Heroku, we’ll then update the app to access data from a Google Docs spreadsheet via the Python API.
Step 1: Create and Setup Virtual Environment
Using your favorite virtual environment, create a new environment to house the app. Using Anaconda, we simply type:
$ conda create --name <your env name> python=3.6
Once the environment is created, activate it within the command prompt (you might not need to prepend “source”, depending on your OS), and then create a folder that we’ll use in subsequent steps to house all the various app files.
$ source activate <your env name>$ mkdir venv$ cd venv
Now, install the dependencies needed for the app.
$ pip install dash$ pip install dash-renderer$ pip install dash-core-components$ pip install dash-html-components$ pip install plotly$ pip install dash-table-experiments $ pip install numpy$ pip install pandas$ pip install gunicorn$ pip install --upgrade google-api-python-client$ pip install numpy$ pip install pandas$ pip install gunicorn
Verify that you are in the ‘venv’ directory created for the project earlier. Initialize an empty git repository here.
$ git init
Step 2: Create file structure and initial app files
A few extra files and folders are required for deploying a web on Heroku compared to simply running it on your local machine. To make sure things work smoothly, we need to create several files according to the following structure:
venv/ app.py .gitignore .Procfile .requirements.txt credentials/ __init__.py Credentials.py
In the ‘venv’ folder created previously, create a new file called “app.py”. We can use the code here (link to original source) for initial testing purposes.
Now, create a ‘credentials’ folder, and within that folder create two files, “__init__.py” and “Credentials.py”. The __init__ file just let’s Python know that we want this folder to be an importable module — we can leave the file itself blank. This second file is where we’ll store our Google API keys for accessing Google Sheet data, but we’ll update those keys later*.
*Important Note: Be sure to update your gitignore file to exclude your credentials folder prior to uploading your code to any public Git repository!
In the ‘venv’ folder, create the .gitignore file (I like to use gitignore.io as a starting template).
# At a minimum, make sure .gitignore file contains these items*.pyc.DS_Store.env
Next, also in the ‘venv’ folder, create a file called “Procfile” with the following contents:
web: gunicorn app:server
Finally, we need to create a listing of our projects dependencies in the ‘requirements.txt’ file. This list is easily generated by simply typing the following command into the prompt:
$ pip freeze > requirements.txt
Step 3: Deploy test app to Heroku
For this step, you will need to have a Heroku account and command line prompt already installed on your machine (see this link for Heroku account setup).
$ heroku create lava-vino # replace "lava-vino" with your-app-name$ git add . $ git commit -m "Initial commit"$ git push heroku master $ heroku ps:scale web=1
Verify the app is visible at https://lava-vino.herokuapp.com/ (or at the equivalent name for your app).
Step 5: Updating app to pull data from Google API and visualize the data
In an earlier tutorial, I explained how to access Google Sheet data using Google’s Python API. In order to visualize the Volcanic Wines dataset mentioned in that tutorial, we’ll need to update our app, as well as provide the appropriate Google API credentials. Slightly modifying the steps described in that tutorial, copy the ‘client_secret.json’ file into the ‘credentials’ folder we created in a previous step. Also, you’ll need to update the ‘Credentials.py’ file with your Mapbox ID token.
Important Note: Be sure to update your gitignore file to exclude your credentials folder prior to uploading your code to any public Git repository!
Next, update the ‘app.py’ file with the code below (be sure to include your own Mapbox ID token, and/or update the Google Sheet name, ID, and data parsing methods to suit your own dataset).
We’re almost ready to deploy the updated app to Heroku, but first, we need to run the app on our local machine in order to generate the Google API credentials file. Go ahead and run the ‘app.py’ file on your local machine; you should get a warning prompting you to visit a link to authenticate your app with your Google account. Click on the link to authenticate — if it’s successful, you should now have a new ‘credentials.json’ file in the credentials folder.
Once the credentials file has been generated, you’re ready to deploy the updated app to Heroku using the following commands:
$ git status # view the changes$ git add . # add all the changes$ git commit -m "Updated app"$ git push heroku master
The moment of truth... navigate to https://lava-vino.herokuapp.com/ (or the URL for your app name, and cross your fingers — success! Our web app is successfully deployed to the world!
As you can see, creating a Dash app and deploying via Heroku is relatively straightforward, and all done without needing to write a single line of HTML, Javascript or CSS. Obviously, there’s a great deal more work to be done on this app — cross-referencing with wine appellation data, visualizing that data, creating a friendly UI, etc. We’ll look at some of these things in future tutorials. I’ll also try to upload a stripped down version of the project in its own Git repository so that it can be readily cloned as a template. In the meantime, hopefully this will get you up and running with your own Dash app! | [
{
"code": null,
"e": 492,
"s": 171,
"text": "Update 09/21/2018:The app created in part one of the tutorial below is now available in this Github repository. While stripped down in terms of functionality, combining the code there with the tutorial here should get you up and running with Dash in no ti... |
PHP | PHP is acronym of Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases.PHP is basically used for developing web based software applications.
PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
Key Points
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time.
PHP has now become a popular scripting language among web developer due to the following reasons −
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
It can encrypt data.
Five important characteristics make PHP's practical nature possible −
Simplicity
Simplicity
Efficiency
Efficiency
Security
Security
Flexibility
Flexibility
Familiarity
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this −
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result −
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is not present in the file sent from the server to your Web browser. All of the PHP present in the Web page is processed and stripped from the page; the only thing returned to the client from the Web server is pure HTML output.
All PHP code must be included inside one of the three special markup tags ate are recognised by the PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
61 Lectures
8 hours
Amit Rana
13 Lectures
2.5 hours
Raghu Pandey
5 Lectures
38 mins
Harshit Srivastava
62 Lectures
3.5 hours
YouAccel
9 Lectures
36 mins
Korey Sheppard
10 Lectures
57 mins
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2699,
"s": 2473,
"text": "PHP is acronym of Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases.PHP is basically used for developing web based software applications."
},
{
"code": null,... |
AngularJS - Ajax | AngularJS provides $http control which works as a service to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner −
function studentController($scope,$https:) {
var url = "data.txt";
$https:.get(url).success( function(response) {
$scope.students = response;
});
}
Here, the file data.txt contains student records. $http service makes an ajax call and sets response to its property students. students model can be used to draw tables in HTML.
[
{
"Name" : "Mahesh Parashar",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}
]
<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "" ng-controller = "studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
var url = "/data.txt";
$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>
To execute this example, you need to deploy testAngularJS.htm and data.txt file to a web server. Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2981,
"s": 2699,
"text": "AngularJS provides $http control which works as a service to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from serv... |
Count no. of characters and words in a string in PL/SQL | We are given a string of any length and the task is to calculate the count of characters and words in a string using PL/SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages.It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL. PL/SQL is one of three key programming languages embedded in the
Oracle Database, along with SQL itself and Java.
In PL/SQL block, we have DECLARE block which is used to declare the variables used in
programming and we have BEGIN block where we write the logic for the given problem,
Input − string str = “Tutorials Point”
Output− count of characters is: 15
Count of words are: 2
Explanation-: In the given string we have a total 2 words so word count is 2 and in those words we have 14 characters plus one is for one space in a given string.
Input − string str = “Honesty is the best policy”
Output − count of characters is: 26
Count of words are: 5
Explanation − In the given string we have a total 5 words so word count is 5 and in those words we have 24 characters plus four is for four spaces in a given string.
Input the string of any length and store it in a variable let’s say, str
Input the string of any length and store it in a variable let’s say, str
Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.
Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.
Traverse the loop starting from i to 0 and till length of a string str
Traverse the loop starting from i to 0 and till length of a string str
Use function substr() that will return the number of substrings in a string that is the number of words in a string
Use function substr() that will return the number of substrings in a string that is the number of words in a string
And, increase the count of characters with every iteration of a loop which is going till the length of a string.
And, increase the count of characters with every iteration of a loop which is going till the length of a string.
Print the count of characters and words in a string.
Print the count of characters and words in a string.
DECLARE
str VARCHAR2(40) := 'Tutorials Point';
nchars NUMBER(4) := 0;
nwords NUMBER(4) := 1;
s CHAR;
BEGIN
FOR i IN 1..Length(str) LOOP
s := Substr(str, i, 1);
nchars:= nchars+ 1;
IF s = ' ' THEN
nwords := nwords + 1;
END IF;
END LOOP;
dbms_output.Put_line('count of characters is:'
||nchars);
dbms_output.Put_line('Count of words are: '
||nwords);
END;
If we run the above code it will generate the following output −
count of characters is: 15
Count of words are: 2 | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "We are given a string of any length and the task is to calculate the count of characters and words in a string using PL/SQL."
},
{
"code": null,
"e": 1485,
"s": 1187,
"text": "PL/SQL is a combination of SQL along with the procedural ... |
Call a Function with a Button or a Key in Tkinter | Let assume that we want to call a function whenever a button or a key is pressed for a particular application. We can bind the function that contains the operation with a button or key using the bind('<button or Key>,' callback_function) method. Here, you can bind any key to the event or function that needs to be called.
In this example, we have created a function that will open a dialog box whenever we click a button.
#Import the required libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("700x350")
#Define a function for opening the Dialog box
def open_prompt():
messagebox.showinfo("Message", "Click Okay to Proceed")
#Create a Label widget
Label(win, text= "Click to Open the MessageBox").pack(pady=15)
#Create a Button for opening a dialog Box
ttk.Button(win, text= "Open", command= open_prompt).pack()
win.mainloop()
Running the above code will display a window containing a label and a button.
Upon clicking the "Open" button", it will call a function to open a dialog box. | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "Let assume that we want to call a function whenever a button or a key is pressed for a particular application. We can bind the function that contains the operation with a button or key using the bind('<button or Key>,' callback_function) method. Here, y... |
SciPy - Basic Functionality | By default, all the NumPy functions have been available through the SciPy namespace. There is no need to import the NumPy functions explicitly, when SciPy is imported. The main object of NumPy is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy, dimensions are called as axes. The number of axes is called as rank.
Now, let us revise the basic functionality of Vectors and Matrices in NumPy. As SciPy is built on top of NumPy arrays, understanding of NumPy basics is necessary. As most parts of linear algebra deals with matrices only.
A Vector can be created in multiple ways. Some of them are described below.
Let us consider the following example.
import numpy as np
list = [1,2,3,4]
arr = np.array(list)
print arr
The output of the above program will be as follows.
[1 2 3 4]
NumPy has built-in functions for creating arrays from scratch. Some of these functions are explained below.
The zeros(shape) function will create an array filled with 0 values with the specified shape. The default dtype is float64. Let us consider the following example.
import numpy as np
print np.zeros((2, 3))
The output of the above program will be as follows.
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
The ones(shape) function will create an array filled with 1 values. It is identical to zeros in all the other respects. Let us consider the following example.
import numpy as np
print np.ones((2, 3))
The output of the above program will be as follows.
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
The arange() function will create arrays with regularly incrementing values. Let us consider the following example.
import numpy as np
print np.arange(7)
The above program will generate the following output.
array([0, 1, 2, 3, 4, 5, 6])
Let us consider the following example.
import numpy as np
arr = np.arange(2, 10, dtype = np.float)
print arr
print "Array Data Type :",arr.dtype
The above program will generate the following output.
[ 2. 3. 4. 5. 6. 7. 8. 9.]
Array Data Type : float64
The linspace() function will create arrays with a specified number of elements, which will be spaced equally between the specified beginning and end values. Let us consider the following example.
import numpy as np
print np.linspace(1., 4., 6)
The above program will generate the following output.
array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])
A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power). Let us consider the following example.
import numpy as np
print np.matrix('1 2; 3 4')
The above program will generate the following output.
matrix([[1, 2],
[3, 4]])
This feature returns the (complex) conjugate transpose of self. Let us consider the following example.
import numpy as np
mat = np.matrix('1 2; 3 4')
print mat.H
The above program will generate the following output.
matrix([[1, 3],
[2, 4]])
This feature returns the transpose of self. Let us consider the following example.
import numpy as np
mat = np.matrix('1 2; 3 4')
mat.T
The above program will generate the following output.
matrix([[1, 3],
[2, 4]])
When we transpose a matrix, we make a new matrix whose rows are the columns of the original. A conjugate transposition, on the other hand, interchanges the row and the column index for each matrix element. The inverse of a matrix is a matrix that, if multiplied with the original matrix, results in an identity matrix.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2310,
"s": 1887,
"text": "By default, all the NumPy functions have been available through the SciPy namespace. There is no need to import the NumPy functions explicitly, when SciPy is imported. The main object of NumPy is the homogeneous multidimensional array. It is a table of ... |
C# | Class and Object - GeeksforGeeks | 23 Feb, 2022
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base classes.
Generally, a class declaration contains only a keyword class, followed by an identifier(name) of the class. But there are some optional attributes that can be used with class declaration according to the application requirement. In general, class declarations can include these components, in order:
Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
Keyword class: A class keyword is used to declare the type class.
Class Identifier: The variable of type class is provided. The identifier(or name of the class) should begin with an initial letter which should be capitalized by convention.
Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon). This is optional.
Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon). A class can implement more than one interface. This is optional.
Body: The class body is surrounded by { } (curly braces).
Constructors in class are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.Example:
// declaring public class
public class Geeks
{
// field variable
public int a, b;
// member function or method
public void display()
{
Console.WriteLine(“Class & Objects in C#”);
}
}
It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of :
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Consider Dog as an object and see the below diagram for its identity, state, and behavior.
Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.Example:
As we declare variables like (type name;). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, the type must be strictly a concrete class name.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.Example:
C#
// C# program to illustrate the// Initialization of an objectusing System; // Class Declarationpublic class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color; } // Property 1 public String GetName() { return name; } // Property 2 public String GetBreed() { return breed; } // Property 3 public int GetAge() { return age; } // Property 4 public String GetColor() { return color; } // Method 1 public String ToString() { return ("Hi my name is " + this.GetName() + ".\nMy breed, age and color are " + this.GetBreed() + ", " + this.GetAge() + ", " + this.GetColor()); } // Main Methodpublic static void Main(String[] args) { // Creating object Dog tuffy = new Dog("tuffy", "papillon", 5, "white"); Console.WriteLine(tuffy.ToString()); }}
Output:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white
Explanation: This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The C# compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, ”papillon”, 5, ”white” as values for those arguments:
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
The result of executing this statement can be illustrated as :
yoyopranavkhandelwal
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
String.Split() Method in C# with Examples
C# | Arrays of Strings
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Abstract Classes
C# | Delegates | [
{
"code": null,
"e": 25304,
"s": 25276,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 25726,
"s": 25304,
"text": "Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototyp... |
How to deal with warning message “Removed X rows containing missing values” for a column of an R data frame while creating a plot? | If we have missing values/NA in our data frame and create a plot using ggplot2 without excluding those missing values then we get the warning “Removed X rows containing missing values”, here X will be the number of rows for the column that contain NA values. But the plot will be correct because it will be calculated by excluding the NA’s. To avoid this error, we just need to pass the subset of the data frame column that do not contains NA values as shown in the below example.
Consider the below data frame with y column having few NA values −
Live Demo
set.seed(112)
x<-sample(0:10,25,replace=TRUE)
y<-sample(c(21:25,NA),25,replace=TRUE) df<-data.frame(x,y)
df
x y
1 4 21
2 10 NA
3 10 23
4 10 22
5 2 NA
6 1 NA
7 0 25
8 8 NA
9 1 22
10 4 23
11 2 21
12 3 23
13 9 25
14 6 25
15 7 21
16 10 24
17 6 NA
18 6 NA
19 8 NA
20 4 24
21 1 23
22 7 21
23 1 21
24 0 22
25 4 NA
Loading ggplot2 package and creating point chart for x and y columns of df −
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
Warning message −
Removed 5 rows containing missing values (geom_point) −
Here, we are getting the warning message for missing values.
Creating the point chart for x and y by excluding the NA values −
ggplot(data=subset(df,!is.na(y)),aes(x,y))+geom_point()
Output of the plot would be same as shown above but the warning message will not be there − | [
{
"code": null,
"e": 1543,
"s": 1062,
"text": "If we have missing values/NA in our data frame and create a plot using ggplot2 without excluding those missing values then we get the warning “Removed X rows containing missing values”, here X will be the number of rows for the column that contain NA va... |
Impala - Order By Clause | The Impala ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Some databases sort the query results in ascending order by default.
Following is the syntax of the ORDER BY clause.
select * from table_name ORDER BY col_name [ASC|DESC] [NULLS FIRST|NULLS LAST]
You can arrange the data in the table in ascending or descending order using the keywords ASC or DESC respectively.
In the same way, if we use NULLS FIRST, all the null values in the table are arranged in the top rows; and if we use NULLS LAST, the rows containing null values will be arranged last.
Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 3 | kaushik | 23 | Kota | 30000 |
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 6 | Komal | 22 | MP | 32000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
+----+----------+-----+-----------+--------+
Fetched 6 row(s) in 0.51s
Following is an example of arranging the data in the customers table, in ascending order of their id’s using the order by clause.
[quickstart.cloudera:21000] > Select * from customers ORDER BY id asc;
On executing, the above query produces the following output.
Query: select * from customers ORDER BY id asc
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 3 | kaushik | 23 | Kota | 30000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 6 | Komal | 22 | MP | 32000 |
+----+----------+-----+-----------+--------+
Fetched 6 row(s) in 0.56s
In the same way, you can arrange the data of customers table in descending order using the order by clause as shown below.
[quickstart.cloudera:21000] > Select * from customers ORDER BY id desc;
On executing, the above query produces the following output.
Query: select * from customers ORDER BY id desc
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 6 | Komal | 22 | MP | 32000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 3 | kaushik | 23 | Kota | 30000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
+----+----------+-----+-----------+--------+
Fetched 6 row(s) in 0.54s
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2473,
"s": 2285,
"text": "The Impala ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Some databases sort the query results in ascending order by default."
},
{
"code": null,
"e": 2521,
"s": 2473,
"te... |
Class getDeclaredFields() method in Java with Examples - GeeksforGeeks | 25 Jan, 2022
The getDeclaredFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are private, public, protected or default and its members, but not the inherited ones. The method returns the fields of this class in the form of array of Field objects. Syntax:
public Field[] getDeclaredFields()
throws SecurityException
Parameter: This method does not accept any parameter.Return Value: This method returns the fields of this class in the form of array of Field objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredFields() method.Example 1:
Java
// Java program to demonstrate getDeclaredFields() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the fields of myClass // using getDeclaredFields() method System.out.println( "DeclaredFields of myClass: " + Arrays.toString( myClass.getDeclaredFields())); }}
Class represented by myClass: class Test
DeclaredFields of myClass: []
Example 2:
Java
// Java program to demonstrate getDeclaredFields() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the fields of myClass // using getDeclaredFields() method System.out.println( "DeclaredFields of myClass: " + Arrays.toString( myClass.getDeclaredFields())); }}
Class represented by myClass: class Main
DeclaredFields of myClass: [public java.lang.Object Main.obj]
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredFields–
saurabh1990aror
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 24290,
"s": 24262,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 24592,
"s": 24290,
"text": "The getDeclaredFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are private, public, protected or defaul... |
Ways to split array into two groups of same XOR value - GeeksforGeeks | 14 Apr, 2021
Given an array A of n integers. The task is to count the number of ways to split given array elements into two disjoint groups, such that XOR of elements of each group is equal.Examples:
Input : A[] = { 1, 2, 3 }
Output : 3
{(1), (2, 3)}, {(2), (1, 3)}, {(3), (1, 2)}
are three ways with equal XOR value of two
groups.
Input : A[] = { 5, 2, 3, 2 }
Output : 0
Let’s denote XOR between all elements in the first group as G1 and XOR between all elements in the second group as G2. Now, the following relation is always correct: G1 ⊕ G2 = A1 ⊕ A2 ⊕ .... ⊕ An. So for G1 = G2, xor between all elements of array A is equal to 0. So, in that case, answer will be (2n – 2)/2 = (2n-1 – 1). In second case, when XOR between all elements isn’t 0, we can not split array. Answer will be 0.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to count number of ways to split// array into two groups such that each group// has equal XOR value#include<bits/stdc++.h>using namespace std; // Return the count number of ways to split// array into two groups such that each group// has equal XOR value.int countgroup(int a[], int n){ int xs = 0; for (int i = 0; i < n; i++) xs = xs ^ a[i]; // We can split only if XOR is 0. Since // XOR of all is 0, we can consider all // subsets as one group. if (xs == 0) return (1 << (n-1)) - 1; return 0;} // Driver Programint main(){ int a[] = { 1, 2, 3 }; int n = sizeof(a)/sizeof(a[0]); cout << countgroup(a, n) << endl; return 0;}
// Java Program to count number of ways// to split array into two groups such// that each group has equal XOR valueimport java.io.*;import java.util.*; class GFG { // Return the count number of ways to split// array into two groups such that each group// has equal XOR value.static int countgroup(int a[], int n) { int xs = 0; for (int i = 0; i < n; i++) xs = xs ^ a[i]; // We can split only if XOR is 0. Since // XOR of all is 0, we can consider all // subsets as one group. if (xs == 0) return (1 << (n - 1)) - 1; return 0;} // Driver programpublic static void main(String args[]) { int a[] = {1, 2, 3}; int n = a.length; System.out.println(countgroup(a, n));}} // This code is contributed by Nikita Tiwari.
# Python3 code to count number of ways# to split array into two groups such# that each group has equal XOR value # Return the count of number of ways# to split array into two groups such# that each group has equal XOR value.def countgroup(a, n): xs = 0 for i in range(n): xs = xs ^ a[i] # We can split only if XOR is 0. # Since XOR of all is 0, we can # consider all subsets as one group. if xs == 0: return (1 << (n-1)) - 1 return 0 # Driver Programa = [1, 2, 3]n = len(a)print(countgroup(a, n)) # This code is contributed by "Sharad_Bhardwaj".
// C# Program to count number of ways// to split array into two groups such// that each group has equal XOR valueusing System; class GFG { // Return the count number of ways to split // array into two groups such that each group // has equal XOR value. static int countgroup(int[] a, int n) { int xs = 0; for (int i = 0; i < n; i++) xs = xs ^ a[i]; // We can split only if XOR is 0. Since // XOR of all is 0, we can consider all // subsets as one group. if (xs == 0) return (1 << (n - 1)) - 1; return 0; } // Driver program public static void Main() { int[] a = { 1, 2, 3 }; int n = a.Length; Console.WriteLine(countgroup(a, n)); }} // This code is contributed by vt_m.
<?php// PHP Program to count number// of ways to split array into// two groups such that each // group has equal XOR value // Return the count number of// ways to split array into// two groups such that each // grouphas equal XOR value.function countgroup($a, $n){ $xs = 0; for ($i = 0; $i < $n; $i++) $xs = $xs ^ $a[$i]; // We can split only if XOR is 0. Since // XOR of all is 0, we can consider all // subsets as one group. if ($xs == 0) return (1 << ($n - 1)) - 1; return 0;} // Driver Code$a = array(1, 2, 3);$n = count($a);echo countgroup($a, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript Program to count number of ways to split // array into two groups such that each group // has equal XOR value // Return the count number of ways to split // array into two groups such that each group // has equal XOR value. function countgroup(a, n) { var xs = 0; for (var i = 0; i < n; i++) xs = xs ^ a[i]; // We can split only if XOR is 0. Since // XOR of all is 0, we can consider all // subsets as one group. if (xs == 0) return (1 << (n - 1)) - 1; } // Driver Program var a = [1, 2, 3]; var n = a.length; document.write(countgroup(a, n) + "<br>"); </script>
Output:
3
vt_m
rdtank
Bitwise-XOR
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 25009,
"s": 24820,
"text": "Given an array A of n integers. The task is to count the number of ways to split given array elements into two disjoint groups, such that XOR of elements of each g... |
Data Observability: Building Data Quality Monitors Using SQL | Towards Data Science | By Ryan Kearns and Barr Moses
In this article series, we walk through how you can create your own data observability monitors from scratch, mapping to five key pillars of data health. Part 1 of this series was adapted from Barr Moses and Ryan Kearns’ O’Reilly training, Managing Data Downtime: Applying Observability to Your Data Pipelines, the industry’s first-ever course on data observability. The associated exercises are available here, and the adapted code shown in this article is available here.
From null values and duplicate rows, to modeling errors and schema changes, data can break for many reasons. Data testing is often our first line of defense against bad data, but what happens if data breaks during its life cycle?
We call this phenomenon data downtime, and it refers to periods of time where data is missing, erroneous, or otherwise inaccurate. Data downtime prompts us to ask questions such as:
Is the data up to date?
Is the data complete?
Are fields within expected ranges?
Is the null rate higher or lower than it should be?
Has the schema changed?
To trigger an alert when data breaks and prevent data downtime, data teams can leverage a tried and true tactic from our friends in software engineering: monitoring and observability.
We define data observability as an organization’s ability to answer these questions and assess the health of their data ecosystem. Reflecting key variables of data health, the five pillars of data observability are:
Freshness: is my data up to date? Are there gaps in time where my data has not been updated?
Distribution: how healthy is my data at the field-level? Is my data within expected ranges?
Volume: is my data intake meeting expected thresholds?
Schema: has the formal structure of my data management system changed?
Lineage: if some of my data is down, what is affected upstream and downstream? How do my data sources depend on one another?
It’s one thing to talk about data observability in this conceptual way, but a complete treatment should pull back the curtain — what does data observability actually look like, under the hood, in the code?
It’s difficult to answer this question entirely, since the details will depend on one’s choice of data warehouse, data lake, BI tools, preferred languages and frameworks, and so on. Even so, addressing these problems using lightweight tools like SQLite and Jupyter could be useful.
In this article, we walk through an example data ecosystem to create our own data quality monitors in SQL and explore what data observability looks like in practice.
Let’s take a look.
This tutorial is based on Exercise 1 of our O’Reilly course, Managing Data Downtime. You’re welcome to try out these exercises on your own using a Jupyter Notebook and SQL. We’ll be going into more detail, including exercises 2, 3 and 4, in future articles.
Our sample data ecosystem uses mock astronomical data about habitable exoplanets. For the purpose of this exercise, I generated the dataset with Python, modeling anomalies off of real incidents I’ve come across in production environments. This dataset is entirely free to use, and the utils folder in the repository contains the code that generated the data, if you’re interested.
I’m using SQLite 3.32.3, which should make the database accessible from either the command prompt or SQL files with minimal setup. The concepts extend to really any query language, and these implementations can be extended to MySQL, Snowflake, and other database environments with minimal changes.
$ sqlite3 EXOPLANETS.dbsqlite> PRAGMA TABLE_INFO(EXOPLANETS);0 | _id | TEXT | 0 | | 01 | distance | REAL | 0 | | 02 | g | REAL | 0 | | 03 | orbital_period | REAL | 0 | | 04 | avg_temp | REAL | 0 | | 05 | date_added | TEXT | 0 | | 0
A database entry in EXOPLANETS contains the following info:
0._id: A UUID corresponding to the planet.1. distance: Distance from Earth, in lightyears.2. g: Surface gravity as a multiple of g, the gravitational force constant.3. orbital_period: Length of a single orbital cycle in days.4. avg_temp: Average surface temperature in degrees Kelvin.5. date_added: The date our system discovered the planet and added it automatically to our databases.
Note that one or more of distance, g, orbital_period, and avg_temp may be NULL for a given planet as a result of missing or erroneous data.
sqlite> SELECT * FROM EXOPLANETS LIMIT 5;
Note that this exercise is retroactive — we’re looking at historical data. In a production data environment, data observability is real time and applied at each stage of the data life cycle, and thus will involve a slightly different implementation than what is done here.
For the purpose of this exercise, we’ll be building data observability algorithms for freshness and distribution, but in future articles, we’ll address the rest of our five pillars — and more.
The first pillar of data observability we monitor for is freshness, which can give us a strong indicator of when critical data assets were last updated. If a report that is regularly updated on the hour suddenly looks very stale, this type of anomaly should give us a strong indication that something is off.
First, note the DATE_ADDED column. SQL doesn’t store metadata on when individual records are added. So, to visualize freshness in this retroactive setting, we need to track that information ourselves.
Grouping by the DATE_ADDED column can give us insight into how EXOPLANETS updates daily. For example, we can query for the number of new IDs added per day:
You can run this yourself with $ sqlite3 EXOPLANETS.db < queries/freshness/rows-added.sql in the repository. We get the following data back:
Based on this graphical representation of our dataset, it looks like EXOPLANETS consistently updates with around 100 new entries each day, though there are gaps where no data comes in for multiple days.
Recall that with freshness, we want to ask the question “is my data up to date?” — thus, knowing about those gaps in table updates is essential to understanding the reliability of our data.
This query operationalizes freshness by introducing a metric for DAYS_SINCE_LAST_UPDATE. (Note: since this tutorial uses SQLite3, the SQL syntax for calculating time differences will be different in MySQL, Snowflake, and other environments).
The resulting table says “on date X, the most recent data in EXOPLANETS was Y days old.” This is information not explicitly available from the DATE_ADDED column in the table — but applying data observability gives us the tools to uncover it.
Now, we have the data we need to detect freshness anomalies. All that’s left to do is to set a threshold parameter for Y — how many days old is too many? A parameter turns a query into a detector, since it decides what counts as anomalous (read: worth alerting) and what doesn’t. (More on setting threshold parameters in a later article!).
The data returned to us represents dates where freshness incidents occurred.
On 2020–05–14, the most recent data in the table was 8 days old! Such an outage may represent a breakage in our data pipeline, and would be good to know about if we’re using this data for anything worthwhile (and if we’re using this in a production environment, chances are, we are).
Note in particular the last line of the query: DAYS_SINCE_LAST_UPDATE > 1;.
Here, 1 is a model parameter — there’s nothing “correct” about this number, though changing it will impact what dates we consider to be incidents. The smaller the number, the more genuine anomalies we’ll catch (high recall), but chances are, several of these “anomalies” will not reflect real outages. The larger the number, the greater the likelihood all anomalies we catch will reflect true anomalies (high precision), but it’s possible we may miss some.
For the purpose of this example, we could change 1 to 7 and thus only catch the two worst outages on 2020–02–08 and 2020–05–14. Any choice here will reflect the particular use case and objectives, and is an important balance to strike that comes up again and again when applying data observability at scale to production environments.
Below, we leverage the same freshness detector, but with DAYS_SINCE_LAST_UPDATE > 3; serving as the threshold. Two of the smaller outages now go undetected.
Note the two undetected outages — these must be fewer than 3-day gaps.
Now we visualize the same freshness detector, but with DAYS_SINCE_LAST_UPDATE > 7; now serving as the threshold. All but the two largest outages now go undetected.
Just like planets, optimal model parameters sit in a “Goldilocks Zone” or “sweet spot” between values considered too low and too high. These data observability concepts (and more!) will be discussed in a later article.
Next, we want to assess the field-level, distributional health of our data. Distribution tells us all of the expected values of our data, as well as how frequently each value occurs. One of the simplest questions is, “how often is my data NULL”? In many cases, some level of incomplete data is acceptable — but if a 10% null rate turns into 90%, we’ll want to know.
This query returns a lot of data! What’s going on?
The general formula CAST(SUM(CASE WHEN SOME_METRIC IS NULL THEN 1 ELSE 0 END) AS FLOAT) / COUNT(*), when grouped by the DATE_ADDED column, is telling us the rate of NULL values for SOME_METRIC in the daily batches of new data in EXOPLANETS. It’s hard to get a sense by looking at the raw output, but a visual can help illuminate this anomaly:
The visuals make it clear that there are null rate “spike” events we should be detecting. Let’s focus on just the last metric, AVG_TEMP, for now. We can detect null spikes most basically with a simple threshold:
As detection algorithms go, this approach is something of a blunt instrument. Sometimes, patterns in our data will be simple enough for a threshold like this to do the trick. In other cases, though, data will be noisy or have other complications, like seasonality, requiring us to change our approach.
For example, detecting 2020–06–02, 2020–06–03, and 2020–06–04 seems redundant. We can filter out dates that occur immediately after other alerts:
Note that in both of these queries, the key parameter is 0.9. We’re effectively saying: “any null rate higher than 90% is a problem, and I need to know about it.”
In this instance, we can (and should) be a bit more intelligent by applying the concept of rolling average with a more intelligent parameter:
One clarification: notice that on line 28, we filter using the quantity AVG_TEMP_NULL_RATE — TWO_WEEK_ROLLING_AVG. In other instances, we might want to take the ABS() of this error quantity, but not here — the reason being that a NULL rate “spike” is much more alarming if it represents an increase from the previous average. It may not be worthwhile to monitor whenever NULLs abruptly decrease in frequency, while the value in detecting a NULL rate increase is clear.
There are, of course, increasingly sophisticated metrics for anomaly detection like Z-scores and autoregressive modeling that are out of scope here. This tutorial just provides the basic scaffolding for field-health monitoring in SQL; I hope it can give you ideas for your own data!
This brief tutorial intends to show that “data observability” is not as mystical as the name suggests, and with a holistic approach to understanding your data health, you can ensure high data trust and reliability at every stage of your pipeline.
In fact, the core principles of data observability are achievable using plain SQL “detectors,” provided some key information like record timestamps and historical table metadata are kept. It’s also worth noting that key ML-powered parameter tuning is mandatory for end-to-end data observability systems that grow with your production environment.
Stay tuned for future articles in this series that focus on monitoring anomalies in distribution and schema, the role of lineage and metadata in data observability, and how to monitor these pillars together at scale to achieve more reliable data.
Until then — here’s wishing you no data downtime!
Interested in learning more about how to apply data observability at scale? Reach out to Ryan, Barr , and the rest of the Monte Carlo team. | [
{
"code": null,
"e": 77,
"s": 47,
"text": "By Ryan Kearns and Barr Moses"
},
{
"code": null,
"e": 551,
"s": 77,
"text": "In this article series, we walk through how you can create your own data observability monitors from scratch, mapping to five key pillars of data health. Part ... |
D3.js - Selections | Selections is one of the core concepts in D3.js. It is based on CSS selectors. It allows us to select one or more elements in a webpage. In addition, it allows us to modify, append, or remove elements in a relation to the pre-defined dataset. In this chapter, we will see how to use selections to create data visualizations.
D3.js helps to select elements from the HTML page using the following two methods −
select() − Selects only one DOM element by matching the given CSS selector. If there are more than one elements for the given CSS selector, it selects the first one only.
select() − Selects only one DOM element by matching the given CSS selector. If there are more than one elements for the given CSS selector, it selects the first one only.
selectAll() − Selects all DOM elements by matching the given CSS selector. If you are familiar with selecting elements with jQuery, D3.js selectors are almost the same.
selectAll() − Selects all DOM elements by matching the given CSS selector. If you are familiar with selecting elements with jQuery, D3.js selectors are almost the same.
Let us go through each of the methods in detail.
The select() method selects the HTML element based on CSS Selectors. In CSS Selectors, you can define and access HTML-elements in the following three ways −
Tag of a HTML element (e.g. div, h1, p, span, etc.,)
Class name of a HTML element
ID of a HTML element
Let us see it in action with examples.
You can select HTML elements using its TAG. The following syntax is used to select the “div” tag elements,
d3.select(“div”)
Example − Create a page “select_by_tag.html” and add the following changes,
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div>
Hello World!
</div>
<script>
d3.select("div").text();
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen −
HTML elements styled using CSS classes can be selected by using the following syntax.
d3.select(“.<class name>”)
Create a webpage “select_by_class.html” and add the following changes −
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
ad3.select(".myclass").text();
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen −
Every element in a HTML page should have a unique ID. We can use this unique ID of an element to access it using the select() method as specified below.
d3.select(“#<id of an element>”)
Create a webpage “select_by_id.html” and add the following changes.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id = "hello">
Hello World!
</div>
<script>
d3.select("#hello").text();
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen.
The D3.js selection provides the append() and the text() methods to append new elements into the existing HTML documents. This section explains about adding DOM elements in detail.
The append() method appends a new element as the last child of the element in the current selection. This method can also modify the style of the elements, their attributes, properties, HTML and text content.
Create a webpage “select_and_append.html” and add the following changes −
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select("div.myclass").append("span");
</script>
</body>
</html>
Requesting the webpage through browser, you could see the following output on the screen,
Here, the append() method adds a new tag span inside the div tag as shown below −
<div class = "myclass">
Hello World!<span></span>
</div>
The text() method is used to set the content of the selected / appended elements. Let us change the above example and add the text() method as shown below.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select("div.myclass").append("span").text("from D3.js");
</script>
</body>
</html>
Now refresh the webpage and you will see the following response.
Here, the above script performs a chaining operation. D3.js smartly employs a technique called the chain syntax, which you may recognize from jQuery. By chaining methods together with periods, you can perform several actions in a single line of code. It is fast and easy. The same script can also access without chain syntax as shown below.
var body = d3.select("div.myclass");
var span = body.append("span");
span.text("from D3.js");
D3.js provides various methods, html(), attr() and style() to modify the content and style of the selected elements. Let us see how to use modify methods in this chapter.
The html() method is used to set the html content of the selected / appended elements.
Create a webpage “select_and_add_html.html” and add the following code.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select(".myclass").html("Hello World! <span>from D3.js</span>");
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen.
The attr() method is used to add or update the attribute of the selected elements. Create a webpage “select_and_modify.html” and add the following code.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select(".myclass").attr("style", "color: red");
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen.
The style() method is used to set the style property of the selected elements. Create a webpage “select_and_style.html” and add the following code.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select(".myclass").style("color", "red");
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen.
The classed() method is exclusively used to set the “class” attribute of an HTML element. Since, a single HTML element can have multiple classes; we need to be careful while assigning a class to an HTML element. This method knows how to handle one or many classes on an element, and it will be performant.
Add class − To add a class, the second parameter of the classed method must be set to true. It is defined below −
Add class − To add a class, the second parameter of the classed method must be set to true. It is defined below −
d3.select(".myclass").classed("myanotherclass", true);
Remove class − To remove a class, the second parameter of the classed method must be set to false. It is defined below −
Remove class − To remove a class, the second parameter of the classed method must be set to false. It is defined below −
d3.select(".myclass").classed("myanotherclass", false);
Check class − To check for the existence of a class, just leave off the second parameter and pass the class name you are querying. This will return true, if it exists, false, if it does not.
Check class − To check for the existence of a class, just leave off the second parameter and pass the class name you are querying. This will return true, if it exists, false, if it does not.
d3.select(".myclass").classed("myanotherclass");
This will return true, if any element in the selection has the class. Use d3.select for single element selection.
Toggle class − To flip a class to the opposite state – remove it if it exists already, add it if it does not yet exist – you can do one of the following.
For a single element, the code might look as shown below −
Toggle class − To flip a class to the opposite state – remove it if it exists already, add it if it does not yet exist – you can do one of the following.
For a single element, the code might look as shown below −
var element = d3.select(".myclass")
element.classed("myanotherclass", !oneBar.classed("myanotherclass"));
The selectAll() method is used to select multiple elements in the HTML document. The select method selects the first element, but the selectAll method selects all the elements that match the specific selector string. In case the selection matches none, then it returns an empty selection. We can chain all the appending modifying methods, append(), html(), text(), attr(), style(), classed(), etc., in the selectAll() method as well. In this case, the methods will affect all the matching elements. Let us understand by creating a new webpage “select_multiple.html” and add the following script −
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h2 class = "myclass">Message</h2>
<div class = "myclass">
Hello World!
</div>
<script>
d3.selectAll(".myclass").attr("style", "color: red");
</script>
</body>
</html>
By requesting the webpage through the browser, you will see the following output on the screen.
Here, the attr() method applies to both div and h2 tag and the color of the text in both tags changes to Red.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2455,
"s": 2130,
"text": "Selections is one of the core concepts in D3.js. It is based on CSS selectors. It allows us to select one or more elements in a webpage. In addition, it allows us to modify, append, or remove elements in a relation to the pre-defined dataset. In this ch... |
Find instances at end of time frame after auto scaling - GeeksforGeeks | 06 Oct, 2021
Given an integer, instances, and an array, arr[] of size N representing the average utilization percentage of the computing system at each second, the task is to find the number of instances at the end of the time frame such that the computing system auto-scales the number of instances according to the following rules:
Average utilization < 25%: Reduce the number of instances by half if the number of instances is greater than 1.
25% ≤ Average utilization ≤ 60%: Take no action.
Average utilization > 60%: Double the number of instances if the doubled value does not exceed 2* 108.
Once an action of adding or reducing the number of instances is performed, the system will stop monitoring for 10 seconds. During that time, the number of instances does not change.
Examples:
Input: instances = 2, arr[] = {25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80}Output: 2Explanation:At second 1, arr[0] = 25 ≤ 25, so take no action.At second 2, arr[1] = 23 < 25, so an action is instantiated to halve the number of instances to ceil(2/2) = 1. The system will stop checking for 10 seconds, so from arr[2] through arr[11] no actions will be taken.At second 13, arr[12] = 76 > 60, so the number of instances is doubled from 1 to 2.
There are no more readings to consider and 2 is the final value.
Input: instances = 5, arr = {30, 5, 4, 8, 19, 89}Output: 3Explanation:At second 1, 25 ≤ arr[0] = 30 ≤ 60, so take no action.At second 2, arr[1] = 5 < 25, so an action is instantiated to halve the number of instances to ceil(5/2) = 3.The system will stop checking for 10 seconds, so from arr[2] through arr[5] no actions will be taken.
There are no more readings to consider and 3 is the final answer.
Approach: The given problem can be solved by traversing the given array arr[] and if the current element is less than 25 then divide the number of instances by 2 if the number of instances is greater than 1. Otherwise, if the current value is greater than 60 multiply the number of instances by 2 if the number of instances is not greater than 108, after performing either of the two operations increment the current index by 10. Follow the steps to solve the problem:
Traverse the array, arr[] using the variable i and perform the following steps:If arr[i] is less than 25 and instances is greater than 1, divide the instances by 2 and increment i by 10.If arr[i] is greater than 60 and instances is less than or equal to 108, multiply instances by 2 and increment i by 10.Increment the index i by 1.
If arr[i] is less than 25 and instances is greater than 1, divide the instances by 2 and increment i by 10.
If arr[i] is greater than 60 and instances is less than or equal to 108, multiply instances by 2 and increment i by 10.
Increment the index i by 1.
After completing the above steps, print the number of instances as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number of// instances after compintionvoid finalInstances(int instances, int arr[], int N){ int i = 0; // Traverse the array, arr[] while (i < N) { // If current element is less // than 25 if (arr[i] < 25 && instances > 1) { // Divide instances by 2 and take ceil value double temp = (instances / 2.0); instances = (int)(ceil(temp)); i = i + 10; } // If the current element is // greater than 60 else if (arr[i] > 60 && instances <= (2*pow(10, 8))) { // Double the instances instances = instances * 2; i = i + 10; } i = i + 1; } // Print the instances at the end // of the traversal cout << instances;} // Driver Codeint main(){ int instances = 2; int arr[] = { 25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call finalInstances(instances, arr, N);} // This code is contributed by splevel62
// Java program for above approachclass GFG{ // Function to find the number of// instances after compintionpublic static void finalInstances(int instances, int[] arr){ int i = 0; // Traverse the array, arr[] while (i < arr.length) { // If current element is less // than 25 if (arr[i] < 25 && instances > 1) { // Divide instances by 2 instances = (instances / 2); i = i + 10; } // If the current element is // greater than 60 else if (arr[i] > 60 && instances <= Math.pow(10, 8)) { // Double the instances instances = instances * 2; i = i + 10; } i = i + 1; } // Print the instances at the end // of the traversal System.out.println(instances);} // Driver Codepublic static void main(String args[]){ int instances = 2; int[] arr = { 25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80 }; // Function Call finalInstances(instances, arr);}} // This code is contributed by _saurabh_jaiswal
# Python program for the above approachfrom math import ceil # Function to find the number of# instances after completiondef finalInstances(instances, arr): i = 0 # Traverse the array, arr[] while i < len(arr): # If current element is less # than 25 if arr[i] < 25 and instances > 1: # Divide instances by 2 instances = ceil(instances / 2) i += 10 # If the current element is # greater than 60 elif arr[i] > 60 and instances <= 10**8: # Double the instances instances *= 2 i += 10 i += 1 # Print the instances at the end # of the traversal print(instances) # Driver Codeinstances = 2 arr = [25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80] # Function CallfinalInstances(instances, arr)
// C# program for above approachusing System; class GFG{ // Function to find the number of// instances after compintionstatic void finalInstances(int instances, int[] arr){ int i = 0; // Traverse the array, arr[] while (i < arr.Length) { // If current element is less // than 25 if (arr[i] < 25 && instances > 1) { // Divide instances by 2 instances = (instances / 2); i = i + 10; } // If the current element is // greater than 60 else if (arr[i] > 60 && instances <= Math.Pow(10, 8)) { // Double the instances instances = instances * 2; i = i + 10; } i = i + 1; } // Print the instances at the end // of the traversal Console.Write(instances); } // Driver Codestatic void Main(){ int instances = 2; int[] arr = {25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80}; // Function Call finalInstances(instances, arr);}} // This code is contributed by sanjoy_62.
<script> // JavaScript Program for the above approach // Function to find the number of // instances after completion function finalInstances(instances, arr) { let i = 0; // Traverse the array, arr[] while (i < arr.length) { // If current element is less // than 25 if (arr[i] < 25 && instances > 1) { // Divide instances by 2 instances = Math.ceil(instances / 2); i = i + 10; } // If the current element is // greater than 60 else if (arr[i] > 60 && instances <= Math.pow(10, 8)) { // Double the instances instances = instances * 2; i = i + 10; } i = i + 1; } // Print the instances at the end // of the traversal document.write(instances); } // Driver Code let instances = 2; let arr = [25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 80]; // Function Call finalInstances(instances, arr); // This code is contributed by Potta Lokesh </script>
2
Time Complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
sanjoy_62
_saurabh_jaiswal
splevel62
mishrapriyank17
Amazon
interview-preparation
Arrays
Mathematical
Amazon
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 25155,
"s": 25127,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 25477,
"s": 25155,
"text": "Given an integer, instances, and an array, arr[] of size N representing the average utilization percentage of the computing system at each second, the task is to f... |
COBOL Mock Test | This section presents you various set of Mock Tests related to COBOL Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself.
Q 1 - Which data type is not available in COBOL?
A - Alphabetic (A)
B - Long (L)
C - Alphanumeric (X)
D - Numeric (9)
Long data type is not available in COBOL. COBOL supports three data types Alphabetic, Numeric & Alphanumeric.
Q 2 - What does COBOL stand for?
A - Common Business Oriented Language
B - Common Business Object Language
C - Common Oriented Business Language
D - Common Object Business Language
COBOL stands for COmmon Business Oriented Language which was developed to automate the business process.
Q 3 - Which is the mandatory division in COBOL program?
A - PROCEDURE DIVISION.
B - IDENTIFICATION DIVISION
C - DATA DIVISION
D - ENVIRONMENT DIVISION
Identification division contains entries that is used to identify the program. This is the the first division and only mandatory division.
Q 4 - How is sign stored in a COMP-3 field?
A - First Bit
B - Last Bit
C - First Nibble
D - Last Nibble
In COMP-3 field, sign is stored in last nibble.
Q 5 - What will happen if you code GO BACK instead of STOP RUN in a stand alone COBOL program?
A - Program will give run time error.
B - Program will go in infinite loop.
C - Program will execute normally.
D - Program will throw compilation error.
A Stop run ends the unit of work and returns control to the operating system whereas GOBACK returns control to calling program. So if we code GO BACK instead of Stop Run, it will go in infinite loop.
Q 6 - Which of the following file opening mode is invalid in COBOL?
A - APPEND
B - INPUT
C - OUTPUT
D - EXTEND
Valid file opening modes in COBOL are INPUT, OUTPUT, I-O, and EXTEND. APPEND file mode is not available in COBOL.
Q 7 - What is the maximum size of a numeric field we can define in COBOL?
A - 9(20)
B - 9(18)
C - 9(31)
D - 9(10)
COBOL applications use 31 digit numeric fields. However, compiler only supports a maximum of 18 digits. So we use a maximum of 18 digits.
Q 8 - What is the mode in which you will OPEN a file for writing?
A - OUTPUT
B - EXTEND
C - Either OUTPUT or EXTEND
D - INPUT-OUTPUT
To write into a file, the file has to be opened in either OUTPUT or EXTEND mode.
Q 9 - What is 77 level used for?
A - Renames
B - Redefine
C - Group Item
D - Elementary Level
77 level is an elementary level item which cannot be subdivided.
Q 10 - Where does AREA B in COBOL start from?
A - 01 to 07 columns
B - 12 to 72 columns
C - 08 to 11 columns
D - 73 to 80 columns
All COBOL statements must begin in area B which starts from 12 to 72 columns
Q 11 - Where does the FILE-CONTROL paragraph appear?
A - Procedure Division
B - Environment Division
C - Identification Division
D - Data Division
FILE-CONTROL paragraph appears in the Input-Ouput Section in the Environment Division which provides information of external data sets used in the program.
Q 12 - Can I redefine an X(10) field with a field of X(20)?
A - No
B - Yes
Yes we can define a X(10) to X(20) as Redefines causes both fields to start at the same location, but it is not a good coding practice.
Q 13 - What is the length of PIC 9.999?
A - 4
B - 6
C - 5
D - 3
Length of PIC 9.999 is 5 as '.' takes 1 byte. So total 1 byte for '.' and 4 bytes for 9.
Q 14 - How many times following loop will execute?
MOVE 5 TO X.
PERFORM X TIMES.
MOVE 10 TO X.
END-PERFORM.
A - 11
B - 5
C - 10
D - 15
PERFORM loop will execute for 5 times. As it reads the first statement PERFORM 5 times. It replaces X with the value 5.
You can try same code using Try it option available below:
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 X PIC 99.
PROCEDURE DIVISION.
MOVE 5 TO X.
PERFORM X TIMES
MOVE 10 TO X
DISPLAY 'COUNT'
END-PERFORM.
STOP RUN.
Q 15 - Which cobol verb is used for updating a file?
A - READ
B - WRITE
C - UPDATE
D - REWRITE
Rewrite verb is used to update the records. File should be opened in I-O mode for rewrite operations. It can be used only after a successful Read operation. Rewrite verb overwrites the last record read.
Q 16 - Under which section we should make an entry in the program for a SORT file?
A - FD
B - SD
C - MD
D - None of these
For sorting a file, we should make an SD entry in File Section.
Q 17 - How you will declare a Half Word Binary in program?
A - S9(8) COMP
B - S9(4) COMP
C - 9(8) COMP
D - 9(4) COMP
S9(4) COMP is used to declare a Half Word Binary.
Q 18 - If 436 value is moved to a PP999 PIC clause, then what is edited value taken?
A - .00436
B - 00436
C - 436
D - 43600
P is assumed decimal scaling position which is used to specify the location of an assumed decimal point when the point is not within the number that appears in the data item. .PIC PP999 means that numeric data item is of 3 characters and there are 5 positions after the decimal point.
Q 19 - Where can we specify OCCURS clause?
A - Elementary Item
B - Group Item
C - Both A & B
D - None of these
In array declaration, we can specify occurs clause on Elementary item as well as on Group item also.
Q 20 - Which utility is used for compiling COBOL program?
A - IKJEFT01
B - IGYCRCTL
C - IGYCTCRL
D - None of these
IGCRCTL utility is used to compile a COBOL program.
Q 21 - How many bytes does a S9(7) SIGN TRAILING SEPARATE field occupy?
A - 7 bytes
B - 8 bytes
C - 4 bytes
D - 10 bytes
9(7) will take 7 bytes and 1 byte for SIGN TRAILING SEPARATE, so total 8 bytes it will take.
Q 22 - What does SEARCH ALL do?
A - Linear search
B - Binary search
C - Sequential search
D - None of these
Search All is a binary search method, which is used to find elements inside the table.
Q 23 - In which division, Linkage Section comes?
A - Identification Division
B - Environment Division
C - Data Division
D - Procedure Division
Linkage section comes under data division which is used in called program.
Q 24 - In which division, Input-Output section?
A - Identification Division
B - Environment Division
C - Data Division
D - Procedure Division
Input-Output section comes under Environment division which provides information about the files to be used in the program.
Q 25 - Which of the following statement will give you ‘Tutorials’ in TutorialsPoint string?
A - TutorialsPoint(1:9)
B - TutorialsPoint(9)
C - TutorialsPoint(9:1)
D - TutorialsPoint(9:9)
In STRING(A,B), A is the staring position and B id the number of digits to select.
12 Lectures
2.5 hours
Nishant Malik
33 Lectures
3.5 hours
Craig Kenneth Kaercher
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2308,
"s": 2022,
"text": "This section presents you various set of Mock Tests related to COBOL Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the... |
Method Overloading based on the order of the arguments in Java | In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same. One way to make sure that the parameter list is different is to change the order of the arguments in the methods.
A program that demonstrates this is given as follows −
Live Demo
class PrintValues {
public void print(int val1, char val2) {
System.out.println("\nThe int value is: " + val1);
System.out.println("The char value is: " + val2);
}
public void print(char val1, int val2) {
System.out.println("\nThe char value is: " + val1);
System.out.println("The int value is: " + val2);
}
}
public class Demo {
public static void main(String[] args) {
PrintValues obj = new PrintValues();
obj.print(15, 'A');
obj.print('P', 4);
}
}
The int value is: 15
The char value is: A
The char value is: P
The int value is: 4
Now let us understand the above program.
The PrintValues class is created with two methods print() in the implementation of method overloading. The first of these takes 2 parameters of type int and type char respectively and the other takes 2 parameters of type char and type int respectively. A code snippet which demonstrates this is as follows −
class PrintValues {
public void print(int val1, char val2) {
System.out.println("\nThe int value is: " + val1);
System.out.println("The char value is: " + val2);
}
public void print(char val1, int val2) {
System.out.println("\nThe char value is: " + val1);
System.out.println("The int value is: " + val2);
}
}
In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters (15, ’A’) and (‘P’, 4) respectively. A code snippet which demonstrates this is as follows:
public class Demo {
public static void main(String[] args) {
PrintValues obj = new PrintValues();
obj.print(15, 'A');
obj.print('P', 4);
}
} | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same. One way to make sure that the parameter list is different is to change the order of the arguments in the methods.... |
Program to check whether 4 points in a 3-D plane are Coplanar - GeeksforGeeks | 05 Nov, 2021
Given 4 points (x1, y1, z1), (x2, y2, z2), (x3, y3, z3), (x4, y4, z4). The task is to write a program to check whether these 4 points are coplanar or not.Note: 4 points in a 3-D plane are said to be coplanar if they lies in the same plane.
Examples:
Input:
x1 = 3, y1 = 2, z1 = -5
x2 = -1, y2 = 4, z2 = -3
x3 = -3, y3 = 8, z3 = -5
x4 = -3, y4 = 2, z4 = 1
Output: Coplanar
Input:
x1 = 0, y1 = -1, z1 = -1
x2 = 4, y2 = 5, z2 = 1
x3 = 3, y3 = 9, z3 = 4
x4 = -4, y4 = 4, z4 = 3
Output: Not Coplanar
Approach:
To check whether 4 points are coplanar or not, first of all, find the equation of the plane passing through any three of the given points. Approach to find equation of a plane passing through 3 points.Then, check whether the 4th point satisfies the equation obtained in step 1. That is, putting the value of 4th point in the equation obtained. If it satisfies the equation then the 4 points are Coplanar otherwise not.
To check whether 4 points are coplanar or not, first of all, find the equation of the plane passing through any three of the given points. Approach to find equation of a plane passing through 3 points.
Then, check whether the 4th point satisfies the equation obtained in step 1. That is, putting the value of 4th point in the equation obtained. If it satisfies the equation then the 4 points are Coplanar otherwise not.
Below is the implementation of the above idea:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if 4 points// in a 3-D plane are Coplanar #include<bits/stdc++.h>using namespace std ; // Function to find equation of plane.void equation_plane(int x1,int y1,int z1,int x2,int y2,int z2, int x3, int y3, int z3, int x, int y, int z) { int a1 = x2 - x1 ; int b1 = y2 - y1 ; int c1 = z2 - z1 ; int a2 = x3 - x1 ; int b2 = y3 - y1 ; int c2 = z3 - z1 ; int a = b1 * c2 - b2 * c1 ; int b = a2 * c1 - a1 * c2 ; int c = a1 * b2 - b1 * a2 ; int d = (- a * x1 - b * y1 - c * z1) ; // equation of plane is: a*x + b*y + c*z = 0 # // checking if the 4th point satisfies // the above equation if(a * x + b * y + c * z + d == 0) cout << "Coplanar" << endl; else cout << "Not Coplanar" << endl; } // Driver Codeint main(){ int x1 = 3 ;int y1 = 2 ;int z1 = -5 ;int x2 = -1 ;int y2 = 4 ;int z2 = -3 ;int x3 = -3 ;int y3 = 8 ;int z3 = -5 ;int x4 = -3 ;int y4 = 2 ;int z4 = 1 ; // function callingequation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) ; return 0; // This code is contributed by ANKITRAI1}
//Java program to check if 4 points//in a 3-D plane are Coplanar public class GFG { //Function to find equation of plane. static void equation_plane(int x1,int y1,int z1,int x2,int y2,int z2, int x3, int y3, int z3, int x, int y, int z) { int a1 = x2 - x1 ; int b1 = y2 - y1 ; int c1 = z2 - z1 ; int a2 = x3 - x1 ; int b2 = y3 - y1 ; int c2 = z3 - z1 ; int a = b1 * c2 - b2 * c1 ; int b = a2 * c1 - a1 * c2 ; int c = a1 * b2 - b1 * a2 ; int d = (- a * x1 - b * y1 - c * z1) ; // equation of plane is: a*x + b*y + c*z = 0 # // checking if the 4th point satisfies // the above equation if(a * x + b * y + c * z + d == 0) System.out.println("Coplanar"); else System.out.println("Not Coplanar"); } //Driver Code public static void main(String[] args) { int x1 = 3 ; int y1 = 2 ; int z1 = -5 ; int x2 = -1 ; int y2 = 4 ; int z2 = -3 ; int x3 = -3 ; int y3 = 8 ; int z3 = -5 ; int x4 = -3 ; int y4 = 2 ; int z4 = 1 ; //function calling equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) ; }}
# Python program to check if 4 points# in a 3-D plane are Coplanar # Function to find equation of plane.def equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x, y, z): a1 = x2 - x1 b1 = y2 - y1 c1 = z2 - z1 a2 = x3 - x1 b2 = y3 - y1 c2 = z3 - z1 a = b1 * c2 - b2 * c1 b = a2 * c1 - a1 * c2 c = a1 * b2 - b1 * a2 d = (- a * x1 - b * y1 - c * z1) # equation of plane is: a*x + b*y + c*z = 0 # # checking if the 4th point satisfies # the above equation if(a * x + b * y + c * z + d == 0): print("Coplanar") else: print("Not Coplanar") # Driver Codex1 = 3y1 = 2z1 = -5x2 = -1y2 = 4z2 = -3x3 = -3y3 = 8z3 = -5x4 = -3y4 = 2z4 = 1equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4)
// C# program to check if 4 points// in a 3-D plane are Coplanarusing System; class GFG{ // Function to find equation of plane.static void equation_plane(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3, int x, int y, int z){ int a1 = x2 - x1 ; int b1 = y2 - y1 ; int c1 = z2 - z1 ; int a2 = x3 - x1 ; int b2 = y3 - y1 ; int c2 = z3 - z1 ; int a = b1 * c2 - b2 * c1 ; int b = a2 * c1 - a1 * c2 ; int c = a1 * b2 - b1 * a2 ; int d = (- a * x1 - b * y1 - c * z1) ; // equation of plane is: a*x + b*y + c*z = 0 # // checking if the 4th point satisfies // the above equation if(a * x + b * y + c * z + d == 0) Console.WriteLine("Coplanar"); else Console.WriteLine("Not Coplanar"); } // Driver Codestatic public void Main (){ int x1 = 3 ; int y1 = 2 ; int z1 = -5 ; int x2 = -1 ; int y2 = 4 ; int z2 = -3 ; int x3 = -3 ; int y3 = 8 ; int z3 = -5 ; int x4 = -3 ; int y4 = 2 ; int z4 = 1 ; //function calling equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); }} // This code is contributed by jit_t
<?php// PHP program to check if 4 points// in a 3-D plane are Coplanar // Function to find equation of plane.function equation_plane($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3, $x, $y, $z){ $a1 = $x2 - $x1; $b1 = $y2 - $y1; $c1 = $z2 - $z1; $a2 = $x3 - $x1; $b2 = $y3 - $y1; $c2 = $z3 - $z1; $a = $b1 * $c2 - $b2 * $c1; $b = $a2 * $c1 - $a1 * $c2; $c = $a1 * $b2 - $b1 * $a2; $d = (- $a * $x1 - $b * $y1 - $c * $z1); // equation of plane is: // a*x + b*y + c*z = 0 # // checking if the 4th point // satisfies the above equation if($a * $x + $b * $y + $c * $z + $d == 0) echo ("Coplanar"); else echo ("Not Coplanar");} // Driver Code$x1 = 3; $y1 = 2; $z1 = -5;$x2 = -1; $y2 = 4; $z2 = -3;$x3 = -3; $y3 = 8; $z3 = -5;$x4 = -3; $y4 = 2; $z4 = 1; // function callingequation_plane($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3, $x4, $y4, $z4); // This code is contributed// by Shivi_Aggarwal?>
<script>//javascript program to check if 4 points//in a 3-D plane are Coplanar // Function to find equation of plane. function equation_plane(x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 , x , y, z) { var a1 = x2 - x1; var b1 = y2 - y1; var c1 = z2 - z1; var a2 = x3 - x1; var b2 = y3 - y1; var c2 = z3 - z1; var a = b1 * c2 - b2 * c1; var b = a2 * c1 - a1 * c2; var c = a1 * b2 - b1 * a2; var d = (-a * x1 - b * y1 - c * z1); // equation of plane is: a*x + b*y + c*z = 0 # // checking if the 4th point satisfies // the above equation if (a * x + b * y + c * z + d == 0) document.write("Coplanar"); else document.write("Not Coplanar"); } // Driver Code var x1 = 3; var y1 = 2; var z1 = -5; var x2 = -1; var y2 = 4; var z2 = -3; var x3 = -3; var y3 = 8; var z3 = -5; var x4 = -3; var y4 = 2; var z4 = 1; // function calling equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); // This code is contributed by Rajput-Ji</script>
Coplanar
ankthon
ukasp
Shivi_Aggarwal
jit_t
Rajput-Ji
arorakashish0911
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Closest Pair of Points | O(nlogn) Implementation
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 25466,
"s": 25224,
"text": "Given 4 points (x1, y1, z1), (x2, y2, z2), (x3, y3, z3), (x4, y4, z4). The task is to write a program to check whether these 4 points are coplanar or not.Note: 4 p... |
Swing Examples - Using JFormattedTextField | Following example showcase how to create and use JFormattedTextField to specify various formats on Text Fields in Swing based application.
We are using the following APIs.
JFormattedTextField − To create a formatted text field.
JFormattedTextField − To create a formatted text field.
NumberFormat − To provide different type of formats to JFormattedTextField.
NumberFormat − To provide different type of formats to JFormattedTextField.
NumberFormat.getNumberInstance() − to get a number format.
NumberFormat.getNumberInstance() − to get a number format.
NumberFormat.getPercentInstance() − to get a percentage format.
NumberFormat.getPercentInstance() − to get a percentage format.
NumberFormat.getCurrencyInstance() − to get a currency format.
NumberFormat.getCurrencyInstance() − to get a currency format.
SimpleDateFormat − to get a date format.
SimpleDateFormat − to get a date format.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTester implements PropertyChangeListener {
private static JFormattedTextField principleTextField;
private static JFormattedTextField rateTextField;
private static JFormattedTextField yearsTextField;
private static JFormattedTextField amountTextField;
public static void main(String[] args) {
SwingTester tester = new SwingTester();
createWindow(tester);
}
private static void createWindow(SwingTester tester) {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame, tester);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame, SwingTester tester) {
JPanel panel = new JPanel();
LayoutManager layout = new GridLayout(6,2);
panel.setLayout(layout);
panel.setSize(300, 200);
panel.setBorder(BorderFactory.createTitledBorder("Formats"));
NumberFormat principleFormat = NumberFormat.getNumberInstance();
principleTextField = new JFormattedTextField(principleFormat);
principleTextField.setName("Principle");
principleTextField.setColumns(10);
JLabel principleLabel = new JLabel("Principle:");
principleLabel.setLabelFor(principleTextField);
principleTextField.setValue(new Double(100000));
principleTextField.addPropertyChangeListener("value", tester);
NumberFormat rateFormat = NumberFormat.getPercentInstance();
rateFormat.setMinimumFractionDigits(2);
rateTextField = new JFormattedTextField(rateFormat);
rateTextField.setName("Rate");
rateTextField.setColumns(10);
JLabel rateLabel = new JLabel("Interest Rate:");
rateLabel.setLabelFor(rateTextField);
rateTextField.setValue(new Double(0.1));
rateTextField.addPropertyChangeListener("value", tester);
yearsTextField = new JFormattedTextField();
yearsTextField.setName("Years");
yearsTextField.setColumns(10);
JLabel yearLabel = new JLabel("Year(s):");
yearLabel.setLabelFor(yearsTextField);
yearsTextField.setValue(new Double(1));
yearsTextField.addPropertyChangeListener("value", tester);
NumberFormat amountFormat = NumberFormat.getCurrencyInstance();
amountTextField = new JFormattedTextField(amountFormat);
amountTextField.setName("Amount");
amountTextField.setColumns(10);
amountTextField.setEditable(false);
JLabel amountLabel = new JLabel("Amount:");
amountLabel.setLabelFor(amountTextField);
amountTextField.setValue(new Double(110000));
DateFormat dateFormat = new SimpleDateFormat("dd MMM YYYY");
JFormattedTextField today = new JFormattedTextField(dateFormat);
today.setName("Today");
today.setColumns(10);
today.setEditable(false);
JLabel todayLabel = new JLabel("Date:");
todayLabel.setLabelFor(today);
today.setValue(new Date());
panel.add(principleLabel);
panel.add(principleTextField);
panel.add(rateLabel);
panel.add(rateTextField);
panel.add(yearLabel);
panel.add(yearsTextField);
panel.add(amountLabel);
panel.add(amountTextField);
panel.add(todayLabel);
panel.add(today);
JPanel mainPanel = new JPanel();
mainPanel.add(panel);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
double amount, rate, years, principle;
principle = ((Number)principleTextField.getValue()).doubleValue();
rate = ((Number)rateTextField.getValue()).doubleValue() * 100;
years = ((Number)yearsTextField.getValue()).doubleValue();
amount = principle + principle * rate * years / 100;
amountTextField.setValue(new Double(amount));
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2178,
"s": 2039,
"text": "Following example showcase how to create and use JFormattedTextField to specify various formats on Text Fields in Swing based application."
},
{
"code": null,
"e": 2211,
"s": 2178,
"text": "We are using the following APIs."
},
{
... |
border-top-0 class in Bootstrap 4 | Use the border-top-0 class in Bootstrap 4 to remove the top border.
Set the border-top-0 class −
<div class="mystyle border border-top-0">
Rectangle is missing the TOP border.
</div>
Let us see an example to implement the border-top-0 class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<style>
.mystyle {
width: 350px;
height: 170px;
margin: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Heading Two</h2>
<div class="mystyle border border-top-0">
Rectangle is missing the TOP border.
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Use the border-top-0 class in Bootstrap 4 to remove the top border."
},
{
"code": null,
"e": 1159,
"s": 1130,
"text": "Set the border-top-0 class −"
},
{
"code": null,
"e": 1247,
"s": 1159,
"text": "<div class=\"m... |
Machine Learning for Anomaly Detection - GeeksforGeeks | 18 Aug, 2021
Anomaly Detection is the technique of identifying rare events or observations which can raise suspicions by being statistically different from the rest of the observations. Such “anomalous” behaviour typically translates to some kind of a problem like a credit card fraud, failing machine in a server, a cyber attack, etc.An anomaly can be broadly categorized into three categories –
Point Anomaly: A tuple in a dataset is said to be a Point Anomaly if it is far off from the rest of the data.Contextual Anomaly: An observation is a Contextual Anomaly if it is an anomaly because of the context of the observation.Collective Anomaly: A set of data instances help in finding an anomaly.
Point Anomaly: A tuple in a dataset is said to be a Point Anomaly if it is far off from the rest of the data.
Contextual Anomaly: An observation is a Contextual Anomaly if it is an anomaly because of the context of the observation.
Collective Anomaly: A set of data instances help in finding an anomaly.
Anomaly detection can be done using the concepts of Machine Learning. It can be done in the following ways –
Supervised Anomaly Detection: This method requires a labeled dataset containing both normal and anomalous samples to construct a predictive model to classify future data points. The most commonly used algorithms for this purpose are supervised Neural Networks, Support Vector Machine learning, K-Nearest Neighbors Classifier, etc.Unsupervised Anomaly Detection: This method does require any training data and instead assumes two things about the data ie Only a small percentage of data is anomalous and Any anomaly is statistically different from the normal samples. Based on the above assumptions, the data is then clustered using a similarity measure and the data points which are far off from the cluster are considered to be anomalies.
Supervised Anomaly Detection: This method requires a labeled dataset containing both normal and anomalous samples to construct a predictive model to classify future data points. The most commonly used algorithms for this purpose are supervised Neural Networks, Support Vector Machine learning, K-Nearest Neighbors Classifier, etc.
Unsupervised Anomaly Detection: This method does require any training data and instead assumes two things about the data ie Only a small percentage of data is anomalous and Any anomaly is statistically different from the normal samples. Based on the above assumptions, the data is then clustered using a similarity measure and the data points which are far off from the cluster are considered to be anomalies.
We now demonstrate the process of anomaly detection on a synthetic dataset using the K-Nearest Neighbors algorithm which is included in the pyod module.Step 1: Importing the required libraries
Python3
import numpy as npfrom scipy import statsimport matplotlib.pyplot as pltimport matplotlib.font_managerfrom pyod.models.knn import KNNfrom pyod.utils.data import generate_data, get_outliers_inliers
Step 2: Creating the synthetic data
Python3
# generating a random dataset with two featuresX_train, y_train = generate_data(n_train = 300, train_only = True, n_features = 2) # Setting the percentage of outliersoutlier_fraction = 0.1 # Storing the outliers and inliners in different numpy arraysX_outliers, X_inliers = get_outliers_inliers(X_train, y_train)n_inliers = len(X_inliers)n_outliers = len(X_outliers) # Separating the two featuresf1 = X_train[:, [0]].reshape(-1, 1)f2 = X_train[:, [1]].reshape(-1, 1)
Step 3: Visualising the data
Python3
# Visualising the dataset# create a meshgridxx, yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200)) # scatter plotplt.scatter(f1, f2)plt.xlabel('Feature 1')plt.ylabel('Feature 2')
Step 4: Training and evaluating the model
Python3
# Training the classifierclf = KNN(contamination = outlier_fraction)clf.fit(X_train, y_train) # You can print this to see all the prediction scoresscores_pred = clf.decision_function(X_train)*-1 y_pred = clf.predict(X_train)n_errors = (y_pred != y_train).sum()# Counting the number of errors print('The number of prediction errors are ' + str(n_errors))
Step 5: Visualising the predictions
Python3
# threshold value to consider a# datapoint inlier or outlierthreshold = stats.scoreatpercentile(scores_pred, 100 * outlier_fraction) # decision function calculates the raw# anomaly score for every pointZ = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1Z = Z.reshape(xx.shape) # fill blue colormap from minimum anomaly# score to threshold valuesubplot = plt.subplot(1, 2, 1)subplot.contourf(xx, yy, Z, levels = np.linspace(Z.min(), threshold, 10), cmap = plt.cm.Blues_r) # draw red contour line where anomaly# score is equal to thresholda = subplot.contour(xx, yy, Z, levels =[threshold], linewidths = 2, colors ='red') # fill orange contour lines where range of anomaly# score is from threshold to maximum anomaly scoresubplot.contourf(xx, yy, Z, levels =[threshold, Z.max()], colors ='orange') # scatter plot of inliers with white dotsb = subplot.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c ='white', s = 20, edgecolor ='k') # scatter plot of outliers with black dotsc = subplot.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c ='black', s = 20, edgecolor ='k')subplot.axis('tight') subplot.legend( [a.collections[0], b, c], ['learned decision function', 'true inliers', 'true outliers'], prop = matplotlib.font_manager.FontProperties(size = 10), loc ='lower right') subplot.set_title('K-Nearest Neighbours')subplot.set_xlim((-10, 10))subplot.set_ylim((-10, 10))plt.show()
Reference: https://www.analyticsvidhya.com/blog/2019/02/outlier-detection-python-pyod/
shubham_singh
rajeev0719singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
Python | Decision tree implementation
Search Algorithms in AI
Difference between Informed and Uninformed Search in AI
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24347,
"s": 24319,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 24732,
"s": 24347,
"text": "Anomaly Detection is the technique of identifying rare events or observations which can raise suspicions by being statistically different from the rest of the obse... |
Which is better System.String or System.Text.StringBuilder classes in C#? | The main difference is StringBuilder is Mutable whereas String is Immutable.
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.
On the other hand, StringBuilder is mutable. Means, if we create a string builder object then we can perform any operation like insert, replace or append without creating new instance for every time. It will update string at one place in memory doesn’t create new space in memory.
Live Demo
using System;
using System.Text;
class DemoApplication{
public static void Main(String[] args){
String systemString = "Hello";
StringConcat(systemString);
Console.WriteLine("String Class Result: " + systemString);
StringBuilder stringBuilderString = new StringBuilder("Hello");
StringBuilderConcat(stringBuilderString);
Console.WriteLine("StringBuilder Class Result: " + stringBuilderString);
}
public static void StringConcat(String systemString){
String appendString = " World";
systemString = String.Concat(systemString, appendString);
}
public static void StringBuilderConcat(StringBuilder stringBuilderString){
stringBuilderString.Append(" World");
}
}
The output of the above example is as follows −
String Class Result: Hello
StringBuilder Class Result: Hello World
Use of StringConcat Method: In this method, we are passing a string “Hello” and performing “systemString = String.Concat(systemString, appendString);” where appendString is “ World” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and systemString in StringConcat() stores reference of the new string. But the references systemString in Main() and StringConcat() refer to different strings.
Use of StringConcat Method: In this method, we are passing a string “Hello” and performing “systemString = String.Concat(systemString, appendString);” where appendString is “ World” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and systemString in StringConcat() stores reference of the new string. But the references systemString in Main() and StringConcat() refer to different strings.
Use of StringBuilderConcat Method: In this method, we are passing a string “Hello” and performing “stringBuilderString.Append(" World");” which changes the actual value of the string (in Main) to “Hello World”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
Use of StringBuilderConcat Method: In this method, we are passing a string “Hello” and performing “stringBuilderString.Append(" World");” which changes the actual value of the string (in Main) to “Hello World”. This is due to the simple fact that StringBuilder is mutable and hence changes its value. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "The main difference is StringBuilder is Mutable whereas String is Immutable."
},
{
"code": null,
"e": 1288,
"s": 1139,
"text": "String is immutable, Immutable means if you create string object then you cannot modify it and It always ... |
Interpolation Search Program in C | Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in sorted and equally distributed form.
It's runtime complexity is log2(log2 n).
#include<stdio.h>
#define MAX 10
// array of items on which linear search will be conducted.
int list[MAX] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };
int find(int data) {
int lo = 0;
int hi = MAX - 1;
int mid = -1;
int comparisons = 1;
int index = -1;
while(lo <= hi) {
printf("\nComparison %d \n" , comparisons ) ;
printf("lo : %d, list[%d] = %d\n", lo, lo, list[lo]);
printf("hi : %d, list[%d] = %d\n", hi, hi, list[hi]);
comparisons++;
// probe the mid point
mid = lo + (((double)(hi - lo) / (list[hi] - list[lo])) * (data - list[lo]));
printf("mid = %d\n",mid);
// data found
if(list[mid] == data) {
index = mid;
break;
} else {
if(list[mid] < data) {
// if data is larger, data is in upper half
lo = mid + 1;
} else {
// if data is smaller, data is in lower half
hi = mid - 1;
}
}
}
printf("\nTotal comparisons made: %d", --comparisons);
return index;
}
int main() {
//find location of 33
int location = find(33);
// if element was found
if(location != -1)
printf("\nElement found at location: %d" ,(location+1));
else
printf("Element not found.");
return 0;
}
If we compile and run the above program, it will produce the following result −
Comparison 1
lo : 0, list[0] = 10
hi : 9, list[9] = 44
mid = 6
Total comparisons made: 1
Element found at location: 7
You can change the search value and execute the program to test it.
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2824,
"s": 2580,
"text": "Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in sorted and equally distributed form."
},
{... |
Can we define an enum inside a method in Java? | Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
We can an enumeration inside a class. But, we cannot define an enum inside a method. If you try to do so it generates a compile time error saying “enum types must not be local”.
public class EnumExample{
public void sample() {
enum Vehicles {
Activa125, Activa5G, Access125, Vespa, TVSJupiter;
}
}
}
EnumExample.java:3: error: enum types must not be local
enum Vehicles {
^
1 error
To use the enum constants inside a method declare the required enum inside a class and use its constants inside a method using the values().
Live Demo
public class EnumerationExample {
enum Enum {
Mango, Banana, Orange, Grapes, Thursday, Apple
}
public void testMethod(){
Enum constants[] = Enum.values();
System.out.println("Value of constants: ");
for(Enum d: constants) {
System.out.println(d);
}
}
public static void main(String args[]) {
EnumerationExample obj = new EnumerationExample();
obj.testMethod();
}
}
Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −"
},
{
"code": null,
"e": 1261,
"s": 1181,
"text": "enum Days {\n SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, F... |
10 SQL ConceptsYou Must Know to Ace any SQL Interviews | by 👩🏻💻 Kessie Zhang | Towards Data Science | It’s almost the end of the year! I hope you all are studying hard and doing well. The beginning of the year (January and February) is usually the best time of the year to look for a job. So we need to be better prepared now and hit the ground running in 2021!
Tech companies usually have a large amount of data stored in their relational databases, so they want to see whether the candidates can extract and manipulate data using complex SQL queries before jumping into any modeling. SQL questions can be very tricky, so don’t underestimate SQL. Besides, no matter how good you are with SQL, you might still find it challenging to write the queries fast enough, especially under pressure. We all know how intimidating interviews can be, it’s ok if you didn’t fail the last interview. You can’t change what’s done, but you can learn from your mistakes and avoid making the same mistakes in the future.
Like all programming problems you’ll find in interviews, if you can’t spot the tricks, even easy problems on Leetcode can be very challenging. If you are new to SQL, you probably hope someone could share all the tricks with you. In this article, I will share all the common patterns I’ve seen from practicing SQL problems on Leetcode to help you be better at SQL immediately.
The goal of this blog is not to go through all the SQL basics. Before we get started, it will be helpful if you are already familiar with SQL basic syntax, different joins, union, window functions, and CTE (Common Table Expressions.)
Here are some resources if you want to learn more about SQL:
W3SchoolsKhanacademySQLZooCodecademyDataCampUdemy
W3Schools
Khanacademy
SQLZoo
Codecademy
DataCamp
Udemy
Here are some common concepts you will be asked during a SQL technical interview.
Group By...Having Aggregate FunctionsHaving >=All()CASE WHENFinding the First/LastDATEDIFF and Self JoinWHERE (X,Y) IN/NOT IN (SELECT X, Y FROM)RankingRolling SumLikeIFNULL()
Group By...Having Aggregate Functions
Having >=All()
CASE WHEN
Finding the First/Last
DATEDIFF and Self Join
WHERE (X,Y) IN/NOT IN (SELECT X, Y FROM)
Ranking
Rolling Sum
Like
IFNULL()
In the following section, I will go over each concept with an example to help you better understand when to use these important concepts.
There is a table courses with columns: student and class.
Please list out all classes which have more than or equal to 5 students.
Note: The students should not be counted duplicates in each course.
First, we need to count the student number in each class. And then select the ones that have more than 5 students. To get the number of students in each class, we use GROUP BY and COUNT . Note that we use DISTINCTsince the student name may be duplicated in a class as it is mentioned in the problem description. After that, we want to filter all the classes with more than or equal to 5 students. HAVING is a very common clause in SQL queries. Like WHERE, it helps filter data; however, HAVING is used to specify the condition or conditions for a group or an aggregation.
SELECT class, COUNT(DISTINCT student)FROM coursesGROUP BY class;
There are two tables: Product with columns: product_id, product_name, and unit_price; and Sales with columns: seller_id, product_id, buyer_id, sale_date, quantity, and price.
Write an SQL query that reports the best-seller by total sales price. If there is a tie, report them all.
We can first get the total price for each seller by using SUM and GROUP BY. After that, we can then use Having >=all() concept to find the seller(s) that has/have the highest total sales price.
SELECT seller_idFROM SalesGROUP BY seller_idHAVING SUM(price) >= All(SELECT SUM(price) FROM Sales GROUP BY seller_id);
There is a table Department with columns: id, revenue and month.
Write an SQL query to reformat the table such that there are a department id column and a revenue column for each month.
A CASE WHEN adds a new column to the result of the query, notice that it always ends with END. (CASE WHEN ... THEN ... ELSE ... END). If you've ever used any programming language, you could think of it as an if-then-else type of logic.
CASE WHEN with aggregates is one of the most common interview concepts. In this example, we simply sum up all the revenue if the condition is true.
SELECT id,SUM(CASE WHEN month=’Jan’ THEN revenue ELSE null END) as Jan_Revenue,SUM(CASE WHEN month=’Feb’ THEN revenue ELSE null END) as Feb_Revenue,SUM(CASE WHEN month=’Mar’ THEN revenue ELSE null END) as Mar_Revenue,SUM(CASE WHEN month=’Apr’ THEN revenue ELSE null END) as Apr_Revenue,SUM(CASE WHEN month=’May’ THEN revenue ELSE null END) as May_Revenue,SUM(CASE WHEN month=’Jun’ THEN revenue ELSE null END) as Jun_Revenue, SUM(CASE WHEN month=’Jul’ THEN revenue ELSE null END) as Jul_Revenue, SUM(CASE WHEN month=’Aug’ THEN revenue ELSE null END) as Aug_Revenue, SUM(CASE WHEN month=’Sep’ THEN revenue ELSE null END) as Sep_Revenue, SUM(CASE WHEN month=’Oct’ THEN revenue ELSE null END) as Oct_Revenue, SUM(CASE WHEN month=’Nov’ THEN revenue ELSE null END) as Nov_Revenue, SUM(CASE WHEN month=’Dec’ THEN revenue ELSE null END) as Dec_Revenue FROM Department GROUP BY id;
There is a table Activity with columns: player_id, device_id, event_date and games_played.
Write an SQL query that reports the first login date for each player.
When it comes to select the first or latest of something, we can use MIN to find the first. Similarly, we can use MAX to find the last one.
SELECT player_id, MIN(event_date) AS first_loginFROMActivityGROUP BYplayer_id;
There is a table: Weather with columns: id, recordDate, and temperature.
Write an SQL query to find all dates’ ids with higher temperatures than their previous dates (yesterday).
Dealing with the time format requires us to be familiar with the queries that deal with time. We usually use time constraint after WHERE , HAVING ,CASE WHEN . Time constraint includes selecting a special time range between 2020–01–01 and 2020–12–31 , a specific year/month/day MONTH('2020–12–31') and the difference between two date values in years, months, weeks, and so on,DATEDIFF( date_part , start_date , end_date). Notice that if you don’t specify the date_part, DATEDIFF(start_date , end_date) will return the number of days between two date values.
In this example, we use self join to create a new w2.recordDate (yesterday) column. Then filter out ids that have higher temperatures than yesterday.
Note:DATEDIFF(‘2007–12–31’,’2007–12–30') will return 1, whileDATEDIFF(‘2010–12–30’,’2010–12–31')will returns -1.
SELECT w1.id FROM Weather w1, Weather w2 WHERE DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.Temperature > w2.Temperature;
There are two tables: Employee with columns: Id, Name, Salary and DepartmentId; and Department with columns: Id, and Name.
Write a SQL query to find employees who have the highest salary in each of the departments.
We can use MAX to find the highest salary in each DepartmentId. Then we can join these two tables to get DepartmentName , Employee and Salary of the ones having the highest salary in their departments.
SELECT D.Name AS Department, E.Name AS Employee, Salary FROM Employee E INNER JOIN Department D ON E.DepartmentId=D.Id WHERE (E.DepartmentId, E.Salary) IN (SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId);
There is a table: Scores with columns: id, and Score.
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no “holes” between ranks.
Dense_Rank is one example of ranking window functions. Ranking can add an ordered number to each of your output rows. There are three functions: Row_number, Rank and Dense_rank . Using row_number gives a result that must always be unique. Each row is assigned a different value even if they are equal. RANK skips the number of positions after records with the same rank number (such as 1, 1, 3, 4, 5). In contrast, the ranking RANK_DENSE doesn’t skip records with the same rank number (such as 1, 1, 2, 3, 4).
In the sample output, there’s no skip record in the Rank column. Therefore, using RANK_DENSE is more appropriate here. Note that when we want to name something that is the same as the reserved name, we use ‘X.’
SELECT Score, Dense_Rank() OVER(ORDER BY Score DESC) as 'Rank'FROM Scores;
There is a table: Queue with columns: person_id, person_name, weight and turn.
The maximum weight the elevator can hold is 1000.
Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit. It is guaranteed that the person who is first in the queue can fit in the elevator.
Rolling sum/average/count are typical window functions. You can simply combine the aggregate functions SUM() or AVG() or COUNT() with the OVER() clause to get the rolling result.
In this example, we first get the rolling total (sum of all the weights from before) and then filter the last person with less than 1000 total rolling sum. When we want to find the first/last record, besides using min and max from above, we can also use ORDER BY ASC/DESC LIMIT 1 .
SELECTperson_nameFROM(SELECTperson_name,SUM(weight) OVER(ORDER BY turn) as totalFROM Queue) TWHERE total<=1000ORDER BY total DESCLIMIT 1
There is a table: Patients with columns: patient_id, patient_name, and conditions.
Write an SQL query to report the patient_id, patient_name all conditions of patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix.
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
% — The percent sign represents zero, one, or multiple characters
_ — The underscore represents a single character
In this example, we know that Type I Diabetes always starts with DIAB1. So we can use where to filter patients who have conditions that start with ‘DIAB1.’
SELECT* FROM Patients WHERE conditions LIKE ‘%DIAB1%’
There is a table: Ads with columns: ad_id, user_id, and action.
A company is running Ads and wants to calculate the performance of each Ad.
Write an SQL query to find the click-through rate of each Ad. [Ad total clicks/(Ad total clicks + Ad total views)]
The IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, IFNULL(expression, alt_value) , this function returns the expression.
In this example, we first define the click-through rate. If the click-through rate is null, return 0. Don’t forget to use ROUND and * 100 to make the code more readable.
SELECTad_id,ROUND(IFNULL(SUM(action = ‘Clicked’) /(SUM(action = ‘Clicked’) + SUM(action = ‘Viewed’)) * 100, 0), 2) AS ctrFROM AdsGROUP BY ad_idORDER BY ctr DESC, ad_id ASC;
There you have it! Now you know all the common patterns and tricks I’ve learned after solving 100 Leetcode SQL questions.... Believe me, I’ve been there. There have been many times that I’ve found myself not being good enough. But let me tell you, one day you can do all the coding problems without checking the solutions as long as you keep practicing. Good luck and happy learning!
If you find this helpful, please follow me and check out my other blogs. ❤️ | [
{
"code": null,
"e": 432,
"s": 172,
"text": "It’s almost the end of the year! I hope you all are studying hard and doing well. The beginning of the year (January and February) is usually the best time of the year to look for a job. So we need to be better prepared now and hit the ground running in 2... |
What are jQuery events .load(), .ready(), .unload()? | jQuery load() method
The load() method is used to attach event handler to load event.
You can try to run the following code to learn how to work with jQuery load() method.
Note: The method deprecated in jQuery 1.8. It got finally removed in jQuery 3.0. To run the following code, add jQuery version lesser than 1.8,
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("This is an image.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="310" height="270">
<p>This image will load only in jQuery version lesser than 1.8</p>
</body>
</html>
jQuery ready() method
Easily specify what happens when a ready event occurs, with the ready() function.
You can try to run the following code to learn how to work with ready() method. For an example, we're hiding an element here:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<p>This is demo text.</p>
<button>Hide</button>
</body>
</html>
jQuery unload() method
If you want to trigger an event while navigate away from the page, use the unload() method.
Note: The jQuery unload() method deprecated in jQuery 1.8. It got finally removed in jQuery 3.0.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(window).unload(function(){
alert("Thanks! Bye!");
});
});
</script>
</head>
<body>
<p>Event triggers when you leave the page.</p>
</body>
</html> | [
{
"code": null,
"e": 1083,
"s": 1062,
"text": "jQuery load() method"
},
{
"code": null,
"e": 1148,
"s": 1083,
"text": "The load() method is used to attach event handler to load event."
},
{
"code": null,
"e": 1234,
"s": 1148,
"text": "You can try to run the fo... |
Python os.write() Method | Python method write() writes the string str to file descriptor fd. Return the number of bytes actually written.
Following is the syntax for write() method −
os.write(fd, str)
fd − This is the file descriptor.
fd − This is the file descriptor.
str − This is the string to be written.
str − This is the string to be written.
This method returns the number of bytes actually written.
Python following example shows the usage of write() method.
# !/usr/bin/python
import os, sys
# Open file
fd = os.open("f1.txt",os.O_RDWR|os.CREAT)
# Writing text
ret = os.write(fd,"This is test")
# ret consists of number of bytes written to f1.txt
print "the number of bytes written: "
print ret
print "written successfully"
# Close opened file
os.close(fd)
print "Closed the file successfully!!"
When we run above program, it produces following result −
the number of bytes written:
12
written successfully
Closed the file successfully!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2356,
"s": 2244,
"text": "Python method write() writes the string str to file descriptor fd. Return the number of bytes actually written."
},
{
"code": null,
"e": 2401,
"s": 2356,
"text": "Following is the syntax for write() method −"
},
{
"code": nul... |
Display the internal Structure of an Object in R Programming - str() Function - GeeksforGeeks | 05 Jun, 2020
str() function in R Language is used for compactly displaying the internal structure of a R object. It can display even the internal structure of large lists which are nested. It provides one liner output for the basic R objects letting the user know about the object and its constituents. It can be used as an alternative to summary() but str() is more compact than summary(). It gives information about the rows(observations) and columns(variables) along with additional information like the names of the columns, class of each columns followed by few of the initial observations of each of the columns.
Syntax: str(object, ...)
Parameter:object: Any R object about which information is required.
Example 1:
# R program to display # structure of a list # Creating a listgfg <- list(2, 4, 5, 6, 7, 9, 13, 15, 3, 1) # Calling str() functionstr(gfg)
Output:
List of 10
$ : num 2
$ : num 4
$ : num 5
$ : num 6
$ : num 7
$ : num 9
$ : num 13
$ : num 15
$ : num 3
$ : num 1
Here, we can observe the output which is a description of the object gfg. It mentions that it is a list having 10 components. In the following rows, it displays each one of them along with their class i.e. numeric in this case.
Example 2:
# R program to display structure # of a pre-defined dataset # Importing Librarylibrary(datasets) # Importing datasethead(airquality) # Calling str() functionstr(airquality)
Here, head(airquality) will display the first few rows of the data frame. After executing, the following output will be displayed.Output :
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
'data.frame': 153 obs. of 6 variables:
$ Ozone : int 41 36 12 18 NA 28 23 19 8 NA ...
$ Solar.R: int 190 118 149 313 NA NA 299 99 19 194 ...
$ Wind : num 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
$ Temp : int 67 72 74 62 56 66 65 59 61 69 ...
$ Month : int 5 5 5 5 5 5 5 5 5 5 ...
$ Day : int 1 2 3 4 5 6 7 8 9 10 ...
It provides us the information that the dataset airquality is a data frame with 153 observations(rows) of 6 variables(columns). Then it tells us about each variable one by one as follows, the first column with name Ozone is of type integer followed by few of its values and the second column is named Solar.R which is also of the integer type followed by few of its contents and so on.
str() will be really useful when we are unsure about the contents of an object as it will help us take a quick preview of the contents and structure of the object. This will also help in revealing issues in the naming of the columns, class of the content, etc, if any exist.
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 25072,
"s": 25044,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 25678,
"s": 25072,
"text": "str() function in R Language is used for compactly displaying the internal structure of a R object. It can display even the internal structure of large lists which... |
Transformers: Implementing NLP Models in 3 Lines of Code | by Fernando López | Towards Data Science | Using state-of-the-art Natural Language Processing models has never been easier. Hugging Face [1] has developed a powerful library called transformers which allows us to implement and make use of a wide variety of state-of-the-art NLP models in a very simple way. In this blog, we are going to see how to install and use the transformers library for different tasks such as:
Text Classification
Question-Answering
Masked Language Modeling
Text Generation
Named Entity Recognition
Text Summarization
Translation
So before we start reviewing each of the implementations for the different tasks, let’s install the transformers library. In my case, I am working on macOS, when trying to install directly with pip I got an error which I solved by previously installing the Rust compiler as follows:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
After that I installed transformers directly with pip as follows:
$ pip install transformers
Great, with the two previous steps, the library would have been installed correctly. So let’s start with the different implementations, let’s go for it!
The text classification task consists of assigning a given text to a specific class from a given set of classes. Sentiment analysis is the most commonly addressed problem in a text classification problem.
To use a text classification model through the transformers library, we only need two arguments, task and model , which specifies the type of problem to be approached and the model to be used respectively. Given the great diversity of models hosted in the Hugging Face repository, we can start playing with some of them. Here you can find the set of models for text classification tasks.
In Figure 2 we can see the implementation of the bert-base-multilingual-uncasced-sentimentmodel for sentiment analysis.
The output is:
Result: [{'label': 'NEG', 'score': 0.9566874504089355}]
Depending on the model that you choose to implement, it will be the result to be obtained. It is important to consider reading the documentation of each model to know what datasets they were trained on and what type of classification they perform. Another great advantage of transformers is that if you have your own model hosted in the Hugging Face repository, you can also use it through this library.
The task of Extractive Question Answering is about trying to find an answer given a question in a given context. One of the most representative datasets for this task is The Stanford Question Answering Dataset (SQuAD) [2].
Tackling this task. the transformers pipeline requires context and question . In the following example the context is determined by a paragraph from the Alice in Wonderland book [3], the question refers to an event described in the paragraph. In the following figure you can see how the implementation would be:
The output is:
Answer: 'her sister'
For this task, we select the model robert-base-squad-v1 , however, in the Hugging Face repository we can find different alternative models for this task, it would be worth taking a look at some of them.
The Masked Language Modeling task is about masking tokens of a given text sentence with a masking token, where the model is asked to fill each mask with an appropriate token.
For a task of this type, the transformers pipeline only requires the name of the task (in this case it is fill-mask ) and then the text sequence where the token to be masked is specified, in the following figure we can see the implementation:
The output is:
[{'sequence': ' Horror movies are often very scary to people', 'score': 0.12314373254776001, 'token': 28719, 'token_str': ' Horror'}, {'sequence': ' horror movies are often very scary to people', 'score': 0.052469268441200256, 'token': 8444, 'token_str': ' horror'}, {'sequence': 'Ghost movies are often very scary to people', 'score': 0.05243474990129471, 'token': 38856, 'token_str': 'Ghost'}, {'sequence': 'War movies are often very scary to people', 'score': 0.03345327079296112, 'token': 20096, 'token_str': 'War'}, {'sequence': 'Action movies are often very scary to people', 'score': 0.029487883672118187, 'token': 36082, 'token_str': 'Action'}]
The result is displayed as a list of tokens and their respective properties. In this case, the token with the best score is Horror and the last token is Action .
The text generation task refers to the creation of a syntactically and semantically correct portion of text with respect to a determined context. In this case, the pipeline initialization requires the type of task and the model to be used, as in the previous tasks. Finally, the pipeline instance requires 2 parameters, the context (or seed) and the length of the sequence to be generated max_length . The number of sequences to generate is an optional parameter.
The following figure shows the implementation of the GPT-2 model for the generation of 5 text sequences:
The output is:
[{'generated_text': 'My name is Fernando, I am from Mexico and live for a reason. I am a musician and the best producer, you might call me a poet'}, {'generated_text': 'My name is Fernando, I am from Mexico and I make an app with a lot of friends to keep us safe!" said Fernando.\n\nThe'}, {'generated_text': 'My name is Fernando, I am from Mexico and I am an atheist. I am living in a town called Tanta and I am living in the'}, {'generated_text': 'My name is Fernando, I am from Mexico and I have been doing this gig since the age of 21 and I am the first person to record this'}, {'generated_text': 'My name is Fernando, I am from Mexico and I am in Mexico", he said.\n\nHis name may be a reference to his birthplace and'}]
A little funny the sequences generated by GPT-2 based on someone who lives in Mexico and his name is Fernando.
The Named Entity Recognition task refers to the assignment of a class to each token of a given text sequence. For the implementation of this task, it is only necessary to assign the task identifier ner to the pipeline initialization. Subsequently, the object receives only one text stream. In the following figure we can see the implementation:
The output is:
('Fernando', 'I-PER')('Mexico', 'I-LOC')('Learning', 'I-ORG')('Engineer', 'I-MISC')('Hit', 'I-ORG')('##ch', 'I-ORG')
For this example, the classes are:
I-MISC, Miscellaneous entity
I-PER, Person’s name
I-ORG, Organisation
I-LOC, Location
It is interesting to see that the company was assigned correctly as an organization.
The Text Summarization task refers to the extraction of a summary given a determined text. To initialize the pipeline , the definition of the task is required as well as the summarization identifier. Subsequently, for the implementation of the task, only the text and the maximum and minimum sequence length to be generated are required as an argument. In the following figure we can see the implementation of this task:
The output is:
[{'summary_text': ' Machine learning is an important component of the growing field of data science . Machine learning, deep learning, and neural networks are all sub-fields of artificial intelligence . As big data continues to grow, the market demand for data scientists will increase, requiring them to assist in the identification of the most relevant business questions .'}]
As we can see, the summary generated by the model is correct with respect to the input text. In the same way as with the previous tasks, we can play with various models for text summarization such as BART , DistilBart and Pegasus [4].
The translation task refers to the conversion of a text written in a given language to another language. The transformers library allows to use state of the art models for translation such as T5 in a very simple way. The pipeline is initialized with the identifier of the task to be solved which refers to the original language and the language to be translated, for example to translate from English to French the identifier is: translation_en_to_fr . Finally, the generated object receives the text to be translated as an argument. In the following figure we can see the implementation of the translator of a text from English to French:
The output is:
L'apprentissage automatique est une branche de l'intelligence artificielle (AI) et de la science informatique qui se concentre sur l'utilisation de données et d'algorithmes pour imiter la façon dont les humains apprennent, en améliorant progressivement sa précision.
Throughout this tutorial blog we saw how to use the transformers library to implement state-of-the-art NLP models in a very simple way.
In this blog we saw how to implement some of the most common tasks, however it is important to mention that the examples shown in this blog are merely for inference, however one of the great attributes of the transformers library is that it provides the methods to be able to fine tune our own models based on those already trained. Which would be a good topic for the next blog.
[1] Hugging Face
[2] SQuAD: The Stanford Question Answering Dataset
[3] Alice in Wonderland
[4] Text Summarization Models | [
{
"code": null,
"e": 547,
"s": 172,
"text": "Using state-of-the-art Natural Language Processing models has never been easier. Hugging Face [1] has developed a powerful library called transformers which allows us to implement and make use of a wide variety of state-of-the-art NLP models in a very sim... |
Node embeddings: Node2vec with Neo4j | by Tomaz Bratanic | Towards Data Science | My last blog post about combining graphs with NLP techniques was the most successful by far. It motivated me to write more about this topic. During my research, I stumbled upon the node2vec algorithm and noticed how easy it would be to implement it with Neo4j and Graph Data Science library. I guess that left me no other choice than to put on my Neo4j Data Science glasses and demonstrate how easy it is to implement it.
Today we will be using the Spoonacular Food Dataset that is available on Kaggle. It contains nutritional information alongside the ingredients used in 1600+ dishes. Unfortunately, it contains no recipe for sourdough bread.
There are three types of nodes in the graph schema. A dish consists of one or more ingredients, which we represent as a connection between a dish and its ingredients. Recipes fall into categories or types such as lunch, breakfast, and so on. We use the apoc.schema.assert procedure to define the graph schema. It allows us to describe multiple indexes and unique constraints in a single query.
CALL apoc.schema.assert( // define indexes null, // define unique constraints {Ingredient:['name'], Dish:['id'], DishType:['name']})
Before we can execute the import query, we have to download the dataset and copy it to the Neo4j import folder. In the import query, we do a tiny bit of preprocessing as we lowercase the names of ingredients and replace dash characters (-) with whitespace.
LOAD CSV WITH HEADERS FROM "file:///newfood.csv" as rowCREATE (d:Dish{id:row.id})SET d += apoc.map.clean(row, ['id','dishTypes','ingredients'],[])FOREACH (i in split(row.ingredients,',') | MERGE (in:Ingredient{name:toLower(replace(i,'-',' '))}) MERGE (in)<-[:HAS_INGREDIENT]-(d))FOREACH (dt in split(row.dishTypes,',') | MERGE (dts:DishType{name:dt}) MERGE (dts)<-[:DISH_TYPE]-(d))
To start off, we will do a bit of graph exploration. Let’s look at which ingredients are used the most.
MATCH (n:Ingredient) RETURN n.name as ingredient, size((n)<--()) as mentionsORDER BY mentions DESC LIMIT 10
Results
Olive oil is by far the most popular as it is used in more than half of the recipes. Slowly following are garlic, salt, and butter. I didn’t know that butter was so popular. I also found it quite surprising that anchovies are so widely used. Or maybe the dataset is just biased towards dishes that contain anchovies.
We could build an application on top of this dataset to search for recipes based on the desired ingredients we want to cook. I borrowed this cypher query from the What’s cooking series written by Mark Needham and Lju Lazarevic. Let’s say, for example, you want to eat zucchini and feta cheese today, but don’t have any idea which recipe to go for. Luckily, our application could help us solve this problem with the following cypher query.
WITH ["feta cheese", "zucchini"] as ingredientsMATCH (d:Dish)WHERE all(i in ingredients WHERE exists( (d)-[:HAS_INGREDIENT]->(:Ingredient {name: i})))RETURN d.title AS dishORDER BY size(ingredients)LIMIT 10
Results
We could go with a salad or a fish. I think I’ll pass and skip over to node2vec for dessert.
The node2vec algorithm is relatively new. It was proposed only in the year 2016 by Jure Leskovac and Aditya Grover in an article node2vec: Scalable Feature Learning for Networks. To understand how it works, we must first understand the word2vec algorithm. Word2vec algorithm was proposed in the year 2013 by a team of researchers led by Tomas Mikolov at Google. It is a popular technique using neural networks to learn the word embedding. It takes a list of sentences as input and produces a vector or an embedding for each word that appears in the text corpus. Words with similar meanings should be closer in the embedding space. For example, apple and pear should be more similar than apple and car. There are two training algorithms for word2vec. The first method is called the continuous bag of words (CBOW), which uses the context of the word to predict a target term. The context is defined as words that appear near the target word in the text. The second method is called skip-gram. Instead of trying to predict the target word from the context, it tries to predict the context of a given term. If you want to learn more about the word2vec algorithm, there is plenty of good literature about it on the internet.
You might ask how we get from word2vec to node2vec. It is actually very straightforward. Instead of using a list of sentences as input, we use a list of random walks. This is the only difference.
Neo4j Graph Data Science library supports the random walk algorithm, which makes it very easy for us to implement the node2vec algorithm. If you need a quick refresher on how the GDS library works, you can check out my previous blog post. We will start by projecting the in-memory graph. We describe all three node labels and project relationships as undirected.
CALL gds.graph.create('all', ['Dish', 'Ingredient'], {undirected:{type:'*', orientation:'UNDIRECTED'}})
Now we are ready to train our first node2vec model. The process will consist of three parts:
Execute the random walk algorithm starting from each node in the graphFeed the random walks to word2vec algorithmInspect results by looking at the most similar neighbors
Execute the random walk algorithm starting from each node in the graph
Feed the random walks to word2vec algorithm
Inspect results by looking at the most similar neighbors
The random walk algorithm has an optional start parameter, which can be used to define the starting node of the walk. We can also specify how long the walk should be with the steps setting and how many times it should be repeated with the walks parameter. Note that every time random walk is executed, we expect a different result.
We will use the Word2vec algorithm implementation in the gensim library. It also has a couple of hyperparameters we can define. Most notable are:
size: Dimensionality of the embedding vectors
window: Maximum distance between the current and predicted word
min_count: The minimum count of words to consider when training the model; words with occurrence less than this count will be ignored.
sg: The training algorithm: 1 for skip-gram; otherwise default CBOW
Check out the official documentation for more information about the word2vec hyperparameters
Results
[('anchovy fillet', 0.6236759424209595), ('pork shoulder roast', 0.6039043068885803), ('penne', 0.5999650955200195), ('cherry', 0.5930663347244263), ('cooked quinoa', 0.5898399353027344), ('turkey', 0.5864514112472534), ('asiago cheese', 0.5858502388000488), ('pasillas', 0.5852196216583252), ('fresh marjoram', 0.5819133520126343), ('prunes', 0.5735701322555542)]
If I knew it was that easy, I would have written about the node2vec algorithm before. On the other hand, the results smell kind of fishy. I have no idea what is it with this dataset and anchovies. It seems like the recipes were mostly written by someone who really likes them. You will probably get quite different results though.
In the original node2vec paper, the authors defined two parameters that control the random walks execution. The first one is the return parameter.
Return parameter, p. Parameter p controls the likelihood of immediately revisiting a node in the walk. Setting it to a high value (> max(q, 1)) ensures that we are less likely to sample an already visited node in the following two steps (unless the next node in the walk had no other neighbor). This strategy encourages moderate exploration and avoids 2-hop redundancy in sampling. On the other hand, if p is low (< min(q, 1)), it would lead the walk to backtrack a step (Figure 2) and this would keep the walk “local” close to the starting node u.
And the second parameter is called the in-out parameter.
In-out parameter, q. Parameter q allows the search to differentiate between “inward” and “outward” nodes. Going back to Figure 2, if q > 1, the random walk is biased towards nodes close to node t. Such walks obtain a local view of the underlying graph with respect to the start node in the walk and approximate BFS behavior in the sense that our samples comprise of nodes within a small locality. In contrast, if q < 1, the walk is more inclined to visit nodes which are further away from the node t. Such behavior is reflective of DFS which encourages outward exploration. However, an essential difference here is that we achieve DFS-like exploration within the random walk framework. Hence, the sampled nodes are not at strictly increasing distances from a given source node u, but in turn, we benefit from tractable preprocessing and superior sampling efficiency of random walks. Note that by setting πv,x to be a function of the preceeding node in the walk t, the random walks are 2nd order Markovian.
In summary, the return parameter directs how often random walk backtracks a step or two. The in-out parameter controls if the random walk is more focused on local exploration, similar to BFS, or inclined more towards outward exploration like the DFS. Even though the random walk algorithm is still in the alpha tier, it supports these two node2vec parameters. Let’s try them out in practice.
Results
[('leg of lamb', 0.7168825268745422), ('anise seeds', 0.6833588480949402), ('basic bruschetta', 0.6759517192840576), ('dried chilli flakes', 0.6719993352890015), ('tuna in olive oil', 0.6697120666503906), ('spaghetti pasta', 0.669307291507721), ('prime rib roast', 0.661544919013977), ('baby artichokes', 0.6588324308395386), ('rice vermicelli', 0.6581511497497559), ('whole wheat fusilli', 0.6571477651596069)]
Looking at results makes me hungry. It is really hard to say if the leg of lamb and olive oil should be regarded as similar ingredients. If we inspect the graph, out of eight recipes that include the leg of lamb, seven of those also use olive oil. By this logic, they are quite similar.
In our next example, we will show how to run the node2vec algorithm and store the result embeddings back to Neo4j. Instead of returning the titles of dishes and ingredients, we will return the internal Neo4j node ids. This will help us to link the results back to Neo4j efficiently.
The embeddings are now available in the vocabulary of the word2vec model. We will store them to Neo4j in a single batch using the UNWIND cypher statement. If possible, try to avoid committing a single transaction per row as this is not very performant.
Word2vec model uses the cosine similarity to find the most similar words. The Graph Data Science library also supports the Cosine similarity algorithm, which can be used to infer a similarity algorithm. As with all similarity algorithms, we have to fine-tune the similarityCutoff and topK parameters to get the best results. They directly influence how sparse the inferred similarity graph will be.
MATCH (node) WITH id(node) as id, node.embedding as weights WITH {item:id, weights: weights} as dishData WITH collect(dishData) as data CALL gds.alpha.similarity.cosine.write({ nodeProjection: '*', relationshipProjection: '*', similarityCutoff:0.5, topK:5, data: data, writeRelationshipType:'COSINE_SIMILARITY'}) YIELD nodes, similarityPairs RETURN nodes, similarityPairs
Results
To finish this analysis, we will inspect the community structure of the inferred network with the label propagation algorithm. As we are only interested in a rough outline of the community structure, we can use the stats mode of the algorithm to provide us some basic community structure statistics.
CALL gds.labelPropagation.stats({ nodeProjection:'*', relationshipProjection:'COSINE_SIMILARITY', maxIterations:20}) YIELD communityCount, communityDistributionRETURN communityCount, apoc.math.round(communityDistribution.p50,2) as p50, apoc.math.round(communityDistribution.p75,2) as p75, apoc.math.round(communityDistribution.p90,2) as p90, apoc.math.round(communityDistribution.p90,2) as p95, apoc.math.round(communityDistribution.mean,2) as mean, apoc.math.round(communityDistribution.max,2) as max
Results
The label propagation algorithm found 118 groups in the similarity network. Most of them have less than 40 members. There are a handful of massive communities with the largest containing 393 members.
The node2vec algorithm is a useful way of learning low-dimensional representations of the nodes in a graph that can be used downstream in a machine learning pipeline. During this blog post, I realized that changing the random walk algorithm parameters as well as the word2vec hyperparameters can produce very different results. Play around with them and see what works best for you.
As always, the code is available on GitHub. | [
{
"code": null,
"e": 469,
"s": 47,
"text": "My last blog post about combining graphs with NLP techniques was the most successful by far. It motivated me to write more about this topic. During my research, I stumbled upon the node2vec algorithm and noticed how easy it would be to implement it with Ne... |
Spring Autowiring 'byType' | This mode specifies autowiring by property type. Spring container looks at the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.
For example, if a bean definition is set to autowire byType in the configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept where you will find no difference with the above example except XML configuration file has been changed.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ) {
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Following is the content of another dependent class file SpellChecker.java −
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml in normal condition −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
<property name = "spellChecker" ref = "spellChecker" />
<property name = "name" value = "Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
But if you are going to use autowiring 'byType', then your XML configuration file will become as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byType">
<property name = "name" value = "Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "SpellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Inside SpellChecker constructor.
Inside checkSpelling.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2666,
"s": 2292,
"text": "This mode specifies autowiring by property type. Spring container looks at the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans... |
How to detect a mobile device in jQuery? - GeeksforGeeks | 16 Apr, 2019
We can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and easiest way to detect mobile devices.
Syntax:
window.matchMedia();
Example-1: Program run on desktop.
<!DOCTYPE html><html lang="en"> <head> <title> jQuery Detect Mobile Device </title></head> <body> <script> if (window.matchMedia("(max-width: 767px)").matches) { // The viewport is less than 768 pixels wide document.write("This is a mobile device."); } else { // The viewport is at least 768 pixels wide document.write("This is a tablet or desktop."); } </script></body> </html>
Output:
Example-2: Program run on mobile device.
<!DOCTYPE html><html lang="en"> <head> <title> jQuery Detect Mobile Device </title></head> <body> <script> if (window.matchMedia("(max-width: 767px)").matches) { // The viewport is less than 768 pixels wide document.write("This is a mobile device."); } else { // The viewport is at least 768 pixels wide document.write("This is a tablet or desktop."); } </script></body> </html>
Output:
Supported Browsers:
Google Chrome
Mozilla Firefox
Opera
Edge
Safari
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers | [
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 24882,
"s": 24718,
"text": "We can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and easiest way to detect mobile devices.... |
Console.Clear Method in C# - GeeksforGeeks | 29 Jan, 2019
This method is used to clear the console buffer and corresponding console window of display information.
Syntax: public static void Clear ();
Exceptions: This method throws IOException if an I/O error occurred.
Below programs show the use of Console.Clear() method:
Program 1: To display the contents before the use of Clear method
// C# program to illustrate the use// of Console.Clear Method using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Print the statements Console.WriteLine("GeeksForGeeks"); Console.WriteLine("A Computer Science Portal"); Console.WriteLine("For Geeks"); }}}
GeeksForGeeks
A Computer Science Portal
For Geeks
Program 2: Use clear() method to clear the console
// C# program to illustrate the use// of Console.Clear Method using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Print the statements Console.WriteLine("GeeksForGeeks"); Console.WriteLine("A Computer Science Portal"); Console.WriteLine("For Geeks"); // Clear the Console Console.Clear(); }}}
CSharp-Console-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n29 Jan, 2019"
},
{
"code": null,
"e": 24407,
"s": 24302,
"text": "This method is used to clear the console buffer and corresponding console window of display information."
},
{
"code": null,
"e": 24444,
"s": 24407... |
Python’s geocoding — Convert a list of addresses into a map | by Vaclav Dekanovsky | Towards Data Science | Every one of us has a database of clients with addresses, a list of factories or stores, regions we sell our products to or cooperate with. Displaying these data on a map is a must in the modern dashboards. In order to do so, we have to transform the addresses (city names or regions) into geospatial data — latitudes and longitudes. Then we can present them on compelling maps.
What will you learn
In this tutorial, we will explore how to:
choose the ideal mapping service
connect to the API using requests (old-fashioned way)
get locations (and more) with Python’s geopy library
convert a list of addresses into geopoints
display the collected data on a map with folium and plotly
save the map into .html file
You can follow along with me using this jupyter notebook downloadable from Github - Address to Location.ipynb.
To transform addresses into coordinates you can either buy a database of addresses with the geographical position or you have to query some geolocation service provider. Anyone who offers maps usually provides a geolocation API (often for a price). Let’s review some of the major providers:
Google Maps Platform
Mapbox API
Bing API
Nominatim, OpenStreetMap API — (free)
Yandex Map API
This article review some of the major providers:
medium.com
Most APIs allow direct calls. You send your address to an URL and receive the geolocation. For years we use python requests library to do it. Let’s explore requests to Google API.
To connect to Google API you need an API key. You have to ask for it (guideline) and then keep secret, because you pay for the service. Google gives $200 free each month which is enough to do 40000 geocoding requests.
Geocoding calls are usually quite simple:
Base address: https://maps.googleapis.com/maps/api/geocode/json?Parameters: # blank spaces are turned to %20 address=1 Apple Park Way, Cupertino, CA key=API_KEY
You prepare the data you want to search for. With the help of urllib you easily turn parameters into an URL and you call requests.get(). The response is either XML, but more often a json which you process by json.loads
import requests
import json
import urllib
# https://developers.google.com/maps/documentation/geocoding/intro
base_url= "https://maps.googleapis.com/maps/api/geocode/json?"
AUTH_KEY = "Your Key"
# set up your search parameters - address and API key
parameters = {"address": "Tuscany, Italy",
"key": AUTH_KEY}
# urllib.parse.urlencode turns parameters into url
print(f"{base_url}{urllib.parse.urlencode(parameters)}")
https://maps.googleapis.com/maps/api/geocode/json?address=Tuscany%2C+Italy&key=Your+Key
r = requests.get(f"{base_url}{urllib.parse.urlencode(parameters)}")
data = json.loads(r.content)
data
{'results': [{'address_components': [{'long_name': 'Tuscany',
'short_name': 'Tuscany',
'types': ['administrative_area_level_1', 'political']},
{'long_name': 'Italy',
'short_name': 'IT',
'types': ['country', 'political']}],
'formatted_address': 'Tuscany, Italy',
'geometry': {'bounds': {'northeast': {'lat': 44.4726899, 'lng': 12.3713555},
'southwest': {'lat': 42.2376686, 'lng': 9.6867213}},
'location': {'lat': 43.7710513, 'lng': 11.2486208},
'location_type': 'APPROXIMATE',
'viewport': {'northeast': {'lat': 44.4726899, 'lng': 12.3713555},
'southwest': {'lat': 42.2376686, 'lng': 9.6867213}}},
'place_id': 'ChIJezSAEFMr1BIRq1kgW7rDxro',
'types': ['administrative_area_level_1', 'political']}],
'status': 'OK'}
data.get("results")[0].get("geometry").get("location")
{'lat': 43.7710513, 'lng': 11.2486208}
You can struggle with the documentation of mapping provider API to get the most of it, but it is easier to take advantage of an existing library like GeoPy. With Geopy you can do the same as above with only a few lines of code.
Geopy provides a class for popular mapping services. Nominatim is the service behind the popular OpenStreetMap that allows you to geocode for free. But you should comply with the usage policies in order to allow everyone to use it:
As a general rule, bulk geocoding of larger amounts of data is not encouraged. smaller one-time bulk tasks may be permissible, if these additional rules are followed
limit your requests to a single thread
limited to 1 machine only, no distributed scripts (including multiple Amazon EC2 instances or similar)
Results must be cached on your side. Clients sending repeatedly the same query may be classified as faulty and blocked.
Do you have a small project or just want to impress your boss? Let’s geocode with Geopy.Nominatim. First, we initialize Nominatim into geolocator variable:
from geopy.geocoders import Nominatimgeolocator = Nominatim(user_agent="example app")
Then you request information about a region, I’ve picked Tuscany in Italy:
[In]: geolocator.geocode("Tuscany, Italy").raw[Out]: {'place_id': 232933113, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'osm_type': 'relation', 'osm_id': 41977, 'boundingbox': ['42.237615', '44.4725419', '9.6867692', '12.3713544'], 'lat': '43.4586541', 'lon': '11.1389204', 'display_name': 'Toscana, Italia', 'class': 'boundary', 'type': 'administrative', 'importance': 0.6870417219974091, 'icon': 'https://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png'}
From the response, you can get the latitude and the longitude
[In]: geolocator.geocode("Tuscany, Italy").point[Out]: Point(43.4586541, 11.1389204, 0.0)
Similarly, you can request geolocation from a full address, for example, the headquarter of Apple.
# request geolocator.geocode("1 Apple Park Way, Cupertino, CA")# extract the coordinates:('37.3337572', '-122.0113815')
Geopy allow geocode operation to turn an address into the coordinates and the opposite reverse to turn the locations into an address:
[In]: geolocator.reverse('37.3337572, -122.0113815')[Out]: Location(Apple Park, 1, Apple Park Way, Monta Vista, Cupertino, Santa Clara County, California, 94087, United States of America, (37.3348469, -122.01139215737962, 0.0))
# https://geopy.readthedocs.io/en/stable/
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="sample app")
data = geolocator.geocode("1 Apple Park Way, Cupertino, CA")
Extracting the data from the raw response can be tidious, because each provider return different data struture
data.raw.get("lat"), data.raw.get("lon")
('37.3337572', '-122.0113815')
using the .point, .point.latitude and .point.longitude makes it easy no matter what provider you are asking. The third tribute is altitude.
data.point
Point(37.3337572, -122.0113815, 0.0)
data.point.latitude, data.point.longitude
(37.3337572, -122.0113815)
.reverse helps you find the address based on the geolocation
geolocator.reverse('37.3337572, -122.0113815')
Location(Apple Park, 1, Apple Park Way, Monta Vista, Cupertino, Santa Clara County, California, 94087, United States of America, (37.3348469, -122.01139215737962, 0.0))
You can use many map services with Geopy, only you will have to provide an API key or user credentials. For example, using Google Maps API:
geolocator = GoogleV3(api_key=AUTH_KEY)
Requesting the geolocation uses the same code as above:
[In]: geolocator.geocode("1 Apple Park Way, Cupertino, CA").point[Out]: Point(37.3337572, -122.0113815, 0.0)
Though the structure of the response JSON will reflect the service used. Lat and Lon in the Google response are stored in the "geometry"."location" . But Geopy did the work for you and you just read the .point attribute.
Before you can display a dataset with addresses on a map you need to find the geolocations of these points. Let’s have a look at this shortlist of addresses:
data = """Name,AddressEU,"Rue de la Loi/Wetstraat 175, Brussel, Belgium"Apple,"1 Apple Park Way, Cupertino, CA"Google,"1600 Amphitheatre Parkway Mountain View, CA 94043"UN,"760 United Nations Plaza; Manhattan, New York City""""
We know that we can use GeoPy’s geolocator.geocode but what is the most effective way of turning a pandas dataFrame to coordinates. I like the approach of Abdishakur describes in this article
towardsdatascience.com
I’ll create a pandas dataFrame from our list
I’ll create a pandas dataFrame from our list
df = pd.read_csv(io.StringIO(data))df
2. Apply geolocator.geocode to the address column
df["loc"] = df["Address"].apply(geolocator.geocode)
3. Get .point containing latitude and longitude from the geocode’s response, if it’s not None.
df["point"]= df["loc"].apply(lambda loc: tuple(loc.point) if loc else None)
4. Split the .point into separate columns 'lat' 'lon' and 'altitude'
df[['lat', 'lon', 'altitude']] = pd.DataFrame(df['point'].to_list(), index=df.index)
Having 'lat' and 'loc' columns in the dataset is sufficient to display the points on any background map.
The geographical coordinates are useless unless you display them on a map. Python offers several libraries to make this task easy enough as well.
folium library, using leaflet.js to create a typical map on the top of OpenStreetMap or any other map data provider
plotly using its inherent map data
Folium maps are interactive, they contain markers with popups that can be clustered in areas with a high density of points, you can use layers and pick different source maps. And it’s all pretty easy to code:
# import the library and its Marker clusterization serviceimport foliumfrom folium.plugins import MarkerCluster# Create a map object and center it to the avarage coordinates to mm = folium.Map(location=df[["lat", "lon"]].mean().to_list(), zoom_start=2)# if the points are too close to each other, cluster them, create a cluster overlay with MarkerCluster, add to mmarker_cluster = MarkerCluster().add_to(m)# draw the markers and assign popup and hover texts# add the markers the the cluster layers so that they are automatically clusteredfor i,r in df.iterrows(): location = (r["lat"], r["lon"]) folium.Marker(location=location, popup = r['Name'], tooltip=r['Name'])\ .add_to(marker_cluster)# display the mapm
Plotly is gaining more and more popularity. Since it has introduced the Plotly express interface, creating a chart is a single liner and that applies to map charts as well. Let’s have a look at how to create a similar map with Plotly.
# import the plotly expressimport plotly.express as px# set up the chart from the df dataFramefig = px.scatter_geo(df, # longitude is taken from the df["lon"] columns and latitude from df["lat"] lon="lon", lat="lat", # choose the map chart's projection projection="natural earth", # columns which is in bold in the pop up hover_name = "Name", # format of the popup not to display these columns' data hover_data = {"Name":False, "lon": False, "lat": False } )
.scatter_geo(df) creates the points on the map based on the data in the df dataFrame, like position or popups. We can set different size or color for each data point, but we didn’t do that in df dataFrame, so we can specify the same for all using .update_traces() .
fig.update_traces(marker=dict(size=25, color="red"))
You don’t have to determine the ideal zoom like in folium, but you just set fitbounds to ‘locations’. You can also show countries, rivers, oceans, lakes and specify their color with .update_geos .
fig.update_geos(fitbounds="locations", showcountries = True)
Finally, let’s add a title using .update_layout and display the final chart-map by fig.show() .
fig.update_layout(title = "Your customers")fig.show()
Admiring the map in the notebook can be satisfying, but occasionally you want to share your work with people who don't have python installed. Luckily exporting the map into .html is only one line of code.
Folium’s .save method creates a file that gets all the necessary resources like jquery, bootstrap, leaflet from CDN and the file has only 8 KB.
m.save("folium_map.html")
Plotly works with .write_html command which has a few optional parameters. The most important is include_plotlyjs . You can set if the output file will contain over 3 MB of plotly library which allows those beautiful chart effects or whether you want only your data points which can be included in another plotly project. In the second case, the size will be 9 KB.
fig.write_html("plotly_map.html", include_plotlyjs=True)
Displaying data on a map can be an effective way of how to present the company’s data. Python’s libraries help us to quickly gather the necessary geospatial data and use them to plot the maps. You can use open-source data or paid services to achieve this task.
Do you search for more inspiration, try plotly and folium map galleries
plotly.com
nbviewer.jupyter.org
Did you like this tutorial, check my other articles dealing with various data-related topics: | [
{
"code": null,
"e": 551,
"s": 172,
"text": "Every one of us has a database of clients with addresses, a list of factories or stores, regions we sell our products to or cooperate with. Displaying these data on a map is a must in the modern dashboards. In order to do so, we have to transform the addr... |
Automating Hyperparameter Tuning of Keras Model | by Himanshu Sharma | Towards Data Science | Building a model is of no use if you cannot optimize it for a good performance and a higher accuracy. Generally, the model building requires less time than optimizing that model, because during optimization or tuning the model you need to look out for the best parameters which is a time-consuming process.
We can automate this process of finding out the best values for the hyperparameters and getting the highest accuracy of the Keras model. In this article, we will be discussing Hyperas which is an open-source python package used for automating the process of Keras Model Hyperparameter Tuning.
Let’s get started......
Like any other python library, we will use pip installation to install hyperas. Before installation, we need to run a command which is required to avoid errors at a later stage, make sure this command is the first code that you run while building this.
from __future__ import print_function!pip install hyperas
In order to run hyperas, we need to change certain settings and also we will use a file named exactly the same as our collab notebook i.e if my collab notebook is named Hyperas.ipynb then in the below code, I will use Hyperas.ipynb as the file name.
!pip install -U -q PyDrivefrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials# Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)# Copy/download the filefid = drive.ListFile({'q':"title='Hyperas.ipynb'"}).GetList()[0]['id']f = drive.CreateFile({'id': fid})f.GetContentFile('Hyperas.ipynb')
Next, we will import all the required dependencies for this article.
import numpy as npfrom hyperopt import Trials, STATUS_OK, tpefrom keras.datasets import mnistfrom keras.layers.core import Dense, Dropout, Activationfrom keras.models import Sequentialfrom keras.utils import np_utilsfrom hyperas import optimfrom hyperas.distributions import choice, uniform
In this step, we will create two functions that will help us in loading the data and creating the model respectively.
def data(): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 nb_classes = 10 y_train = np_utils.to_categorical(y_train, nb_classes) y_test = np_utils.to_categorical(y_test, nb_classes) return x_train, y_train, x_test, y_test
def create_model(x_train, y_train, x_test, y_test): model = Sequential() model.add(Dense(512, input_shape=(784,))) model.add(Activation('relu')) model.add(Dropout({{uniform(0, 1)}})) model.add(Dense({{choice([256, 512, 1024])}})) model.add(Activation({{choice(['relu', 'sigmoid'])}})) model.add(Dropout({{uniform(0, 1)}})) if {{choice(['three', 'four'])}} == 'four': model.add(Dense(100))model.add({{choice([Dropout(0.5), Activation('linear')])}}) model.add(Activation('relu'))model.add(Dense(10)) model.add(Activation('softmax'))model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer={{choice(['rmsprop', 'adam', 'sgd'])}})result = model.fit(x_train, y_train, batch_size={{choice([64, 128])}}, epochs=2, verbose=2, validation_split=0.1) #get the highest validation accuracy of the training epochs validation_acc = np.amax(result.history['val_accuracy']) print('Best validation acc of epoch:', validation_acc) return {'loss': -validation_acc, 'status': STATUS_OK, 'model': model}
This is the final step where we will use hyperas and find out the best parameters and highest accuracy.
if __name__ == '__main__': best_run, best_model = optim.minimize(model=create_model, data=data, algo=tpe.suggest, max_evals=5, trials=Trials(), notebook_name='Hyperas') X_train, Y_train, X_test, Y_test = data() print("Evalutation of best performing model:") print(best_model.evaluate(X_test, Y_test)) print("Best performing model chosen hyper-parameters:") print(best_run)
Here you can clearly analyze how hyperas displayed the best performing hyperparameters along with the accuracy of the model. This is easy and can save time and effort.
Go ahead try this and let me know your experiences in the response section.
This article is in collaboration with Piyush Ingale
Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 479,
"s": 172,
"text": "Building a model is of no use if you cannot optimize it for a good performance and a higher accuracy. Generally, the model building requires less time than optimizing that model, because during optimization or tuning the model you need to look out for the... |
Affinity Propagation Algorithm Explained | by Cory Maklin | Towards Data Science | Affinity Propagation was first published in 2007 by Brendan Frey and Delbert Dueck in Science. In contrast to other traditional clustering methods, Affinity Propagation does not require you to specify the number of clusters. In layman’s terms, in Affinity Propagation, each data point sends messages to all other points informing its targets of each target’s relative attractiveness to the sender. Each target then responds to all senders with a reply informing each sender of its availability to associate with the sender, given the attractiveness of the messages that it has received from all other senders. Senders reply to the targets with messages informing each target of the target’s revised relative attractiveness to the sender, given the availability messages it has received from all targets. The message-passing procedure proceeds until a consensus is reached. Once the sender is associated with one of its targets, that target becomes the point’s exemplar. All points with the same exemplar are placed in the same cluster.
Suppose that we had the following dataset. Each of the participants is represented as a data point in a 5 dimensional space.
Barring those on the diagonal, every cell in the similarity matrix is calculated by negating the sum of the squares of the differences between participants.
If that didn’t make any sense to you, don’t fret, it will become clear once go walk through an example. For the similarity between Alice and Bob, the sum of the squares of the differences is (3–4)2 + (4–3)2 + (3–5)2 + (2–1)2 + (1–1)2 = 7. Thus, the similarity value is -7.
Still not clear? Let’s look at another example.
I highly recommend calculated a few of these yourself. You should end up with something close to the following table.
The algorithm will converge around a small number of clusters if a smaller value is chosen for the diagonal, and vice versa. Therefore, we fill in the diagonal elements of the similarity matrix with -22, the lowest number from among the different cells.
We start off by constructing an availability matrix with all elements set to zero. Then, we calculate every cell in the responsibility matrix using the following formula:
where i refers to the row and k the column of the associated matrix.
For example, the responsibility of Bob (column) to Alice (row) is -1, which is the similarity of Bob to Alice (-7) minus the maximum of the remaining similarities of Alice’s row (-6).
Again, I highly recommend you try calculating a few of these yourself.
After calculating the responsibilities for the rest of the pairs of participants, we end up with the following matrix.
We use a separate equation for updating the elements on the diagonal of the availability matrix than we do the elements off the diagonal of the availability matrix.
The proceeding formula is used to fill in the elements on the diagonal:
where i refers to the row and k the column of the associated matrix.
In essence, the equation is telling you to sum all the values above 0 along the column except for the row whose value is equal to the column in question. For example, the self-availability of Alice is the sum of the positive responsibilities of Alice’s column excluding Alice’s self-responsibility (10 + 11 + 0 + 0 = 21).
Still don’t understand? Let’s go over a couple more examples.
The following equation is used to update off-diagonal elements:
In other words, say you’re trying to fill in a(Cary, Edna). Considering the elements along Edna’s column, you exclude the Edna/Edna relationship and the Cary/Edna relationship and sum all the remaining positive responsibilities together. For example, the availability of Bob (column) to Alice (row) is Bob’s self-responsibility plus the sum of the remaining positive responsibilities of Bob’s column excluding the responsibility of Bob to Alice (-15 + 0 + 0 + 0 = -15).
I highly recommend you try calculating a few cells yourself.
After calculating the rest, we wind up with the following availability matrix.
Each cell in the criterion matrix is simply the sum of the availability matrix and responsibility matrix at that location.
The criterion value of Bob (column) to Alice (row) is the sum of the responsibility and availability of Bob to Alice (-1 + -15 = -16).
The highest criterion value of each row is designated as the exemplar. Rows that share the same exemplar are in the same cluster. Thus, in our example. Alice, Bob, and Cary form one cluster whereas Doug and Edna constitute the second.
It’s worth noting that in this example, the variables ranged over the same scale. In general, however, variables are on different scales and must be normalized prior to training.
Let’s jump into some code. To start, import the following libraries.
import numpy as npfrom matplotlib import pyplot as pltimport seaborn as snssns.set()from sklearn.datasets.samples_generator import make_blobsfrom sklearn.cluster import AffinityPropagation
We use scikit-learn to generate data with nicely defined clusters.
X, clusters = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)plt.scatter(X[:,0], X[:,1], alpha=0.7, edgecolors='b')
Next, we initialize and train our model.
af = AffinityPropagation(preference=-50)clustering = af.fit(X)
Finally, we plot the data points using a different color for each cluster.
plt.scatter(X[:,0], X[:,1], c=clustering.labels_, cmap='rainbow', alpha=0.7, edgecolors='b')
Affinity Propagation is an unsupervised machine learning algorithm that is particularly well suited for problems where we don’t know the optimal number of clusters. | [
{
"code": null,
"e": 1207,
"s": 171,
"text": "Affinity Propagation was first published in 2007 by Brendan Frey and Delbert Dueck in Science. In contrast to other traditional clustering methods, Affinity Propagation does not require you to specify the number of clusters. In layman’s terms, in Affinit... |
How to create JavaScript alert with 3 buttons (Yes, No and Cancel)? | The standard JavaScript alert box won’t work if you want to customize it. For that, we have a custom alert box, which we’re creating using jQuery and styled with CSS.
You can try to run the following code to create an alert box with 3 buttons i.e Yes, No and Cancel.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionConfirm(msg, myYes, myNo, cancel) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no,.cancel").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.find(".no").click(cancel);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #91FF00;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message"></div>
<button class="yes">Yes</button>
<button class="no">No</button>
<button class="cancel">Cancel</button>
</div>
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
}, function no() {
alert("no")
}
);'>submit</button>
</body>
</html> | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "The standard JavaScript alert box won’t work if you want to customize it. For that, we have a custom alert box, which we’re creating using jQuery and styled with CSS."
},
{
"code": null,
"e": 1329,
"s": 1229,
"text": "You can try to ... |
C++ Program for Longest Common Subsequence - GeeksforGeeks | 04 Dec, 2018
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program that outputs the differences between two files), and has applications in bioinformatics.
Examples:LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).
If last characters of both sequences match (or X[m-1] == Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
If last characters of both sequences do not match (or X[m-1] != Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])
/* A Naive recursive implementation of LCS problem */#include <bits/stdc++.h> int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */int lcs(char* X, char* Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));} /* Utility function to get max of 2 integers */int max(int a, int b){ return (a > b) ? a : b;} /* Driver program to test above function */int main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %d\n", lcs(X, Y, m, n)); return 0;}
Length of LCS is 4
Following is a tabulated implementation for the LCS problem.
/* Dynamic Programming C/C++ implementation of LCS problem */#include <bits/stdc++.h> int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} /* Utility function to get max of 2 integers */int max(int a, int b){ return (a > b) ? a : b;} /* Driver program to test above function */int main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %d\n", lcs(X, Y, m, n)); return 0;}
Length of LCS is 4
Please refer complete article on Dynamic Programming | Set 4 (Longest Common Subsequence) for more details!
LCS
C++ Programs
Dynamic Programming
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23 | [
{
"code": null,
"e": 24632,
"s": 24604,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24995,
"s": 24632,
"text": "LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same re... |
Sort Correlation Matrix in Python - GeeksforGeeks | 26 Dec, 2020
Prerequisites: correlation matrix
A correlation matrix investigates the dependence between multiple variables at the same time. It shows symmetric tabular data where each row and column represent a variable, and the corresponding value is the correlation coefficient denoting the strength of a relationship between these two variables. There are many types of correlation coefficients (Pearson’s coefficient, Kendall’s coefficient, Spearman’s coefficient, etc.) which are computed by different methods of correlation analysis. The variables with correlation coefficient values closer to 1 show a strong positive correlation, the values closer to -1 show a strong negative correlation, and the values closer to 0 show weak or no correlation.
In data analysis, a correlation matrix is highly useful for summarizing and spotting relations in large amounts of data. It is also a common metric for exploratory data analysis and feature selection in machine learning.
Interpreting a correlation matrix can become difficult with large data. Sometimes sorting the correlation values helps to see the degree of dependence of various variable pairs easily. In this article, we will see how to sort a correlation matrix in Python.
Import module
Load data
Create a correlation matrix using the above data
Sort the data.
Display sorted data
We will use the Iris data set from Python’s Seaborn package. The data set contains 3 classes of a type of iris flower having 50 instances of their attributes each. Note that a correlation matrix ignores any non-numeric column in the data. So, first change any non-numeric data that you want to include in your correlation matrix to numeric data using label encoding.
Now, to sort the correlation matrix, first we have to convert the matrix to one-dimensional series. The unstack() function is used to do so. The series will have multiple index.
For sorting sort_values() function is used. The sort_values() function sorts a data frame in Ascending or Descending order of passed Column.
Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Parameters:
by: Single/List of column names to sort Data Frame by.
axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column
ascending: Boolean value which sorts Data frame in ascending order if True
inplace: Boolean value. Makes the changes in passed data frame itself if True.
kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame.
na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
Return type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame.
Dataframe in use:
Example 1:
Python3
# Import required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Load dataset
df = sns.load_dataset('iris')
# Convert categorical values to numeric
label_encoder = LabelEncoder()
df['species'] = label_encoder.fit_transform(df['species'])
# Create correlation matrix
corr_mat = df.corr(method='pearson')
# Convert correlation matrix to 1-D Series and sort
sorted_mat = corr_mat.unstack().sort_values()
print(sorted_mat)
Output:
Example 2: Sort correlation matrix without duplicates
In order to remove duplicate and self-correlation values, get the upper or lower triangular values of the matrix before converting the correlation matrix to one-dimensional series. For this purpose triu() function is used which returns an upper triangular matrix with the shape of the correlation matrix (Value 1 for elements above the main diagonal and 0 for others). The method astype() converts the matrix values to boolean. This is where the function can select arrays based on another conditional array so the result we get is a matrix with upper triangular values of the correlation matrix and the remaining values are null.
Then the correlation matrix is converted to the one-dimensional array to be sorted as done in the example above. Implementation is given below:
Python3
# Import required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Load dataset
df = sns.load_dataset('iris')
# Convert categorical values to numeric
label_encoder = LabelEncoder()
df['species'] = label_encoder.fit_transform(df['species'])
# Create correlation matrix
corr_mat = df.corr(method='pearson')
# Retain upper triangular values of correlation matrix and
# make Lower triangular values Null
upper_corr_mat = corr_mat.where(
np.triu(np.ones(corr_mat.shape), k=1).astype(np.bool))
# Convert to 1-D series and drop Null values
unique_corr_pairs = upper_corr_mat.unstack().dropna()
# Sort correlation pairs
sorted_mat = unique_corr_pairs.sort_values()
print(sorted_mat)
Output:
Picked
Python-numpy
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions | [
{
"code": null,
"e": 23973,
"s": 23942,
"text": " \n26 Dec, 2020\n"
},
{
"code": null,
"e": 24007,
"s": 23973,
"text": "Prerequisites: correlation matrix"
},
{
"code": null,
"e": 24715,
"s": 24007,
"text": "A correlation matrix investigates the dependence betw... |
Using class to implement Vector Quantities in C++ | In this tutorial, we will be discussing a program to understand how to use class to implement vector quantities in C++.
Vector quantities are the ones which have both magnitude and direction. Here we will be implementing them using classes and then performing basic operations on them.
Live Demo
#include <cmath>
#include <iostream>
using namespace std;
class Vector {
private:
int x, y, z;
//components of the Vector
public:
Vector(int x, int y, int z){
this->x = x;
this->y = y;
this->z = z;
}
Vector operator+(Vector v);
Vector operator-(Vector v);
int operator^(Vector v);
Vector operator*(Vector v);
float magnitude(){
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
}
friend ostream& operator<<(ostream& out, const Vector& v);
//outputting the vector
};
// Addition of vectors
Vector Vector::operator+(Vector v){
int x1, y1, z1;
x1 = x + v.x;
y1 = y + v.y;
z1 = z + v.z;
return Vector(x1, y1, z1);
}
// Subtraction of vectors
Vector Vector::operator-(Vector v){
int x1, y1, z1;
x1 = x - v.x;
y1 = y - v.y;
z1 = z - v.z;
return Vector(x1, y1, z1);
}
// Dot product of vectors
int Vector::operator^(Vector v){
int x1, y1, z1;
x1 = x * v.x;
y1 = y * v.y;
z1 = z * v.z;
return (x1 + y1 + z1);
}
// Cross product of vectors
Vector Vector::operator*(Vector v){
int x1, y1, z1;
x1 = y * v.z - z * v.y;
y1 = z * v.x - x * v.z;
z1 = x * v.y - y * v.x;
return Vector(x1, y1, z1);
}
ostream& operator<<(ostream& out, const Vector& v){
out << v.x << "i ";
if (v.y >= 0)
out << "+ ";
out << v.y << "j ";
if (v.z >= 0)
out << "+ ";
out << v.z << "k" << endl;
return out;
}
int main(){
Vector V1(3, 4, 2), V2(6, 3, 9);
cout << "V1 = " << V1;
cout << "V2 = " << V2;
cout << "V1 + V2 = " << (V1 + V2);
cout << "Dot Product is : " << (V1 ^ V2);
cout << "Cross Product is : " << (V1 * V2);
return 0;
}
V1 = 3i + 4j + 2k
V2 = 6i + 3j + 9k
V1 + V2 = 9i + 7j + 11k
Dot Product is : 48 Cross Product is : 30i -15j -15k | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand how to use class to implement vector quantities in C++."
},
{
"code": null,
"e": 1348,
"s": 1182,
"text": "Vector quantities are the ones which have both magnitude and d... |
5 Ways to develop a Sentiment Analyser in Machine Learning | by Satyam Kumar | Towards Data Science | Sentiment Analysis is a Natural Language Processing technique to determine the sentiment or opinion of a given text. A sentiment analysis model can predict whether a given text data is positive, negative, or neutral by extracting meaning from the natural language and assigning it to a numerical score.
There are various ways to develop or train a sentiment analysis model, in this article we will discuss 5 different ways:
Custom Trained Supervised Model
TextBlob
Word-Dictionary based model
Bert
Named Entity based Sentiment Analyzer
Sentiment analysis is used by various organizations to understand the sentiment of their customers, using reviews, social media conversations, and to more fast and accurate business decisions accordingly.
You can train a custom machine learning or deep learning sentiment analysis model. A Labeled dataset is the key requirement to train a robust ML model. The ML model will learn various patterns in the dataset and can predict sentiment for given unseen text.
To train a custom sentiment analysis model, one must follow the following steps:
Collect raw labeled dataset for sentiment analysis.
Preprocessing of text
Numerical Encoding of text
Choosing the appropriate ML algorithm
Hypertuning and Training ML model
Prediction
Read the below article, to know how to develop a movie review sentiment analysis model using the Naive Bayes classifier algorithm.
satyam-kumar.medium.com
TextBlob is an open-sourced Python library used to process textual data and allows you to specify which algorithms you want to use under the hood of its simple API. TextBlobs’s API can be used to perform tasks such as part-of-speech tagging, noun phrase extraction, classification, translation, sentiment analysis, etc.
For sentiment analysis, the TextBlob library provides two implementations:
PatternAnalyzer: (Default) Based on pattern library.
NaiveBayesAnalyzer: An NLTK classifier trained on movie review corpus.
pip install -U textblob
It involves creating an n-gram dictionary of positive and negative words from the text corpus. This method requires a labeled text corpus, and use custom python functions to create a dictionary of n-gram words for positive and negative text separately.
Custom words can be also added to the dictionary based on domain knowledge that serves as an added advantage.
In the next step, create a custom function that can use the above-formed dictionary of positive and negative words to analyze the given input text and can be classified as a positive or negative sentiment.
Each positive word present in the input text increments the sentiment score, and the negative word decrements the sentiment score.
Divide the final sentiment score with the number of words in that text to normalize the score.
A positive sentiment score ranging between 0 to 1, depicts a positive sentiment, where 1 being positive sentiment prediction with 100% confidence. Whereas, a negative sentiment score ranges between -1 to 0, where -1 being negative sentiment prediction with 100% confidence.
BERT stands for Bidirectional Encoder Representations from Transformers developed by Google, and it is a state-of-the-art ML model used for NLP tasks. To train a sentiment analysis model using BERT follow the steps:
Install Transformers Library
Load the BERT classifier and Tokenizer
Create a processed dataset
Configure and train the loaded BERT model and fine-tune its hyperparameters
Make sentiment analysis predictions
Follow the below-mentioned article for implementation of sentiment analysis model with BERT.
towardsdatascience.com
Named Entity based Sentiment Analyzer is mainly targetted towards entity or importance words. It can be also referred to as target sentiment analysis, and is more accurate and useful than the above three mentioned methods, as it only focuses on important words or entities.
The first step is to find all the named entities in the text corpus.
Apply name entity recognition on the text to find various entities such as PERSON, ORG, GPE.
Sentiment Analysis based on top named entities.
Targetted by finding sentences containing the named entities and performing sentiment analysis only on those sentences one by one.
In this article, we have discussed 5 different ways to develop a sentiment analysis model. Let us understand that no one method is a hard and fast rule to follow while developing a sentiment analysis model. It needs planning and tweaking of the algorithms according to the problem statement and dataset.
[1] BERT Wiki: https://en.wikipedia.org/wiki/BERT
[2] Sentiment Analysis using BERT by Orhan G. Yalçın: https://towardsdatascience.com/sentiment-analysis-in-10-minutes-with-bert-and-hugging-face-294e8a04b671
Thank You for Reading | [
{
"code": null,
"e": 475,
"s": 172,
"text": "Sentiment Analysis is a Natural Language Processing technique to determine the sentiment or opinion of a given text. A sentiment analysis model can predict whether a given text data is positive, negative, or neutral by extracting meaning from the natural ... |
Python | Indices of sorted list of list elements - GeeksforGeeks | 11 May, 2020
Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and moreover just require to find the order in which element occurs before getting sorted. Let’s find out how to get indices of sorted order in list of lists.
Method #1 : Using List comprehension + enumerate() + sort()
The combination of above 3 functions can be used to perform this particular task. In this, we perform the sorting taking triplets consisting of element and row and column coordinates and return them in 2nd step.
# Python3 code to demonstrate# Indices of sorted list of list elements# using List comprehension + enumerate() + sort() # initializing listtest_list = [[4, 5, 1], [9, 3, 2], [8, 6]] # printing original listprint("The original list : " + str(test_list)) # using List comprehension + enumerate() + sort()# Indices of sorted list of list elementsres = [(i, j) for i, x in enumerate(test_list) for j, k in enumerate(x)] res.sort(key = lambda ij: test_list[ij[0]][ij[1]]) # print resultprint("The indices of sorted order are : " + str(res))
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]]The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
Method #2 : Using sorted() + lambda
The task performed above can be performed as arguments to the sorted function and lambda function performs the task of list comprehension function as above.
# Python3 code to demonstrate# Indices of sorted list of list elements# using sorted() + lambda # initializing listtest_list = [[4, 5, 1], [9, 3, 2], [8, 6]] # printing original listprint("The original list : " + str(test_list)) # using sorted() + lambda# Indices of sorted list of list elementsres = sorted([(i, j) for i, x in enumerate(test_list) for j, k in enumerate(x)], key = lambda ij: test_list[ij[0]][ij[1]]) # print resultprint("The indices of sorted order are : " + str(res))
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]]The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
Python list-programs
Python-list-of-lists
Python-Sorted
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 23813,
"s": 23785,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 24127,
"s": 23813,
"text": "Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and more... |
Python – Get all numbers combinations in list | 03 Jul, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar but can have application in many domains such as day-day programming and gaming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [7, 3, 4, 5]Output : [73, 74, 75, 34, 35, 45]
Input : test_list = [2, 5]Output : [25]
Method #1 : Using list comprehension + combination()The combination of above functions can be used to solve this problem. In this, we perform the task of finding all combination using combination() and f-strings can be used to perform concatenation.
# Python3 code to demonstrate working of # All numbers combinations# Using list comprehension + combinationsfrom itertools import combinations # initializing listtest_list = [59, 236, 31, 38, 23] # printing original list print("The original list : " + str(test_list)) # All numbers combinations# Using list comprehension + combinationsres = [int(f"{x}{y}") for x, y in combinations(test_list, 2)] # printing result print("All numbers combinations : " + str(res))
The original list : [59, 236, 31, 38, 23]All numbers combinations : [59236, 5931, 5938, 5923, 23631, 23638, 23623, 3138, 3123, 3823]
Method #2 : Using loop + str() + int()The combination of above functions can be used to solve this problem. In this we perform the task of forming combinations using brute force and type conversions in nested loop. This also outputs reverse combinations.
# Python3 code to demonstrate working of # All numbers combinations# Using loop + str() + int()from itertools import combinations # initializing listtest_list = [59, 236, 31, 38, 23] # printing original list print("The original list : " + str(test_list)) # All numbers combinations# Using loop + str() + int()res = []for i in test_list: for j in test_list: if j != i: res.append(int(str(i) + str(j))) # printing result print("All numbers combinations : " + str(res))
The original list : [59, 236, 31, 38, 23]All numbers combinations : [59236, 5931, 5938, 5923, 23659, 23631, 23638, 23623, 3159, 31236, 3138, 3123, 3859, 38236, 3831, 3823, 2359, 23236, 2331, 2338]
Python list-programs
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
Introduction To PYTHON
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 Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar bu... |
Clean the string data in the given Pandas Dataframe | 26 Jan, 2019
As we know, In today’s world data analytics is being used by all sorts of companies out there. While working with data, we can come across any sort of problem which requires an out of the box approach for evaluation. Most of the Data in real life contains the name of entities or other nouns. It might be possible that the names are not in proper format. In this post, we are going to discuss the approaches to clean such data.
Suppose we are dealing with the data of an e-commerce based website. The name of the products is not in the proper format. Properly format the data such that the there are no leading and trailing whitespaces as well as the first letters of all products are capital letter.
Solution #1: Many times we will come across a situation where we are required to write our own customized function suited for the task at hand.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':[' UMbreLla', ' maTress', 'BaDmintoN ', 'Shuttle'], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 8, 15, 10]}) # Print the dataframeprint(df)
Output :
Now we will writer our own customized function to solve this problem.
def Format_data(df): # iterate over all the rows for i in range(df.shape[0]): # reassign the values to the product column # we first strip the whitespaces using strip() function # then we capitalize the first letter using capitalize() function df.iat[i, 1]= df.iat[i, 1].strip().capitalize() # Let's call the functionFormat_data(df) # Print the Dataframeprint(df)
Output :
Solution #2 : Now we will see a better and efficient approach using Pandas DataFrame.apply() function.
# importing pandas as pdimport pandas as pd # Create the dataframedf = pd.DataFrame({''Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Product':[' UMbreLla', ' maTress', 'BaDmintoN ', 'Shuttle'], 'Updated_Price':[1250, 1450, 1550, 400], 'Discount':[10, 8, 15, 10]}) # Print the dataframeprint(df)
Output :
Let’s use the Pandas DataFrame.apply() function to format the Product names in the right format. Inside the Pandas DataFrame.apply() function we will use lambda function.
# Using the df.apply() function on product columndf['Product'] = df['Product'].apply(lambda x : x.strip().capitalize()) # Print the Dataframeprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jan, 2019"
},
{
"code": null,
"e": 456,
"s": 28,
"text": "As we know, In today’s world data analytics is being used by all sorts of companies out there. While working with data, we can come across any sort of problem which requires a... |
HTML | DOM Dialog show() Method | 31 May, 2019
The DOM Dialog show() method is used to show the dialog. The Dialog element is accessed by getElementById(). It is used in HTML5.While using this method, the user can interact with other elements on the page.
Syntax:
dialogObject.show()
Example: This example shows the working of Dialog show() Method:
<!DOCTYPE html><html><body> <h3> HTML | DOM Dialog show() Method</h3><p>Click on the below buttons to show or close the dialog window.</p> <button onclick="showDialog()">Show dialog box</button> <dialog id="showDialog" style= "color:green"> Welcome to GeeksforGeeks</dialog> <script>var gfg = document.getElementById("showDialog"); function showDialog() { gfg.show(); } </script> </body></html>
Output:Before Clicking on Button:
After Clicking on Button:
Supported Browsers:
Google Chrome 37.0
Opera 24.0
Safari 6.0
HTML-DOM
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Form validation using HTML and JavaScript | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2019"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "The DOM Dialog show() method is used to show the dialog. The Dialog element is accessed by getElementById(). It is used in HTML5.While using this method, the user can interact... |
Difference between Primary Key and Foreign Key | 28 Mar, 2020
Primary Key:A primary key is used to ensure data in the specific column is unique. It is a column cannot have NULL values. It is either an existing table column or a column that is specifically generated by the database according to a defined sequence.
Example: Refer the figure –STUD_NO, as well as STUD_PHONE both, are candidate keys for relation STUDENT but STUD_NO can be chosen as the primary key (only one out of many candidate keys).
Foreign Key:A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It is a column (or columns) that references a column (most often the primary key) of another table.
Example: Refer the figure –STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT relation.
Figure:
Let’s see the difference between Primary Key and Foreign Key:
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Mar, 2020"
},
{
"code": null,
"e": 305,
"s": 52,
"text": "Primary Key:A primary key is used to ensure data in the specific column is unique. It is a column cannot have NULL values. It is either an existing table column or a column t... |
SQL - Temporary Tables | There are RDBMS, which support temporary tables. Temporary Tables are a great feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables.
The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates.
Temporary tables are available in MySQL version 3.23 onwards. If you use an older version of MySQL than 3.23, you can't use temporary tables, but you can use heap tables.
As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.
Here is an example showing you the usage of a temporary table.
mysql> CREATE TEMPORARY TABLE SALESSUMMARY (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SALESSUMMARY
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SALESSUMMARY;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command, then your temporary table will not be listed out in the list. Now, if you log out of the MySQL session and then issue a SELECT command, you will find no data available in the database. Even your temporary table will not be existing.
By default, all the temporary tables are deleted by MySQL when your database connection gets terminated. Still if you want to delete them in between, then you can do so by issuing a DROP TABLE command.
Following is an example on dropping a temporary table.
mysql> CREATE TEMPORARY TABLE SALESSUMMARY (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SALESSUMMARY
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SALESSUMMARY;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SALESSUMMARY;
mysql> SELECT * FROM SALESSUMMARY;
ERROR 1146: Table 'TUTORIALS.SALESSUMMARY' doesn't exist | [
{
"code": null,
"e": 2834,
"s": 2587,
"text": "There are RDBMS, which support temporary tables. Temporary Tables are a great feature that lets you store and process intermediate results by using the same selection, update, and join capabilities that you can use with typical SQL Server tables."
},
... |
Python program to draw a bar chart using turtle | 02 Dec, 2021
Prerequisite: Turtle Programming Basics
Turtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like a turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is a beginner-friendly way to learn Python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways.
To draw, Python turtle provides many functions and methods i.e. forward, backward, etc. Some commonly used methods are:
forward(x): moves the pen in the forward direction by x unit.
backward(x): moves the pen in the backward direction by x unit.
right(x): rotate the pen in the clockwise direction by an angle x.
left(x): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
Turtle can be used to draw any static shape (Shape that can be drawn using lines). We all know that
Approach:
Import the turtle library.
Create a function, say drawBar() that takes a turtle object, a height value, and a color name and perform the following steps:The function draws vertical rectangles of a given height and fixed width (say 40).The function fills the rectangle with the given color name.
The function draws vertical rectangles of a given height and fixed width (say 40).
The function fills the rectangle with the given color name.
Initialize a list having some numerical values (data for the bar graph).
Initialize a turtle instance.
Set up the window and call the drawBar() for each value of the list with the created turtle instance and any color of your choice.
After completing the above steps, close the turtle instance.
Below is the implementation of the above approach:
Python3
# Python program to draw a turtleimport turtle # Function that draws the turtledef drawBar(t, height, color): # Get turtle t to draw one bar # of height # Start filling this shape t.fillcolor(color) t.begin_fill() t.left(90) t.forward(height) t.write(str(height)) t.right(90) t.forward(40) t.right(90) t.forward(height) t.left(90) # stop filling the shape t.end_fill() # Driver Code xs = [48, 117, 200, 96, 134, 260, 99]clrs = ["green", "red", "yellow", "black", "pink", "brown", "blue"] maxheight = max(xs)numbers = len(xs)border = 10 # Set up the window and its# attributeswn = turtle.Screen() wn.setworldcoordinates(0 - border, 0 - border, 40 * numbers + border, maxheight + border) # Create tess and set some attributestess = turtle.Turtle() tess.pensize(3) for i in range(len(xs)): drawBar (tess, xs[i], clrs[i]) wn.exitonclick()
Output:
clintra
Python-turtle
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 68,
"s": 28,
"text": "Prerequisite: Turtle Programming Basics"
},
{
"code": null,
"e": 539,
"s": 68,
"text": "Turtle is a Python feature like a drawing board, which lets us comma... |
numpy.tri() in Python | 09 Mar, 2022
numpy.tri(R, C = None, k = 0, dtype = ‘float’) : Creates an array with 1’s at and below the given diagonal(about k) and 0’s elsewhere.Parameters :
R : Number of rows
C : [optional] Number of columns; By default R = C
k : [int, optional, 0 by default]
Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
dtype : [optional, float(byDefault)] Data type of returned array.
# Python Program illustrating# numpy.tri method import numpy as geek print("tri with k = 1 : \n",geek.tri(2, 3, 1, dtype = float), "\n") print("tri with main diagonal : \n",geek.tri(3, 5, 0), "\n") print("tri with k = -1 : \n",geek.tri(3, 5, -1), "\n")
Output :
tri with k = 1 :
[[ 1. 1. 0.]
[ 1. 1. 1.]]
tri with main diagonal :
[[ 1. 0. 0. 0. 0.]
[ 1. 1. 0. 0. 0.]
[ 1. 1. 1. 0. 0.]]
tri with k = -1 :
[[ 0. 0. 0. 0. 0.]
[ 1. 0. 0. 0. 0.]
[ 1. 1. 0. 0. 0.]]
References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.tri.htmlNote :These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "numpy.tri(R, C = None, k = 0, dtype = ‘float’) : Creates an array with 1’s at and below the given diagonal(about k) and 0’s elsewhere.Parameters :"
},
{
"code": null,
... |
Rotate a matrix by 90 degree in clockwise direction without using any extra space | 11 Jul, 2022
Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3
Input:
1 2
3 4
Output:
3 1
4 2
Method 1
Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements of the cycle in a clockwise direction i.e. An N x N matrix will have floor(N/2) square cycles. For example, a 3 X 3 matrix will have 1 cycle. The cycle is formed by its 1st row, last column, last row, and 1st column. For each square cycle, we swap the elements involved with the corresponding cell in the matrix in the clockwise direction. We just need a temporary variable for this.
Explanation:
Let size of row and column be 3. During first iteration – a[i][j] = Element at first index (leftmost corner top)= 1.a[j][n-1-i]= Rightmost corner top Element = 3.a[n-1-i][n-1-j] = Rightmost corner bottom element = 9.a[n-1-j][i] = Leftmost corner bottom element = 7.Move these elements in the clockwise direction. During second iteration – a[i][j] = 2.a[j][n-1-i] = 6.a[n-1-i][n-1-j] = 8.a[n-1-j][i] = 4. Similarly, move these elements in the clockwise direction.
Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define N 4 // Function to rotate the matrix 90 degree clockwisevoid rotate90Clockwise(int a[N][N]){ // Traverse each cycle for (int i = 0; i < N / 2; i++) { for (int j = i; j < N - i - 1; j++) { // Swap elements of each cycle // in clockwise direction int temp = a[i][j]; a[i][j] = a[N - 1 - j][i]; a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j]; a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i]; a[j][N - 1 - i] = temp; } }} // Function for print matrixvoid printMatrix(int arr[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << '\n'; }} // Driver codeint main(){ int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90Clockwise(arr); printMatrix(arr); return 0;}
// Java implementation of above approachimport java.io.*; class GFG{ static int N = 4; // Function to rotate the matrix 90 degree clockwisestatic void rotate90Clockwise(int a[][]){ // Traverse each cycle for (int i = 0; i < N / 2; i++) { for (int j = i; j < N - i - 1; j++) { // Swap elements of each cycle // in clockwise direction int temp = a[i][j]; a[i][j] = a[N - 1 - j][i]; a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j]; a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i]; a[j][N - 1 - i] = temp; } }} // Function for print matrixstatic void printMatrix(int arr[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print( arr[i][j] + " "); System.out.println(); }} // Driver code public static void main (String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90Clockwise(arr); printMatrix(arr); }} // This code has been contributed by inder_verma.
# Function to rotate the matrix# 90 degree clockwisedef rotate90Clockwise(A): N = len(A[0]) for i in range(N // 2): for j in range(i, N - i - 1): temp = A[i][j] A[i][j] = A[N - 1 - j][i] A[N - 1 - j][i] = A[N - 1 - i][N - 1 - j] A[N - 1 - i][N - 1 - j] = A[j][N - 1 - i] A[j][N - 1 - i] = temp # Function to print the matrixdef printMatrix(A): N = len(A[0]) for i in range(N): print(A[i]) # Driver codeA = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]rotate90Clockwise(A)printMatrix(A) # This code was contributed# by pk_tautolo
// C# implementation of above approachusing System; class GFG{static int N = 4; // Function to rotate the matrix// 90 degree clockwisestatic void rotate90Clockwise(int[,] a){ // Traverse each cycle for (int i = 0; i < N / 2; i++) { for (int j = i; j < N - i - 1; j++) { // Swap elements of each cycle // in clockwise direction int temp = a[i, j]; a[i, j] = a[N - 1 - j, i]; a[N - 1 - j, i] = a[N - 1 - i, N - 1 - j]; a[N - 1 - i, N - 1 - j] = a[j, N - 1 - i]; a[j, N - 1 - i] = temp; } }} // Function for print matrixstatic void printMatrix(int[,] arr){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write( arr[i, j] + " "); Console.Write("\n"); }} // Driver codepublic static void Main () { int [,]arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; rotate90Clockwise(arr); printMatrix(arr);}} // This code is contributed// by ChitraNayal
<?php// PHP implementation of above approach$N = 4; // Function to rotate the matrix// 90 degree clockwisefunction rotate90Clockwise(&$a){ global $N; // Traverse each cycle for ($i = 0; $i < $N / 2; $i++) { for ($j = $i; $j < $N - $i - 1; $j++) { // Swap elements of each cycle // in clockwise direction $temp = $a[$i][$j]; $a[$i][$j] = $a[$N - 1 - $j][$i]; $a[$N - 1 - $j][$i] = $a[$N - 1 - $i][$N - 1 - $j]; $a[$N - 1 - $i][$N - 1 - $j] = $a[$j][$N - 1 - $i]; $a[$j][$N - 1 - $i] = $temp; } }} // Function for print matrixfunction printMatrix(&$arr){ global $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) echo $arr[$i][$j] . " "; echo "\n"; }} // Driver code$arr = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));rotate90Clockwise($arr);printMatrix($arr); // This code is contributed// by ChitraNayal?>
<script> // Javascript implementation of above approach var N = 4; // Function to rotate the matrix 90 degree clockwise function rotate90Clockwise(a) { // Traverse each cycle for (i = 0; i < parseInt(N / 2); i++) { for (j = i; j < N - i - 1; j++) { // Swap elements of each cycle // in clockwise direction var temp = a[i][j]; a[i][j] = a[N - 1 - j][i]; a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j]; a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i]; a[j][N - 1 - i] = temp; } } } // Function for print matrix function printMatrix(arr) { for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(arr[i][j] + " "); document.write("<br/>"); } } // Driver code var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; rotate90Clockwise(arr); printMatrix(arr); // This code contributed by Rajput-Ji </script>
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Complexity Analysis:
Time Complexity – O(n*n)
Auxiliary Space – O(1)
Method 2:
Approach: The approach is based on the pattern made by indices after rotating the matrix. Consider the following illustration to have a clear insight into it.
Consider a 3 x 3 matrix having indices (i, j) as follows.
00 01 02 10 11 12 20 21 22
After rotating the matrix by 90 degrees in clockwise direction, indices transform into20 10 00 current_row_index = 0, i = 2, 1, 0 21 11 01 current_row_index = 1, i = 2, 1, 0 22 12 02 current_row_index = 2, i = 2, 1, 0
Observation: In any row, for every decreasing row index i, there exists a constant column index j, such that j = current_row_index.
This pattern can be printed using 2 nested loops.(This pattern of writing indices is achieved by writing the exact indices of the desired elements of where they actually existed in the original array.)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define N 4 // Function to rotate the matrix 90 degree clockwisevoid rotate90Clockwise(int arr[N][N]){ // printing the matrix on the basis of // observations made on indices. for (int j = 0; j < N; j++) { for (int i = N - 1; i >= 0; i--) cout << arr[i][j] << " "; cout << '\n'; }} // Driver codeint main(){ int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90Clockwise(arr); return 0;} // This code is contributed by yashbeersingh42
// Java implementation of above approachimport java.io.*; class GFG { static int N = 4; // Function to rotate the matrix 90 degree clockwise static void rotate90Clockwise(int arr[][]) { // printing the matrix on the basis of // observations made on indices. for (int j = 0; j < N; j++) { for (int i = N - 1; i >= 0; i--) System.out.print(arr[i][j] + " "); System.out.println(); } } public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90Clockwise(arr); }}// This code is contributed by yashbeersingh42
# Python3 implementation of above approachN = 4 # Function to rotate the matrix 90 degree clockwisedef rotate90Clockwise(arr) : global N # printing the matrix on the basis of # observations made on indices. for j in range(N) : for i in range(N - 1, -1, -1) : print(arr[i][j], end = " ") print() # Driver code arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]rotate90Clockwise(arr); # This code is contributed by divyesh072019.
// C# implementation of above approachusing System;class GFG { static int N = 4; // Function to rotate the matrix 90 degree clockwise static void rotate90Clockwise(int[,] arr) { // printing the matrix on the basis of // observations made on indices. for (int j = 0; j < N; j++) { for (int i = N - 1; i >= 0; i--) Console.Write(arr[i, j] + " "); Console.WriteLine(); } } // Driver code static void Main() { int[,] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90Clockwise(arr); }} // This code is contributed by divyeshrabadiya07.
<script>// javascript implementation of above approach var N = 4; // Function to rotate the matrix 90 degree clockwise function rotate90Clockwise(arr) { // printing the matrix on the basis of // observations made on indices. for (j = 0; j < N; j++) { for (i = N - 1; i >= 0; i--) document.write(arr[i][j] + " "); document.write("<br/>"); } } var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; rotate90Clockwise(arr); // This code contributed by Rajput-Ji</script>
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Complexity Analysis:
Time Complexity – O(n*n)
Auxiliary Space – O(1)
Method 3:
Approach: The Approach is to rotate the given matrix two times, first time with respect to the Main diagonal, next time rotate the resultant matrix with respect to the middle column, Consider the following illustration to have a clear insight into it.
Rotate square matrix 90 degrees in a clockwise direction
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; #define N 4 void print(int arr[N][N]){ for(int i = 0; i < N; ++i) { for(int j = 0; j < N; ++j) cout << arr[i][j] << " "; cout << '\n'; }} void rotate(int arr[N][N]){ // First rotation // with respect to main diagonal for(int i = 0; i < N; ++i) { for(int j = 0; j < i; ++j) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Second rotation // with respect to middle column for(int i = 0; i < N; ++i) { for(int j = 0; j < N / 2; ++j) { int temp = arr[i][j]; arr[i][j] = arr[i][N - j - 1]; arr[i][N - j - 1] = temp; } }} // Driver codeint main(){ int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); print(arr); return 0;} // This code is contributed by Rahul Verma
import java.io.*; class GFG { static void rotate(int[][] arr) { int n=arr.length; // first rotation // with respect to main diagonal for(int i=0;i<n;++i) { for(int j=0;j<i;++j) { int temp = arr[i][j]; arr[i][j]=arr[j][i]; arr[j][i]=temp; } } // Second rotation // with respect to middle column for(int i=0;i<n;++i) { for(int j=0;j<n/2;++j) { int temp =arr[i][j]; arr[i][j] = arr[i][n-j-1]; arr[i][n-j-1]=temp; } } } // to print matrix static void printMatrix(int arr[][]) { int n=arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( arr[i][j] + " "); System.out.println(); } } // Driver code public static void main (String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); printMatrix(arr); }}// This code is contributed by Rahul Verma
# Python3 implementation of above approachN = 4 # Function to rotate the matrix 90 degree clockwisedef rotate(arr): global N # First rotation# with respect to main diagonal for i in range(N): for j in range(i): temp = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = temp # Second rotation# with respect to middle column for i in range(N): for j in range(int(N/2)): temp = arr[i][j] arr[i][j] = arr[i][N-j-1] arr[i][N-j-1] = temp # Driver codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotate(arr) for i in range(N): for j in range(N): print(arr[i][j], end=" ") print() # This code is contributed by Aarti_Rathi
using System;using System.Collections.Generic;public class GFG { static void rotate(int[,] arr) { int n=arr.GetLength(0); // first rotation // with respect to main diagonal for(int i=0;i<n;++i) { for(int j=0;j<i;++j) { int temp = arr[i,j]; arr[i,j]=arr[j,i]; arr[j,i]=temp; } } // Second rotation // with respect to middle column for(int i=0;i<n;++i) { for(int j=0;j<n/2;++j) { int temp =arr[i,j]; arr[i,j] = arr[i,n-j-1]; arr[i,n-j-1]=temp; } } } // to print matrix static void printMatrix(int [,]arr) { int n=arr.GetLength(0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write( arr[i,j] + " "); Console.WriteLine(); } } // Driver code public static void Main(String[] args) { int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); printMatrix(arr); }} // This code contributed by Rajput-Ji
<script> let N = 4 function print(arr){ for(let i = 0; i < N; ++i) { for(let j = 0; j < N; ++j) document.write(arr[i][j] + " "); document.write("<br>"); }} function rotate(arr){ // First rotation // with respect to main diagonal for(let i = 0; i < N; ++i) { for(let j = 0; j < i; ++j) { let temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Second rotation // with respect to middle column for(let i = 0; i < N; ++i) { for(let j = 0; j < N / 2; ++j) { let temp = arr[i][j]; arr[i][j] = arr[i][N - j - 1]; arr[i][N - j - 1] = temp; } }} // Driver code let arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; rotate(arr); print(arr); //This code is contributed by Mayank Tyagi</script>
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Complexity Analysis:
Time Complexity – O(n*n)
Auxiliary Space – O(1)
Method 4:
Approach: This approach is similar to method 3 the only difference is that in first rotation we rotate about the Secondary Diagonal and after that about the Middle row.
Rotate square matrix 90 degrees in a clockwise direction
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; #define N 4 void print(int arr[N][N]){ for(int i = 0; i < N; ++i) { for(int j = 0; j < N; ++j) cout << arr[i][j] << " "; cout << '\n'; }} void rotate(int arr[N][N]){ // First rotation // with respect to Secondary diagonal for(int i = 0; i < N; i++) { for(int j = 0; j < N - i; j++) { int temp = arr[i][j]; arr[i][j] = arr[N - 1 - j][N - 1 - i]; arr[N - 1 - j][N - 1 - i] = temp; } } // Second rotation // with respect to middle row for(int i = 0; i < N / 2; i++) { for(int j = 0; j < N; j++) { int temp = arr[i][j]; arr[i][j] = arr[N - 1 - i][j]; arr[N - 1 - i][j] = temp; } }} // Driver codeint main(){ int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); print(arr); return 0;} // This code is contributed by Rahul Verma
import java.io.*; class GFG { static void rotate(int[][] arr) { int n = arr.length; // first rotation // with respect to Secondary diagonal for (int i = 0; i < n; i++) { for (int j = 0; j < n - i; j++) { int temp = arr[i][j]; arr[i][j] = arr[n - 1 - j][n - 1 - i]; arr[n - 1 - j][n - 1 - i] = temp; } } // Second rotation // with respect to middle row for (int i = 0; i < n / 2; i++) { for (int j = 0; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[n - 1 - i][j]; arr[n - 1 - i][j] = temp; } } } // to print matrix static void printMatrix(int arr[][]) { int n = arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } // Driver code public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); printMatrix(arr); }}// This code is contributed by Rahul Verma
# Python3 implementation of above approachN = 4 def display(arr): for i in range(N) : for j in range(N) : print(arr[i][j],end=" ") print() # Function to rotate the matrix 90 degree clockwisedef rotate90Clockwise(arr) : global N # First rotation # with respect to Secondary diagonal for i in range(N) : for j in range(N-i) : arr[i][j],arr[N - 1 - j][N - 1 - i]=arr[N - 1 - j][N - 1 - i],arr[i][j] # Second rotation # with respect to middle row for i in range(N//2) : for j in range(N) : arr[i][j],arr[N - 1 - i][j]=arr[N - 1 - i][j],arr[i][j] # Driver code arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]rotate90Clockwise(arr)display(arr) # This code is contributed by Aarti_Rathi
using System;using System.Collections.Generic; class GFG{ static void rotate(int[,] arr){ int n = arr.GetLength(0); // First rotation // with respect to Secondary diagonal for(int i = 0; i < n; i++) { for(int j = 0; j < n - i; j++) { int temp = arr[i, j]; arr[i, j] = arr[n - 1 - j, n - 1 - i]; arr[n - 1 - j, n - 1 - i] = temp; } } // Second rotation // with respect to middle row for(int i = 0; i < n / 2; i++) { for(int j = 0; j < n; j++) { int temp = arr[i, j]; arr[i, j] = arr[n - 1 - i, j]; arr[n - 1 - i, j] = temp; } }} // To print matrixstatic void printMatrix(int [,]arr){ int n = arr.GetLength(0); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) Console.Write(arr[i, j] + " "); Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate(arr); printMatrix(arr);}} // This code is contributed by aashish1995
<script> function rotate(arr) { var n = arr.length; // first rotation // with respect to Secondary diagonal for (i = 0; i < n; i++) { for (j = 0; j < n - i; j++) { var temp = arr[i][j]; arr[i][j] = arr[n - 1 - j][n - 1 - i]; arr[n - 1 - j][n - 1 - i] = temp; } } // Second rotation // with respect to middle row for (i = 0; i < n / 2; i++) { for (j = 0; j < n; j++) { var temp = arr[i][j]; arr[i][j] = arr[n - 1 - i][j]; arr[n - 1 - i][j] = temp; } } } // to print matrix function printMatrix(arr) { var n = arr.length; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) document.write(arr[i][j] + " "); document.write("<br/>"); } } // Driver code var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; rotate(arr); printMatrix(arr); // This code is contributed by gauravrajput1</script>
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Complexity Analysis:
Time Complexity – O(n*n)
Auxiliary Space – O(1)
Method 5:
Approach: We first transpose the given matrix, and then reverse the content of individual rows to get the resultant 90 degree clockwise rotated matrix.
1 2 3 1 4 7 7 4 1
4 5 6 ——Transpose——> 2 5 8 —-Reverse individual rows—-> 8 5 2 (Resultant matrix)
7 8 9 3 6 9 9 6 3
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std;const int n = 4;void print(int mat[n][n]){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; }}void rotate90clockwise(int mat[n][n]){ // Transpose of matrix for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) swap(mat[i][j], mat[j][i]); // Reverse individual rows for (int i = 0; i < n; i++) { int low = 0, high = n - 1; while (low < high) { swap(mat[i][low], mat[i][high]); low++; high--; } }}int main(){ int mat[n][n] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90clockwise(mat); print(mat);}
import java.util.*; class GFG { static int n = 4; static void print(int mat[][]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(mat[i][j] + " "); System.out.println(); } } static void rotate90clockwise(int mat[][]) { // Transpose of matrix for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { int t = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = t; } // Reverse individual rows for (int i = 0; i < n; i++) { int low = 0, high = n - 1; while (low < high) { int t = mat[i][low]; mat[i][low] = mat[i][high]; mat[i][high] = t; low++; high--; } } } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90clockwise(mat); print(mat); }} // This code is contributed by umadevi9616
# Python3 implementation of above approachN = 4 def display(arr): for i in range(N) : for j in range(N) : print(arr[i][j],end=" ") print() # Function to rotate the matrix 90 degree clockwisedef rotate90Clockwise(arr) : global N # Transpose of matrix for i in range(N) : for j in range(i+1,N) : arr[i][j],arr[j][i]=arr[j][i],arr[i][j] # Reverse individual rows for i in range(N//2) : low = 0 high = N-1 while (low<high) : arr[i][low],arr[i][high]=arr[i][high],arr[i][low] low = low + 1 high = high - 1 # Driver code arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]rotate90Clockwise(arr)display(arr) # This code is contributed by Aarti_Rathi
using System;using System.Collections.Generic; class GFG{ static void rotate90clockwise(int[,] arr){ int n = arr.GetLength(0); // Transpose of matrix for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { int temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } /// Reverse individual rows for (int i = 0; i < n; i++) { int low = 0, high = n - 1; while (low < high) { int temp = arr[i, low]; arr[i, low] = arr[i, high]; arr[i, high] = temp; low++; high--; } }} // To print matrixstatic void printMatrix(int [,]arr){ int n = arr.GetLength(0); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) Console.Write(arr[i, j] + " "); Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90clockwise(arr); printMatrix(arr);}} // This code is contributed by Aarti_Rathi
<script> function rotate(arr) { var n = arr.length; // Transpose of matrix for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { var temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Reverse individual rows for (i = 0; i < n; i++) { var low = 0, high = n-1; while (low < high) { var temp = arr[i][low]; arr[i][low] = arr[i][high]; arr[i][high] = temp; low++; high--; } } } // to print matrix function printMatrix(arr) { var n = arr.length; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) document.write(arr[i][j] + " "); document.write("<br/>"); } } // Driver code var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; rotate(arr); printMatrix(arr); // This code is contributed by Aarti_Rathi</script>
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Complexity Analysis:
Time Complexity – O(n*n)
Auxiliary Space – O(1)
inderDuMCA
pk_tautolo
ukasp
ajit12
yashbeersingh42
divyeshrabadiya07
divyesh072019
rv60231023
Rajput-Ji
mayanktyagi1709
aashish1995
adnanirshad158
rishavsaha
tushargupta1999
GauravRajput1
umadevi9616
_shinchancode
sachinvinod1904
isha307
rotation
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 155,
"s": 54,
"text": "Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space."
},
{
"code": null,
"e": 166,
"s": 155,
"text": "Exam... |
Python | Largest, Smallest, Second Largest, Second Smallest in a List | 04 Jul, 2022
Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. Moreover, the vast inbuilt functions of Python, make the task easier. So using these techniques, let’s try to find the various ranges of the number in a given list.
Examples:
Input : list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
Output :
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4
Input : list = [22, 85, 62, 40, 55, 12, 39, 2, 43]
Output :
Largest element is: 85
Smallest element is: 2
Second Largest element is: 62
Second Smallest element is: 12
Approach#1: The approach is simple. Python allows us to sort a list using the list() function. Using this we can find various ranges of numbers in a list, from their position, after being sorted. Like the first position must contain the smallest and the last element must be the greatest.
Python3
# Python prog to illustrate the following in a listdef find_len(list1): length = len(list1) list1.sort() print("Largest element is:", list1[length-1]) print("Smallest element is:", list1[0]) print("Second Largest element is:", list1[length-2]) print("Second Smallest element is:", list1[1]) # Driver Codelist1=[12, 45, 2, 41, 31, 10, 8, 6, 4]Largest = find_len(list1)
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4
Approach#2: Below is another traditional method to do the following calculation. The algorithm is simple, we take a number and compare it with all other numbers present in the list and get the largest, smallest, second largest, and second smallest element.
Python3
# Python program to find largest, smallest,# second largest and second smallest in a# list with complexity O(n)def Range(list1): largest = list1[0] lowest = list1[0] largest2 = None lowest2 = None for item in list1[1:]: if item > largest: largest2 = largest largest = item elif largest2 is None or largest2 < item: largest2 = item if item < lowest: lowest2 = lowest lowest = item elif lowest2 is None or lowest2 > item: lowest2 = item print("Largest element is:", largest) print("Smallest element is:", lowest) print("Second Largest element is:", largest2) print("Second Smallest element is:", lowest2) # Driver Codelist1 = [12, 45, 2, 41, 31, 10, 8, 6, 4]Range(list1)
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4
Approach#3: This task can be performed using max and pop methods of list. We can find largest and smallest element of list using max and min method after getting min and max element pop outs the elements from list and again use min and max element to get the second largest and second smallest element.
Python3
# Python prog for finding largest, smallest# Second largest and second smallestdef find_len( list1 ) : # max gives maximum element of list # Pop pull outs index element Lelmt = max( list1 ) list1.pop( list1.index( Lelmt ) ) sLelmt = max(list1) # Min gives minimum element of list # Pop pull outs index element Selmt = min( list1 ) list1.pop( list1.index( Selmt ) ) sSelmt = min( list1 ) # Printing Min and max of list print("Largest element is:", Lelmt ) print("Smallest element is:", Selmt ) print("Second Largest element is:", sLelmt ) print("Second Smallest element is:", sSelmt ) # Driver Codelist1=[12, 45, 2, 41, 31, 10, 8, 6, 4]Largest = find_len(list1)
Output:
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4
ashrafiseyedbabak
satyam00so
simmytarika5
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 393,
"s": 54,
"text": "Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. M... |
Mode in a stream of integers (running integers) | 18 Sep, 2020
Given that integers are being read from a data stream. Find the mode of all the elements read so far starting from the first integer till the last integer.
Mode is defined as the element which occurs the maximum time. If two or more elements have the same maximum frequency, then take the one with the last occurrence.
Examples:
Input: stream[] = {2, 7, 3, 2, 5}Output: 2 7 3 2 2 Explanation: Mode of Running Stream is computed as follows: Mode({2}) = 2 Mode({2, 7}) = 7 Mode({2, 7, 3}) = 3 Mode({2, 7, 3, 2}) = 2 Mode({2, 7, 3, 2, 2}) = 2
Input: stream[] = {3, 5, 9, 9, 2, 3, 3, 4}Output: 3 5 9 9 9 3 3 3
Approach: The idea is to use a Hash-map to map elements to its frequency. While reading the elements one by one update the frequencies of elements in the map and also update the mode which will be the mode of the stream of the running integers.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function that prints// the Mode valuesvoid findMode(int a[], int n){ // Map used to mp integers // to its frequency map<int, int> mp; // To store the maximum frequency int max = 0; // To store the element with // the maximum frequency int mode = 0; // Loop used to read the // elements one by one for(int i = 0; i < n; i++) { // Updates the frequency of // that element mp[a[i]]++; // Checks for maximum Number // of occurrence if (mp[a[i]] >= max) { // Updates the maximum frequency max = mp[a[i]]; // Updates the Mode mode = a[i]; } cout << mode << " "; }} // Driver Codeint main(){ int arr[] = { 2, 7, 3, 2, 5 }; int n = sizeof(arr)/sizeof(arr[0]); // Function call findMode(arr, n); return 0;} // This code is contributed by rutvik_56
// Java implementation of the// above approach import java.util.*; public class GFG { // Function that prints // the Mode values public static void findMode(int[] a, int n) { // Map used to map integers // to its frequency Map<Integer, Integer> map = new HashMap<>(); // To store the maximum frequency int max = 0; // To store the element with // the maximum frequency int mode = 0; // Loop used to read the // elements one by one for (int i = 0; i < n; i++) { // Updates the frequency of // that element map.put(a[i], map.getOrDefault(a[i], 0) + 1); // Checks for maximum Number // of occurrence if (map.get(a[i]) >= max) { // Updates the maximum frequency max = map.get(a[i]); // Updates the Mode mode = a[i]; } System.out.print(mode); System.out.print(" "); } } // Driver Code public static void main(String[] args) { int arr[] = { 2, 7, 3, 2, 5 }; int n = arr.length; // Function Call findMode(arr, n); }}
# Python3 implementation of the # above approach # Function that prints # the Mode values def findMode(a, n): # Map used to mp integers # to its frequency mp = {} # To store the maximum frequency max = 0 # To store the element with # the maximum frequency mode = 0 # Loop used to read the # elements one by one for i in range(n): if a[i] in mp: mp[a[i]] += 1 else: mp[a[i]] = 1 # Checks for maximum Number # of occurrence if (mp[a[i]] >= max): # Updates the maximum # frequency max = mp[a[i]] # Updates the Mode mode = a[i] print(mode, end = " ") # Driver Codearr = [ 2, 7, 3, 2, 5 ]n = len(arr) # Function call findMode(arr,n) # This code is contributed by divyeshrabadiya07
// C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG{ // Function that prints // the Mode values public static void findMode(int[] a, int n) { // Map used to map integers // to its frequency Dictionary<int, int> map = new Dictionary<int, int>(); // To store the maximum frequency int max = 0; // To store the element with // the maximum frequency int mode = 0; // Loop used to read the // elements one by one for (int i = 0; i < n; i++) { // Updates the frequency of // that element if (map.ContainsKey(a[i])) { map[a[i]] = map[a[i]] + 1; } else { map.Add(a[i], 1); } // Checks for maximum Number // of occurrence if (map[a[i]] >= max) { // Updates the maximum frequency max = map[a[i]]; // Updates the Mode mode = a[i]; } Console.Write(mode); Console.Write(" "); } } // Driver Code public static void Main(String[] args) { int[] arr = {2, 7, 3, 2, 5}; int n = arr.Length; // Function Call findMode(arr, n); }} // This code is contributed by Amit Katiyar
2 7 3 2 2
Performance Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
amit143katiyar
rutvik_56
divyeshrabadiya07
array-stream
frequency-counting
Java-HashMap
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Given that integers are being read from a data stream. Find the mode of all the elements read so far starting from the first integer till the last integer."
},
{
"cod... |
fmt.Scan() Function in Golang With Examples | 26 Feb, 2021
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scan() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Scan(a ...interface{}) (n int, err error)
Here, “a ...interface{}” receives each type of the given texts.Returns: It returns the number of items successfully scanned.
Example 1:
C
// Golang program to illustrate the usage of// fmt.Scan() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scan() function for // scanning and reading the input // texts given in standard input fmt.Scan(&name) fmt.Scan(&alphabet_count) // Printing the given texts fmt.Printf("The word %s containing %d number of alphabets.", name, alphabet_count) }
Input:
GFG 3
Output:
The word GFG containing 3 number of alphabets.
Example 2:
C
// Golang program to illustrate the usage of// fmt.Scan() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var bool_value bool // Calling Scan() function for // scanning and reading the input // texts given in standard input fmt.Scan(&name) fmt.Scan(&alphabet_count) fmt.Scan(&float_value) fmt.Scan(&bool_value) // Printing the given texts fmt.Printf("%s %d %g %t", name, alphabet_count, float_value, bool_value) }
Input:
GeeksforGeeks 13 6.789 true
Output:
GeeksforGeeks 13 6.789 true
arorakashish0911
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
How to Trim a String in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 471,
"s": 28,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scan() function in Go language scans the input text... |
Java 8 Predicate with Examples | 13 Apr, 2022
A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate, consumer, supplier etc. The return type of a Lambda function (introduced in JDK 1.8) is a also functional interface.
The Functional Interface PREDICATE is defined in the java.util.Function package. It improves manageability of code, helps in unit-testing them separately, and contain some methods like:
isEqual(Object targetRef) : Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).static Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are
equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate
Parameters:
targetRef : the object reference with which to
compare for equality, which may be null
Returns: a predicate that tests if two arguments
are equal according to Objects.equals(Object, Object)
and(Predicate other) : Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
default Predicate and(Predicate other)
Returns a composed predicate that represents a
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is nullnegate() : Returns a predicate that represents the logical negation of this predicate.default Predicate negate()
Returns:a predicate that represents the logical
negation of this predicateor(Predicate other) : Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.default Predicate or(Predicate other)
Parameters:
other : a predicate that will be logically-ORed with this predicate
Returns:
a composed predicate that represents the short-circuiting
logical OR of this predicate and the other predicate
Throws : NullPointerException - if other is nulltest(T t) : Evaluates this predicate on the given argument.boolean test(T t)test(T t)
Parameters:
t - the input argument
Returns:
true if the input argument matches the predicate, otherwise false
isEqual(Object targetRef) : Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).static Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are
equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate
Parameters:
targetRef : the object reference with which to
compare for equality, which may be null
Returns: a predicate that tests if two arguments
are equal according to Objects.equals(Object, Object)
static Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are
equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate
Parameters:
targetRef : the object reference with which to
compare for equality, which may be null
Returns: a predicate that tests if two arguments
are equal according to Objects.equals(Object, Object)
and(Predicate other) : Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
default Predicate and(Predicate other)
Returns a composed predicate that represents a
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is null
default Predicate and(Predicate other)
Returns a composed predicate that represents a
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is null
negate() : Returns a predicate that represents the logical negation of this predicate.default Predicate negate()
Returns:a predicate that represents the logical
negation of this predicate
default Predicate negate()
Returns:a predicate that represents the logical
negation of this predicate
or(Predicate other) : Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.default Predicate or(Predicate other)
Parameters:
other : a predicate that will be logically-ORed with this predicate
Returns:
a composed predicate that represents the short-circuiting
logical OR of this predicate and the other predicate
Throws : NullPointerException - if other is null
default Predicate or(Predicate other)
Parameters:
other : a predicate that will be logically-ORed with this predicate
Returns:
a composed predicate that represents the short-circuiting
logical OR of this predicate and the other predicate
Throws : NullPointerException - if other is null
test(T t) : Evaluates this predicate on the given argument.boolean test(T t)test(T t)
Parameters:
t - the input argument
Returns:
true if the input argument matches the predicate, otherwise false
test(T t)
Parameters:
t - the input argument
Returns:
true if the input argument matches the predicate, otherwise false
Examples
Example 1: Simple Predicate
Java
// Java program to illustrate Simple Predicate import java.util.function.Predicate;public class PredicateInterfaceExample1 { public static void main(String[] args) { // Creating predicate Predicate<Integer> lesserthan = i -> (i < 18); // Calling Predicate method System.out.println(lesserthan.test(10)); }}
True
Example 2: Predicate Chaining
Java
// Java program to illustrate Predicate Chaining import java.util.function.Predicate;public class PredicateInterfaceExample2 { public static void main(String[] args) { Predicate<Integer> greaterThanTen = (i) -> i > 10; // Creating predicate Predicate<Integer> lowerThanTwenty = (i) -> i < 20; boolean result = greaterThanTen.and(lowerThanTwenty).test(15); System.out.println(result); // Calling Predicate method boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15); System.out.println(result2); }}
True
False
Example 3: Predicate in to Function
Java
// Java program to illustrate // passing Predicate into function import java.util.function.Predicate;class PredicateInterfaceExample3 { static void pred(int number, Predicate<Integer> predicate) { if (predicate.test(number)) { System.out.println("Number " + number); } } public static void main(String[] args) { pred(10, (i) -> i > 7); }}
Number 10
Example 4: Predicate OR
Java
// Java program to illustrate OR Predicate import java.util.function.Predicate;class PredicateInterfaceExample4 { public static Predicate<String> hasLengthOf10 = new Predicate<String>() { @Override public boolean test(String t) { return t.length() > 10; } }; public static void predicate_or() { Predicate<String> containsLetterA = p -> p.contains("A"); String containsA = "And"; boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA); System.out.println(outcome); } public static void main(String[] args) { predicate_or(); }}
True
Example 5: Predicate AND
Java
// Java program to illustrate AND Predicate import java.util.function.Predicate;import java.util.Objects; class PredicateInterfaceExample5 { public static Predicate<String> hasLengthOf10 = new Predicate<String>() { @Override public boolean test(String t) { return t.length() > 10; } }; public static void predicate_and() { Predicate<String> nonNullPredicate = Objects::nonNull; String nullString = null; boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString); System.out.println(outcome); String lengthGTThan10 = "Welcome to the machine"; boolean outcome2 = nonNullPredicate.and(hasLengthOf10). test(lengthGTThan10); System.out.println(outcome2); } public static void main(String[] args) { predicate_and(); }}
False
True
Example 6: Predicate negate()
Java
// Java program to illustrate // negate Predicate import java.util.function.Predicate;class PredicateInterfaceExample6 { public static Predicate<String> hasLengthOf10 = new Predicate<String>() { @Override public boolean test(String t) { return t.length() > 10; } }; public static void predicate_negate() { String lengthGTThan10 = "Thunderstruck is a 2012 children's " + "film starring Kevin Durant"; boolean outcome = hasLengthOf10.negate().test(lengthGTThan10); System.out.println(outcome); } public static void main(String[] args) { predicate_negate(); }}
False
Example 7: Predicate in Collection
Java
// Java program to demonstrate working of predicates// on collection. The program finds all admins in an// arrayList of users.import java.util.function.Predicate;import java.util.*;class User{ String name, role; User(String a, String b) { name = a; role = b; } String getRole() { return role; } String getName() { return name; } public String toString() { return "User Name : " + name + ", Role :" + role; } public static void main(String args[]) { List<User> users = new ArrayList<User>(); users.add(new User("John", "admin")); users.add(new User("Peter", "member")); List admins = process(users, (User u) -> u.getRole().equals("admin")); System.out.println(admins); } public static List<User> process(List<User> users, Predicate<User> predicate) { List<User> result = new ArrayList<User>(); for (User user: users) if (predicate.test(user)) result.add(user); return result; }}
[User Name : John, Role :admin]
The same functionality can also be achieved by using Stream APIand lambda functions offered since JDK 1.8 on top of the Collections API.
The Stream API allows "streaming" of collections for dynamic processing. Streams allow concurrent and parallel computation on data (using internal iterations), to support database-like operations such as grouping and filtering the data (similar to GROUP BY and WHERE clause in SQL). This allows the developers to focus on "what data is needed" instead of "how data is needed" since streaming hides the details of the implementation and provides the result. This is done by providing predicates as inputs to functions operating at runtime upon the streams of collections. In the following example, we illustrate how Stream API can be used along with predicates to filter the collections of data as achieved in Example 7.
Java
// Java program to demonstrate working of predicates// on collection. The program finds all admins in an// arrayList of users.import java.util.function.Predicate;import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; class User{ String name, role; User(String a, String b) { name = a; role = b; } String getRole() { return role; } String getName() { return name; } public String toString() { return "User Name : " + name + ", Role :" + role; } public static void main(String args[]) { List<User> users = new ArrayList<User>(); users.add(new User("John", "admin")); users.add(new User("Peter", "member")); // This line uses Predicates to filter // out the list of users with the role "admin". // List admins = process(users, (User u) -> // u.getRole().equals("admin")); // Replacing it with the following line // using Stream API and lambda functions // produces the same output // the input to the filter() is a lambda // expression that returns a predicate: a // boolean value for each user encountered // (true if admin, false otherwise) List admins = users.stream() .filter((user) -> user.getRole().equals("admin")) .collect(Collectors.toList()); System.out.println(admins); }}
Output:
[User Name : John, Role :admin]
GarvitaBajaj
popliparul20
as5853535
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 347,
"s": 54,
"text": "A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate... |
Longest Palindrome in a String | Practice | GeeksforGeeks | Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index).
Example 1:
Input:
S = "aaaabbaa"
Output: aabbaa
Explanation: The longest Palindromic
substring is "aabbaa".
Example 2:
Input:
S = "abc"
Output: a
Explanation: "a", "b" and "c" are the
longest palindromes with same length.
The result is the one with the least
starting index.
Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S.
Expected Time Complexity: O(|S|2).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ |S| ≤ 103
0
spiderman694 hours ago
Easy solution without DP
string longestPalin (string S) {
// code here
int length1= INT_MIN;
string ans="";
for(int i=0;i<S.length();i++)
{
int start = i-1;
int end = i+1;
while(start>=0 && end<=S.length()-1)
{
if(S[start] == S[end])
{
start--;
end++;
}else break;
}
int l1 = (end-start)-1;
if(l1>ans.length())
{
ans = S.substr(start+1,l1);
}
start = i-1;
end = i;
while(start>=0 && end<=S.length()-1)
{
if(S[start] == S[end])
{
start--;
end++;
} else break;
}
int l2 = (end-start)-1;
if(l2>ans.length())
{
ans = S.substr(start+1,l2);
}
}
return ans;
}
0
botty11 day ago
class Solution {
public:
// Data Members
int right;
int left;
string maxPalin = "";
int maxLen = 1;
// Data Members
void extractPalin(string& S, int low, int high) {
right = high;
left = low;
int strlen = S.length();
while(left >= -1 or right <= strlen) {
if(left == -1 or right == strlen or S[right] != S[left]) {
int temp = right - left - 1;
if(temp > maxLen) {
maxLen = temp;
maxPalin = S.substr(left + 1, maxLen);
}
break;
}
left--;
right++;
}
}
string longestPalin (string S) {
int strlen = S.length();
string tempStr = S + " ";
maxPalin = S[0];
for (int i = 0; i < strlen; ++i)
{
extractPalin(S, i, i);
if(tempStr[i] == tempStr[i + 1]) extractPalin(S, i, i + 1);
}
return maxPalin;
}
};
0
aryabamboli20022 days ago
Easy solution with Dp C++
string longestPalin (string S) { int n = S.length(); int dp[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ dp[i][j]=1; } else if(j==i+1){ if(S[i]==S[j]){ dp[i][j]=1; }else{ dp[i][j]=0; } }else{ dp[i][j]=0; } } } string str=""; int ans=INT_MIN, k, previ=INT_MAX; for(int i=n-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ if(j-i>1){ if(S[i]==S[j] && dp[i+1][j-1]==1){ dp[i][j]=1; } } if(dp[i][j]==1 && (j-i+1>ans or (j-i+1==ans && i<previ))){ ans=j-i+1; k=i; previ=i; str=""; while(k<=j){ str+=S[k]; k++; } } } } return str;
0
om shankar ohdar3 days ago
Python without Dp in N^2: def longestPalin(self, S): # code here start = 0 maxL = 1 low = 0 high = 0 for i in range(1, len(S)): # for substring with odd length low = i-1 high = i while low >=0 and high < len(S) and S[low] == S[high]: if (high -low + 1) > maxL: start = low maxL = high - low + 1 low -= 1 high += 1 # for substring with even length low = i-1 high = i+1 while low >= 0 and high < len(S) and S[low] == S[high]: if (high - low + 1) > maxL: start = low maxL = high - low + 1 low -= 1 high += 1 return S[start: start+maxL]
0
rishitharapolu21
This comment was deleted.
0
kamresh4853 days ago
bool isPalindrome(string&S,int l,int r){
while(l<r)
if(S[l++]!=S[r--])
return false;
return true;
}
string longestPalin (string S) {
string max=S.substr(0,1);
for(int i=0;i<S.length()-1;i++)
for(int j=i+1;j<S.length();j++)
if(isPalindrome(S,i,j) && max.length()<j-i+1)
max=S.substr(i,j-i+1);
return max;
}
0
luvgupta76695 days ago
Simple Working Java Solution-
static String longestPalin(String S) {
if(S.length() < 2){
return S;
}
String max="";
for(int i=0; i<S.length()-1; i++){
String odd = findPalindrome(S, i, i);
String even = findPalindrome(S, i, i+1);
if (odd.length() > max.length()) {
max = odd;
}
if (even.length() > max.length()) {
max = even;
}
}
return max;
}
static String findPalindrome(String s, int left, int right) {
while(left>=0 && right<s.length() && s.charAt(left) == s.charAt(right)){
left--; right++;
}
return s.substring(left+1, right);
}
-1
rupendrasaraswat5 days ago
static String longestPalin(String S){ // code here String str=""; for(int i=0;i<S.length();i++){ for(int j=i+1;j<=S.length();j++){ String a=S.substring(i,j); if(palin(a)) if(a.length()>str.length()) str=a; } } return str; } public static boolean palin(String s){ int len=s.length(); for(int i=0;i<len/2;i++){ if(s.charAt(i)!=s.charAt(len-1-i)) return false; } return true; }
0
nitind3566 days ago
Simple C++ Solution using Dynamic programming
string longestPalin (string s) {
bool dp[s.length()][s.length()];
int st=0,ed=0,l=0;
for(int g=0;g<s.length();g++)
{
for(int i=0,j=g;j<s.length();i++,j++)
{
if(g==0)
dp[i][j]=true;
else if(g==1)
{
if(s[i]==s[j])
{
dp[i][j]=true;
}
else
{
dp[i][j]=false;
}
}
else
{
if(s[i]==s[j] && dp[i+1][j-1]==true)
{
dp[i][j]=true;
}
else
{
dp[i][j]=false;
}
}
if(dp[i][j] && (g+1)>l)
{
st=i;
ed=j;
l=g+1;
}
}
}
return s.substr(st,ed-st+1);
}
-4
rrodwal221 week ago
bool isPalindrome(string str, int s, int e){ while(s < e){ if(str[s] != str[e]){ return false; } s++; e--; } return true; } public: string longestPalin (string S) { int n = S.length(); int maxLen = 0; string ans = ""; if(n == 1){ return S; } for(int i = 0; i<n-1; i++){ for(int j = i; j<n; j++){ if(isPalindrome(S, i, j) && maxLen < (j-i+1)){ maxLen = j-i+1; ans = S.substr(i, j-i+1); } } } return ans;
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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. | [
{
"code": null,
"e": 571,
"s": 238,
"text": "Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of confli... |
SQL NULL Values | 30 Sep, 2021
In SQL there may be some records in a table that do not have values or data for every field. This could be possible because at a time of data entry information is not available. So SQL supports a special value known as NULL which is used to represent the values of attributes that may be unknown or not apply to a tuple. SQL places a NULL value in the field in the absence of a user-defined value. For example, the Apartment_number attribute of an address applies only to address that are in apartment buildings and not to other types of residences.
It is important to understand that a NULL value is different from a zero value.
A NULL value is used to represent a missing value, but that it usually has one of three different interpretations: The value unknown (value exists but is not known)Value not available (exists but is purposely withheld)Attribute not applicable (undefined for this tuple)
The value unknown (value exists but is not known)
Value not available (exists but is purposely withheld)
Attribute not applicable (undefined for this tuple)
It is often not possible to determine which of the meanings is intended. Hence, SQL does not distinguish between the different meanings of NULL.
Setting a NULL value is appropriate when the actual value is unknown, or when a value would not be meaningful.
A NULL value is not equivalent to a value of ZERO if the data type is a number and is not equivalent to spaces if the data type is character.
A NULL value can be inserted into columns of any data type.
A NULL value will evaluate NULL in any expression.
Suppose if any column has a NULL value, then UNIQUE, FOREIGN key, CHECK constraints will ignore by SQL.
In general, each NULL value is considered to be different from every other NULL in the database. When a NULL is involved in a comparison operation, the result is considered to be UNKNOWN. Hence, SQL uses a three-valued logic with values True, False, and Unknown. It is, therefore, necessary to define the results of three-valued logical expressions when the logical connectives AND, OR, and NOT are used.
How to test for NULL Values?
SQL allows queries that check whether an attribute value is NULL. Rather than using = or to compare an attribute value to NULL, SQL uses IS and IS NOT. This is because SQL considers each NULL value as being distinct from every other NULL value, so equality comparison is not appropriate.
Now, consider the following Employee Table,
Suppose if we find the Fname, Lname of the Employee having no Super_ssn then the query will be:
Query
SELECT Fname, Lname FROM Employee WHERE Super_ssn IS NULL;
Output:
Now if we find the Count of the number of Employees having Super_ssn.
Query:
SELECT COUNT(*) AS Count FROM Employee WHERE Super_ssn IS NOT NULL;
Output:
varshachoudhary
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
OLAP Guidelines (Codd's Rule)
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
KDD Process in Data Mining | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 605,
"s": 53,
"text": "In SQL there may be some records in a table that do not have values or data for every field. This could be possible because at a time of data entry information is not availab... |
install command in Linux with examples | 22 May, 2019
install command is used to copy files and set attributes. It is used to copy files to a destination of the user’s choice, If the user want to download and install a ready to use package on GNU/Linux system then he should use apt-get, apt, yum, etc depending on their distribution.
Syntax:
install [OPTION]... [-T] SOURCE DEST
install [OPTION]... SOURCE... DIRECTORY
install [OPTION]... -t DIRECTORY SOURCE...
install [OPTION]... -d DIRECTORY...
Here, the first three forms are used to copy the SOURCE to DEST or multiple SOURCE(s) to the existing DIRECTORY while setting permission modes and owner/group. But the fourth form is used to create all components of the given DIRECTORY.
Options:
–backup[=CONTROL] : This option is used to create a backup of each existing destination file.
-b : Like –backup but It will not accept an argument.
-C, –compare : Used to compare each pair of source and destination files. But in some cases it does not modify the destination.
-d, –directory : It will act as directory names towards all arguments. And create all components of the specified directories.
-g, –group=GROUP : Used to set group ownership, instead of processing the current group.
-m, –mode=MODE : Set permission mode (as in chmod).
-o, –owner=OWNER : Set ownership (super-user only).
-p, –preserve-timestamps : Apply access/modification times of SOURCE files to corresponding destination files
-t, –target-directory=DIRECTORY : Copy all SOURCE arguments into DIRECTORY.
-T, –no-target-directory : Treat DEST as a normal file.
-v, –verbose : Used to show the name of each directory as it is created.
–help : Display the help message and exit.
–version : Shows the version information and exit.
Examples:
Copies two files rocket.c and rocket to directory demo.
Compare and copies files(observe the difference).
Using -T option(observe that it makes a file instead of directory).
Changing owner and permissions.
Printing version information.
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
Compiling with g++
UDP Server-Client implementation in C
Head command in Linux with examples
nohup Command in Linux with Examples
ZIP command in Linux with examples
'dd' command in Linux
Tail command in Linux with examples
Conditional Statements | Shell Script | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 335,
"s": 54,
"text": "install command is used to copy files and set attributes. It is used to copy files to a destination of the user’s choice, If the user want to download and install a ready to ... |
Python | time.time_ns() method | 05 Sep, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method.
The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Note: time.time_ns() method is new in Python version 3.7
Syntax:time.time_ns()
Parameter:No parameter is required.
Return type:This method returns an integer value whichrepresents the time in nanoseconds since the epoch.
Code: Use of time.time_ns() method
# Python program to explain time.time_ns() method # importing time module import time # Get the epoch obj = time.gmtime(0) epoch = time.asctime(obj) print("epoch is:", epoch) # Get the time in seconds # since the epoch # using time.time() methodtime_sec = time.time() # Get the time in nanoseconds# since the epoch# using time.time_ns() methodtime_nanosec = time.time_ns() # Print the time # in seconds since the epoch print("Time in seconds since the epoch:", time_sec) # Print the time # in nanoseconds since the epoch print("Time in nanoseconds since the epoch:", time_nanosec)
epoch is: Thu Jan 1 00:00:00 1970
Time in seconds since the epoch: 1567451658.4676464
Time in nanoseconds since the epoch: 1567451658467647709
References: https://docs.python.org/3/library/time.html#time.time_ns
python-utility
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules."
},
{
"code": null,
"e": 318,
"s": 15... |
How to Boot Linux ISO Image Directly from Hard Drive | 17 Jun, 2021
To Boot Linux ISO Image Directly from Hard Drive, you must have a Linux operating system installed on your hard drive and your computer must be using a GRUB2 bootloader. The GRUB2 bootloader is a standard bootloader on most Linux systems.
Note: The downloaded ISO file of Linux must be a live CD release of each Linux ISO image.
1) First of all, search for the ISO file on Google which you want to download. To download these Linux distributions you may visit:
Ubuntu : https://ubuntu.com/download
debian : https://www.debian.org/CD/http-ftp/
LinuxMint : https://linuxmint.com/download.php
RedHat: https://www.redhat.com/en/store
2) Let us take the example of downloading Ubuntu.
Visit the official website and navigate to the download tab.
Select the Ubuntu desktop for downloading.
Select the LTS(Long Term Support) version of Ubuntu for downloading.
Your download will start in a few seconds.
The “device name” scheme used by GRUB is a different scheme than Linux. In your Linux system, /dev/sda1 is the first partition on the first hard disk, where a means the first hard disk and 1 means its first partition. In GRUB, (hd0,1) is equivalent to /dev/sda0 where 0 means the first hard disk and 1 means the first partition on it. That means that in a GRUB device name, the disk numbers start counting at 0 and the partition numbers start counting at 1. For example, (hd2,5) refers to the fifth partition on the third hard disk.
To view the information, we use the fdisk -l command on Ubuntu’s terminal and use the following command:
sudo fdisk -l
A list of Linux device paths is shown, which you can convert to GRUB device names on your own.
The best way by which you can add a custom boot entry is by editing the /etc/grub.d/40_custom script, which is a file designed for user-added custom boot entries. After you are done editing the file, every content of your /etc/defaults/grub file and the /etc/grub.d/ scripts will get combined and create a /boot/grub/grub.cfg file.
Note: You shouldn’t edit this file by hand. It’s designed to be automatically generated from the settings you specify in other files.
You’ll need to open the /etc/grub.d/40_custom file for editing with root privileges. On Ubuntu, you can do this by opening a Terminal window and running the following command:
sudo gedit /etc/grub.d/40_custom
You can open this file in your favorite editor by just replacing gedit with your editor name.
So to boot an Ubuntu or Ubuntu-based distribution from an ISO file. We tested this with Ubuntu 20.04:
menuentry “Ubuntu 20.04 ISO” {
set isofile=”/home/nikhil/ubuntu-20.04.1-desktop-amd64.iso”
loopback loop (hd0,1)$isofile
linux (loop)/casper/vmlinuz.efi boot=casper iso-scan/filename=${isofile} quiet splash
initrd (loop)/casper/initrd.lz
}
Note:
You can customize the boot entry to contain your desired menu entry name, the correct path to the ISO file on your pc, and the device name of the hard disk and partition containing the ISO file. If the vmlinuz and initrd files have different names or paths, be sure to specify the correct path to those files, too.
Different Linux distributions require different boot entries with different boot options. The GRUB Live ISO Multiboot project offers a variety of menu entries for different Linux distributions. You should be able to adapt these example menu entries for the ISO file you want to boot or you can also just perform a web search for the name and release number of the Linux distribution you want to boot along with “boot from ISO in GRUB” to find more information.
If you want to add more ISO boot options, add additional sections to the file, otherwise just save the file and return to the terminal window.
To update GRUB run the following command:
sudo update-grub
The next time you boot your computer, you’ll see the ISO boot entry and you can choose to boot the ISO file. You may have to hold Shift while booting to see the GRUB menu.
Note: If you see an error message or a black screen when you attempt to boot the ISO file, you misconfigured the boot entry somewhere. Even if you got the ISO file path and device name right, the paths to the vmlinuz and intird files on the ISO file may not be correct or the Linux system you’re booting may require different options.
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "To Boot Linux ISO Image Directly from Hard Drive, you must have a Linux operating system installed on your hard drive and your computer must be using a GRUB2 bootloader. The ... |
What are the different kinds of Doctypes available ? | 28 Nov, 2021
A doctype declaration or document type declaration is information to the browser about what document type should it expect. It is not an HTML tag. All the HTML documents that you code should start with a <!DOCTYPE> declaration.
The doctype declaration is written just above the <html> tag, at the very start of each document you write.
HTML5 doctype: This is the most latest version of the document type currently used. It has no disadvantages and is easier to implement and recall. It will correctly validate all HTML 5 features, as well as most of HTML 4/XHTML 1.0 features.
Syntax:
<!DOCTYPE html>
Strict doctype (HTML 4.01): The HTML 4.01 strict doctype validates the written code against the HTML 4.01 spec. However, it doesn’t allow any deprecated elements or presentational markups such as <font> elements, or framesets to be used. It validates loose HTML style markup, for example, minimized attributes and non-quoted attributes (eg required, rather than required=”required”).
Syntax:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
Transitional doctype (HTML 4.01): The HTML 4.01 transitional doctype also validates the written code against the HTML 4.01 spec, the same as the strict doctype. It does allow some presentational markup and deprecated elements (such as <font> elements) but not framesets. Just like strict doctype, it also validates loose HTML style markup.
Syntax:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
Strict and Transitional doctypes (XML 1.0): These are the exact XHTML 1.0 coequals of the HTML 4.01 doctypes we talked about above, so functionally they are the same, except that they won’t validate loose HTML style markup: it all has to be well-formed XML.
Syntax:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
And
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Frameset doctypes (HTML 4.01 and XML 1.0): They are functionally the same as HTML 4.01 transitional and XHTML 1.0 transitional independently, but they allow the use of framesets.
Note: We would suggest that you should avoid using framesets and the frameset doctype. They are outdated and are not used in modern times and coding practices.
If you want to use framesets and still have your markup validated, you can use one of these two doctypes:
Syntax:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
And,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
Other doctypes: There are some more ancient and rare versions of doctypes but they are even more outdated than the frameset doctype. In case you come across any other doctype, that is not mentioned here it is because they are not used anymore. Chances are that the code you find such doctypes is itself written or used in earlier versions.
Example:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>GeeksforGeeks</title> </head> <body> <h2>What are the different kinds of Doctypes?</h2> </body></html>
Output:
HTML-Questions
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 282,
"s": 54,
"text": "A doctype declaration or document type declaration is information to the browser about what document type should it expect. It is not an HTML tag. All the HTML documents that... |
Exit codes in C/C++ with Examples | 23 Jun, 2021
The purpose of the exit() function is to terminate the execution of a program. The “return 0”(or EXIT_SUCCESS) implies that the code has executed successfully without any error. Exit codes other than “0”(or EXIT_FAILURE) indicate the presence of an error in the code. Among all the exit codes, the codes 1, 2, 126 – 165 and 255 have special meanings and hence these should be avoided for user-defined exit codes.Syntax
void exit(int return_code)
Note: It is also to taken into consideration that an exit code with a value greater than 255 returns an exit code modulo 256.For Example: If we execute a statement exit(9999) then it will execute exit(15) as 9999%256 = 15.Some of the Exit Codes are:
exit(1): It indicates abnormal termination of a program perhaps as a result a minor problem in the code.
exit(2): It is similar to exit(1) but is displayed when the error occurred is a major one. This statement is rarely seen.
exit(127): It indicates command not found.
exit(132): It indicates that a program was aborted (received SIGILL), perhaps as a result of illegal instruction or that the binary is probably corrupt.
exit(133): It indicates that a program was aborted (received SIGTRAP), perhaps as a result of dividing an integer by zero.
exit(134): It indicates that a program was aborted (received SIGABRT), perhaps as a result of a failed assertion.
exit(136): It indicates that a program was aborted (received SIGFPE), perhaps as a result of floating point exception or integer overflow.
exit(137): It indicates that a program took up too much memory.
exit(138): It indicates that a program was aborted (received SIGBUS), perhaps as a result of unaligned memory access.
exit(139): It indicates Segmentation Fault which means that the program was trying to access a memory location not allocated to it. This mostly occurs while using pointers or trying to access an out-of-bounds array index.
exit(158/152): It indicates that a program was aborted (received SIGXCPU), perhaps as a result of CPU time limit exceeded.
exit(159/153): It indicates that a program was aborted (received SIGXFSZ), perhaps as a result of File size limit exceeded.
Hence the various exit codes help the user to debug the code. For instance, if one receives an exit code of 139, this implies that the code has a segmentation fault and the code can be debugged accordingly.Program 1: Below program will give Segmentation Fault:
CPP
// C++ program to demonstrate Segmentation Fault#include <iostream>using namespace std; // Driver Codeint main(){ // An array of size 100 int arr[100] = { 0 }; // When we try to access the array out // of bound, it will give Segmentation Fault cout << arr[100001]; return 0;}
Output: Below is the output of the above program:
Program 2: Below program will give Floating Point Error:
CPP
// C++ program to demonstrate// Floating Point Error#include <iostream>using namespace std; // Driver Codeint main(){ int a = 1, b = 0; // When we try to divide by zero // it should give SIGFPE cout << a / b; return 0;}
Output: Below is the output of the above program:
Program 3: Below program will give Time Limit Exceed:
CPP
// C++ program to demonstrate TLE#include <iostream>using namespace std; // Driver Codeint main(){ // Below statement will give time // limit exceeded as well as memory // limit exceeded due to infinite loop for (;;) { int arr[10000]; } return 0;}
Output: Below is the output of the above program:
ruhelaa48
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
Sorting a Map by value in C++ STL
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
C++ program for hashing with chaining
C++ Program to check if a given String is Palindrome or not | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 473,
"s": 52,
"text": "The purpose of the exit() function is to terminate the execution of a program. The “return 0”(or EXIT_SUCCESS) implies that the code has executed successfully without any err... |
How to find a HTML tag that contains certain text using BeautifulSoup ? | 30 Jun, 2021
In this article, we are going to see how to find an HTML tag that contains certain text using BeautifulSoup.
Methods used:
Open( filename, mode ): It opens the given filename in that mode which we have passed.
find_all ( ): It finds all the pattern in the file which will match with the passed expression.
Here, in the given below code, we are finding a certain text mentioned as a pattern in the program, in various different tags. Now the code will provide all these tags which will have the text matched with the pattern.
Approach:
Here we first import the regular expressions and BeautifulSoup libraries. Then we open the HTML file using the open function which we want to parse. Then using the find_all function, we find a particular tag that we pass inside that function and also the text we want to have within the tag. If the passed tag has that certain text, then it is added to a list.
So all the tags having certain text are stored in a list and then the list is printed. If we get the empty list, then it means that there is no such tag having the text we were trying to check.
Below is the HTML file for demonstration:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GFG </title></head><body> <a href="https://www.geeksforgeeks.org/">Geeks For Geeks</a> <a href="Dummy Check Text">Geeks For Geeks</a> <a href="Dummywebsite.com">Dummy Text</a> <h1>Hello</h1> <h1>Python Program</h1> <span class = true>Geeks For Geeks</span> <span class = false>Geeks For Geeks</span> <li class = 1 >Python Program</li> <li class = 2 >Python Code</li> <table> <tr>GFG Website</tr> </table> </body></html>
Output:
Below is the implementation:
Python3
# Python program to find a HTML tag# that contains certain text Using BeautifulSoup # Importing libraryfrom bs4 import BeautifulSoupimport re # Opening and reading the html filefile = open("gfg.html", "r")contents = file.read() soup = BeautifulSoup(contents, 'html.parser') # Finding a pattern(certain text)pattern = 'Geeks For Geeks' # Anchor tagtext1 = soup.find_all('a', text = pattern)print(text1) # Span tagtext2 = soup.find_all('span', text = pattern) print(text2) # Finding a pattern(certain text)pattern2 = 'Python Program' # Heading tagtext3 = soup.find_all('h1', text = pattern2) print(text3) # List tagtext4 = soup.find_all('li', text = pattern2) print(text4) # Finding a pattern(certain text)pattern3 = 'GFG Website' # Table(row) tagtext5 = soup.find_all('tr', text = pattern3) print(text5)
Output:
[<a href=”https://www.geeksforgeeks.org/”>Geeks For Geeks</a>, <a href=”Dummy Check Text”>Geeks For Geeks</a>]
[<span class=”true”>Geeks For Geeks</span>, <span class=”false”>Geeks For Geeks</span>]
[<h1>Python Program</h1>]
[<li class=”1′′>Python Program</li>]
[<tr>GFG Website</tr>]
ysachin2314
Picked
Python BeautifulSoup
Python bs4-Exercises
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "In this article, we are going to see how to find an HTML tag that contains certain text using BeautifulSoup."
},
{
"code": null,
"e": 151,
"s": 137,
"text"... |
How to read the contents of a JSON file using Java? | JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document −
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program.
Following is the maven dependency for the JSON-simple library −
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency> 301 to 305
</dependencies>
Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)
First of all, let us create a JSON document with name sample.json with the 6 key-value pairs as shown below −
{
"ID": "1",
"First_Name": "Shikhar",
"Last_Name": "Dhawan",
"Date_Of_Birth": "1981-12-05",
"Place_Of_Birth":"Delhi",
"Country": "India"
}
To read the contents of a JSON file using a Java program −
Instantiate the JSONParser class of the json-simple library.
JSONParser jsonParser = new JSONParser();
Parse the contents of the obtained object using the parse() method.
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json"));
Retrieve the value associated with a key using the get() method.
String value = (String) jsonObject.get("key_name");
Following Java program parses the above created sample.json file, reads its contents and, displays them.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingJSON {
public static void main(String args[]) {
//Creating a JSONParser object
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/sample.json"));
String id = (String) jsonObject.get("ID");
String first_name = (String) jsonObject.get("First_Name");
String last_name = (String) jsonObject.get("Last_Name");
String date_of_birth = (String) jsonObject.get("Date_Of_Birth");
String place_of_birth = (String) jsonObject.get("Place_Of_Birth");
String country = (String) jsonObject.get("Country");
//Forming URL
System.out.println("Contents of the JSON are: ");
System.out.println("ID :"+id);
System.out.println("First name: "+first_name);
System.out.println("Last name: "+last_name);
System.out.println("Date of birth: "+date_of_birth);
System.out.println("Place of birth: "+place_of_birth);
System.out.println("Country: "+country);
System.out.println(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Contents of the JSON are:
ID :1
First name: Shikhar
Last name: Dhawan
Date of birth :1981-12-05
Place of birth: Delhi
Country: India | [
{
"code": null,
"e": 1431,
"s": 1187,
"text": "JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document −"
},
{... |
Int32.Parse(String) Method in C# with Examples | 12 Jun, 2019
Int32.Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent.
Syntax:
public static int Parse (string str);
Here, str is a string that contains a number to convert. The format of str will be [optional white space][optional sign]digits[optional white space].
Return Value: It is a 32-bit signed integer equivalent to the number contained in str.
Exceptions:
ArgumentNullException: If str is null.
FormatException: If str is not in the correct format.
OverflowException: If str represents a number less than MinValue or greater than MaxValue.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to demonstrate// Int32.Parse(String) Methodusing System; class GFG { // Main Method public static void Main() { // passing different values // to the method to check checkParse("2147483647"); checkParse("214,7483,647"); checkParse("-2147483"); checkParse(" 2183647 "); } // Defining checkParse method public static void checkParse(string input) { try { // declaring Int32 variable int val; // getting parsed value val = Int32.Parse(input); Console.WriteLine("'{0}' parsed as {1}", input, val); } catch (FormatException) { Console.WriteLine("Can't Parsed '{0}'", input); } }}
'2147483647' parsed as 2147483647
Can't Parsed '214,7483,647'
'-2147483' parsed as -2147483
' 2183647 ' parsed as 2183647
Example 2: For ArgumentNullException
// C# program to demonstrate// Int32.Parse(String) Method// for ArgumentNullExceptionusing System; class GFG { // Main Method public static void Main() { try { // passing null value as a input checkParse(null); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining checkparse method public static void checkParse(string input) { // declaring Int32 variable int val; // getting parsed value val = Int32.Parse(input); Console.WriteLine("'{0}' parsed as {1}", input, val); }}
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.parse?view=netframework-4.7.2#System_Int32_Parse_System_String_
CSharp-Int32-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "Int32.Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent."
},
{
"code": null,
"e": 161,
"s":... |
PHP | strftime() Function | 06 Jul, 2021
The strftime() function is an inbuilt function in PHP that formats local time or date according to locale settings i.e. it formats local time or date for location set for it of a place.
Syntax:
strftime( $format, $timestamp )
Parameters: This function accept two parameters as mentioned above and described below:
$format: This parameter defines the format for the date and time it is a must required parameter.
$timestamp: The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().
Return Values: It returns a string formatted to $format using the given $timestamp(if mentioned explicitly, otherwise takes default time). Month and weekday names and other language-dependent strings respect the current locale set with setlocale().
Example:
PHP
<?php // This program prints the current daysetlocale(LC_TIME, "C");echo strftime("%A");?>
Output:
Thursday
Format: Following are the values that can be added to $format for a desired output.
Hour formatting:
Time and Date stamps formatting:
Day formatting:
Week formatting:
Month formatting:
Year formatting:
Miscellaneous formatting:
Below examples illustrate the application of strftime() in php:
Example 1: A simple program to display the date and time provided to it.
PHP
<?php // Displays the dateecho strftime("%d, %B, %Y", strtotime("01/03/2004")); // Displays the timeecho strftime(" %I:%M %p", strtotime("21:34"));?>
Output:
03, January, 2004 09:34 PM
Example 2: This example display the time at a specific region (an additional function, setlocale() is employed for this. For setlocale() to work, locales should be supported by your server.)
PHP
<?php // Setting locale to germansetlocale(LC_ALL, "de");echo strftime("The current german time is %r"); // Setting locale to englishsetlocale(LC_ALL, "en");echo strftime(" and the current english time is %r");?>
Output:
The current german time is 22:14:20 and the current english time is 10:14:20 PM
Reference: https://www.php.net/manual/en/function.strftime.php
Akanksha_Rai
varshagumber28
PHP-date-time
PHP-function
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
How to create admin login page using PHP?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "The strftime() function is an inbuilt function in PHP that formats local time or date according to locale settings i.e. it formats local time or date for location set for it o... |
Structure and Types of IP Address | 07 Jul, 2022
An IP address represents an Internet Protocol address. A unique address that identifies the device over the network. It is almost like a set of rules governing the structure of data sent over the Internet or through a local network. An IP address helps the Internet to distinguish between different routers, computers, and websites. It serves as a specific machine identifier in a specific network and helps to improve visual communication between source and destination.
IP address structure: IP addresses are displayed as a set of four digits- the default address may be 192.158.1.38. Each number on the set may range from 0 to 255. Therefore, the total IP address range ranges from 0.0.0.0 to 255.255.255.255.
IP address is basically divided into two parts: X1. X2. X3. X4
1. [X1. X2. X3] is the Network ID
2. [X4] is the Host ID
Network ID– It is the part of the left-hand IP address that identifies the specific network where the device is located. In the normal home network, where the device has an IP address 192.168.1.32, the 192.168.1 part of the address will be the network ID. It is customary to fill in the last part that is not zero, so we can say that the device’s network ID is 192.168.1.0.Hosting ID– The host ID is part of the IP address that was not taken by the network ID. Identifies a specific device (in the TCP / IP world, we call devices “host”) in that network. Continuing with our example of the IP address 192.168.1.32, the host ID will be 32- the unique host ID on the 192.168.1.0 network.
Network ID– It is the part of the left-hand IP address that identifies the specific network where the device is located. In the normal home network, where the device has an IP address 192.168.1.32, the 192.168.1 part of the address will be the network ID. It is customary to fill in the last part that is not zero, so we can say that the device’s network ID is 192.168.1.0.
Hosting ID– The host ID is part of the IP address that was not taken by the network ID. Identifies a specific device (in the TCP / IP world, we call devices “host”) in that network. Continuing with our example of the IP address 192.168.1.32, the host ID will be 32- the unique host ID on the 192.168.1.0 network.
Version of IP address:
Currently there are 2 versions of IP addresses are in use i.e IPV4 and IPV6
IPV4 (Internet Protocol Version 4): It is the first version of Internet Protocol address. The address size of IPV4 is 32 bit number. In this Internet Protocol Security (IPSec) with respect to network security is optional. It is having 4,294,967,296 number of address still we are seeing a shortage in network addresses as the use of network & virtual devices are increasing rapidly.IPV6 (Internet Protocol Version 6): It is the recent version of Internet Protocol address. The address size of IPV4 is 128 bit number. In this Internet Protocol Security (IPSec) with respect to network security is mandatory. It allows 3.4 x 1038 unique IP addresses which seems to be more than sufficient to support trillions of internet devices present now or coming in future.
IPV4 (Internet Protocol Version 4): It is the first version of Internet Protocol address. The address size of IPV4 is 32 bit number. In this Internet Protocol Security (IPSec) with respect to network security is optional. It is having 4,294,967,296 number of address still we are seeing a shortage in network addresses as the use of network & virtual devices are increasing rapidly.
IPV6 (Internet Protocol Version 6): It is the recent version of Internet Protocol address. The address size of IPV4 is 128 bit number. In this Internet Protocol Security (IPSec) with respect to network security is mandatory. It allows 3.4 x 1038 unique IP addresses which seems to be more than sufficient to support trillions of internet devices present now or coming in future.
IP Address Types:There are 4 types of IP Addresses- Public, Private, Fixed, and Dynamic. Among them, public and private addresses are derived from their local network location, which should be used within the network while public IP is used offline.
Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.Static IP Address–A static IP address is an invalid IP address. Conversely, a dynamic IP address will be provided by the Dynamic Host Configuration Protocol (DHCP) server, which can change. The Static IP address does not change but can be changed as part of normal network management.Static IP addresses are incompatible, given once, remain the same over the years. This type of IP also helps you get more information about the device.Dynamic IP address–It means constant change. A dynamic IP address changes from time to time and is not always the same. If you have a live cable or DSL service, you may have a strong IP address. Internet Service Providers provide customers with dynamic IP addresses because they are too expensive. Instead of one permanent IP address, your IP address is taken out of the address pool and assigned to you. After a few days, weeks, or sometimes even months, that number is returned to the lake and given a new number. Most ISPs will not provide a static IP address to customers who live there and when they do, they are usually more expensive. Dynamic IP addresses are annoying, but with the right software, you can navigate easily and for free.
Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.
Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.
Static IP Address–A static IP address is an invalid IP address. Conversely, a dynamic IP address will be provided by the Dynamic Host Configuration Protocol (DHCP) server, which can change. The Static IP address does not change but can be changed as part of normal network management.Static IP addresses are incompatible, given once, remain the same over the years. This type of IP also helps you get more information about the device.
Dynamic IP address–It means constant change. A dynamic IP address changes from time to time and is not always the same. If you have a live cable or DSL service, you may have a strong IP address. Internet Service Providers provide customers with dynamic IP addresses because they are too expensive. Instead of one permanent IP address, your IP address is taken out of the address pool and assigned to you. After a few days, weeks, or sometimes even months, that number is returned to the lake and given a new number. Most ISPs will not provide a static IP address to customers who live there and when they do, they are usually more expensive. Dynamic IP addresses are annoying, but with the right software, you can navigate easily and for free.
Types of Website IP address: Website IP address is of two types- Dedicated IP Address and Shared IP Address. Let us discuss the two.
Dedicated IP address–A dedicated IP address is one that is unique for each website. This address is not used by any other domain. A dedicated IP address is beneficial in many ways. It provides increased speed when the traffic load is high and brings in increased security. But dedicated IPs are costly as compared to shared IPs. Shared IP address–A shared IP address is one that is not unique. It is shared between multiple domains. A shared IP address is enough for most users because common configurations don’t require a dedicated IP.
Dedicated IP address–A dedicated IP address is one that is unique for each website. This address is not used by any other domain. A dedicated IP address is beneficial in many ways. It provides increased speed when the traffic load is high and brings in increased security. But dedicated IPs are costly as compared to shared IPs.
Shared IP address–A shared IP address is one that is not unique. It is shared between multiple domains. A shared IP address is enough for most users because common configurations don’t require a dedicated IP.
IP Address Classification Based on Operational Characteristics:According to operational characteristics, IP address is classified as follows:
Broadcast addressing–The term ‘Broadcast’ means to transmit audio or video over a network. A broadcast packet is sent to all users of a local network at once. They do not have to be explicitly named as recipients. The users of a network can open the data packets and then interpret the information, carry out the instructions or discard it. This service is available in IPv4. The IP address commonly used for broadcasting is 255.255.255.255Unicast addressing–This address identifies a unique node on the network. Unicast is nothing but one-to-one data transmission from one point in the network to another. It is the most common form of IP addressing. This method can be used for both sending and receiving data. It is available in IPv4 and IPv6. Multicast IP addresses–These IP addresses mainly help to establish one-to-many communication. Multicast IP routing protocols are used to distribute data to multiple recipients. The class D addresses (224.0.0.0 to 239.255.255.255) define the multicast group.Anycast addressing–In anycast addressing the data, a packet is not transmitted to all the receivers on the network. When a data packet is allocated to an anycast address, it is delivered to the closest interface that has this anycast address.
Broadcast addressing–The term ‘Broadcast’ means to transmit audio or video over a network. A broadcast packet is sent to all users of a local network at once. They do not have to be explicitly named as recipients. The users of a network can open the data packets and then interpret the information, carry out the instructions or discard it. This service is available in IPv4. The IP address commonly used for broadcasting is 255.255.255.255
Unicast addressing–This address identifies a unique node on the network. Unicast is nothing but one-to-one data transmission from one point in the network to another. It is the most common form of IP addressing. This method can be used for both sending and receiving data. It is available in IPv4 and IPv6.
Multicast IP addresses–These IP addresses mainly help to establish one-to-many communication. Multicast IP routing protocols are used to distribute data to multiple recipients. The class D addresses (224.0.0.0 to 239.255.255.255) define the multicast group.
Anycast addressing–In anycast addressing the data, a packet is not transmitted to all the receivers on the network. When a data packet is allocated to an anycast address, it is delivered to the closest interface that has this anycast address.
Satyabrata_Jena
Cyber-security
Network-security
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 524,
"s": 52,
"text": "An IP address represents an Internet Protocol address. A unique address that identifies the device over the network. It is almost like a set of rules governing the structure ... |
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 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 182,
"s": 54,
"text": "Introduction: Learn about Selecting data from MySQL database using node.js. We are going to use standard SELECT FROM SQL Query."
},
{
"code": null,
"e": 190,
... |
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 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "In this article we are going to learn about SetBackgroundColour() function associated with wx.StaticText class of wxPython. SetBackgroundColour() function is simply used to se... |
Feeding JSON Data to Kafka Topic Using Rest Proxy | 22 Nov, 2021
This POC describes the procedure of feeding JSON format data to a Kafka Topic using Kafka REST Proxy, that which provides a RESTful interface to a Kafka cluster.
Before you start this procedure, ensure that :
Administrative access to running Kafka VM and that VM must have connectivity as described in the loading Prerequisites.
Identify and note the Zoo-Keeper hostname and port.
Identify and note the hostname and port of the Kafka broker(s).
Identify and note the hostname and port of the Kafka Rest Proxy.
Note: This procedure assumes that you have installed the Apache Kafka distribution. If you are using a different Kafka distribution, you may need to adjust certain commands in the procedure.
Here, In this Use case, we have configured hostnames and ports with the following
rest-proxy localhost: 8082
zookeeper localhost: 2182
bootstrap-server localhost: 9095
Step 1: Log in to a host in your Kafka VM.
$ cd kafka_2.12-2.4.0 /*if this directory does not exit, Use ls command to view the folder and copy/paste the existing folder*/
To list out, all the topics which are present inside that kafka topics, use the below cmd
$ bin/kafka-topics.sh --list --zookeeper localhost:2182 /*To check/verify and to display all the topics*/
Step 2: Create a Kafka topic. Here, create a topic named “topic-test-1” with a single partition and only one replica:
For example:
$ bin/kafka-topics.sh --create --zookeeper localhost:2182 --replication-factor 1 --partitions 1 --topic topic-test-1
$ bin/kafka-topics.sh --list --zookeeper localhost:2182 /*To verify or to list out the created topic*/
Step 3: Create a JSON file. Create a file named sample- json-data.json in the editor of your choice.
For example:
$ vi sample-json-data.json
then, paste some json format text and add it to a file, and then save the file and exit
For example:
{
"first_name": "Tom",
"last_name": "Cruze",
"email": "cruze@gmail.com",
"gender": "Male",
"ip_address": "1.2.3.4"
}
Step 4: To stream the contents of the json file to a Kafka console producer
$ bin/kafka-console-producer.sh --broker-list localhost:9095 --topic topic-test-1 < sample-json-data.json
Step 5: To verify that the Kafka console producer published the messages to the topic by running a Kafka console consumer
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9095 --topic topic-test-1 --from-beginning
Step 6: To stream the contents of the other JSON file to a Kafka console producer
For example:
$ vi sample.json
then, paste some JSON format text and add it to a file, and then save the file and exit
{ “cust_id”: 1313131, “month”: 12, “expenses”: 1313.13 }
{ “cust_id”: 3535353, “month”: 11, “expenses”: 761.35 }
{ “cust_id”: 7979797, “month”: 10, “expenses”: 4489.00 }
{ “cust_id”: 7979797, “month”: 11, “expenses”: 18.72 }
{ “cust_id”: 3535353, “month”: 10, “expenses”: 6001.94 }
{ “cust_id”: 7979797, “month”: 12, “expenses”: 173.18 }
{ “cust_id”: 1313131, “month”: 10, “expenses”: 492.83 }
{ “cust_id”: 3535353, “month”: 12, “expenses”: 81.12 }
{ “cust_id”: 1313131, “month”: 11, “expenses”: 368.27 }
The Kafka REST Proxy provides a RESTful interface to a Kafka cluster. It makes it easy to produce and consume messages, view the state of the cluster, and perform administrative actions without using the native Kafka protocol or clients.
To get the list of topics using curl
$ curl "http://localhost:8082/topics"
To get the info of one topic
$ curl http://localhost:8082/topics/<menction topic name>
For example:
$ curl "http://localhost:8082/topics/topic-test-1"
Step 1: To Produce a message using JSON with a value to a topic
For example, to produce a message using JSON with a value ‘{ “month”: 12}’ to the topic topic-test-1
$ curl -X POST -H “Content-Type: application/vnd.kafka.json.v2+json” \
-H “Accept: application/vnd.kafka.v2+json” \
–data ‘{“records”:[{“value”:{“month”: 12}}]}’ “http://localhost:8082/topics/topic-test-1”
/*Expected output from preceding command*/
{
“offsets”:[{“partition”:0,”offset”:16,”error_code”:null,”error”:null}],”key_schema_id”:null,”value_schema_id”:null
}
To verify that the Kafka console producer published the messages to the topic by running a Kafka console consumer
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9095 --topic topic-test-1 --from-beginning
Step 2: Create a consumer for JSON data, starting at the beginning of the topic’s
$ curl -X POST -H "Content-Type: application/vnd.kafka.v2+json" \
--data '{"name": "my_consumer_instance", "format": "json", "auto.offset.reset": "earliest"}' \ http://localhost:8082/consumers/my_json_consumer
/* Expected output from preceding command*/
{
"instance_id":"my_consumer_instance",
"base_uri":"http://localhost:8082/consumers/my_json_consumer/instances/my_consumer_instance"
OR
"base_uri":"http://rest-proxy:8082/consumers/my_json_consumer/instances/my_consumer_instance"
}
Step 3: Log and subscribe to a topic.
$ curl -X POST -H "Content-Type: application/vnd.kafka.v2+json" --data '{"topics":["topic-test-1"]}' \
http://localhost:8082/consumers/my_json_consumer/instances/my_consumer_instance/subscription
/* Expected output from preceding command*/
# No content in response
Step 4: To consume some data using the base URL in the first response.
$ curl -X GET -H "Accept: application/vnd.kafka.json.v2+json" \
http://localhost:8082/consumers/my_json_consumer/instances/my_consumer_instance/records
Optional Steps:
Step 1: Finally, to close the consumer with a DELETE to make it leave the group and clean up its resources.
$ curl -X DELETE -H "Content-Type: application/vnd.kafka.v2+json" \
http://localhost:8082/consumers/my_json_consumer/instances/my_consumer_instance
/* Expected output from preceding command*/
# No content in response
Step 2: verify the consumer instance using the following command
$ curl -X GET -H "Accept: application/vnd.kafka.json.v2+json" \
http://localhost:8082/consumers/my_json_consumer/instances/my_consumer_instance/records
/* Expected output from preceding command*/
{ “error_code”: 40403, “message”: “Consumer instance not found.” }
Apache
Advanced Computer Subject
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "This POC describes the procedure of feeding JSON format data to a Kafka Topic using Kafka REST Proxy, that which provides a RESTful interface to a Kafka cluster."
},
{
... |
Simple Recursive solution to check whether BST contains dead end | 28 Jun, 2022
Given a Binary Search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any integer element after that node.Examples:
Input : 8
/ \
5 9
/ \
2 7
/
1
Output : Yes
Explanation : Node "1" is the dead End because
after that we cant insert any element.
Input : 8
/ \
7 10
/ / \
2 9 13
Output :Yes
Explanation : We can't insert any element at
node 9.
We have discussed a solution in below post.Check whether BST contains Dead End or notThe idea in this post is based on method 3 of Check if a binary tree is BST or not.First of all, it is given that it is a BST and nodes are greater than zero, root node can be in the range [1, ∞] and if root val is say, val, then left sub-tree can have the value in the range [1, val-1] and right sub-tree the value in range [val+1, ∞]. we need to traverse recursively and when the min and max value of range coincided it means that we cannot add any node further in the tree. Hence we encounter a dead end.Following is the simple recursive solution to the problem.
C++
Java
Python3
C#
Javascript
// CPP Program to check if there is a dead end// in BST or not.#include <bits/stdc++.h>using namespace std; // A BST nodestruct Node { int data; struct Node *left, *right;}; // A utility function to create a new nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // Returns true if tree with given root contains// dead end or not. min and max indicate range// of allowed values for current node. Initially// these values are full range.bool deadEnd(Node* root, int min=1, int max=INT_MAX){ // if the root is null or the recursion moves // after leaf node it will return false // i.e no dead end. if (!root) return false; // if this occurs means dead end is present. if (min == max) return true; // heart of the recursion lies here. return deadEnd(root->left, min, root->data - 1) || deadEnd(root->right, root->data + 1, max);} // Driver programint main(){ /* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ Node* root = NULL; root = insert(root, 8); root = insert(root, 5); root = insert(root, 2); root = insert(root, 3); root = insert(root, 7); root = insert(root, 11); root = insert(root, 4); if (deadEnd(root) == true) cout << "Yes " << endl; else cout << "No " << endl; return 0;}
// Java Program to check if there// is a dead end in BST or not.class BinarySearchTree { // Class containing left and right // child of current node and key value class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // This method mainly calls insertRec() void insert(int data) { root = insertRec(root, data); } // A recursive function // to insert a new key in BST Node insertRec(Node root, int data) { // If the tree is empty, // return a new node if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); /* return the (unchanged) node pointer */ return root; } // Returns true if tree with given root contains// dead end or not. min and max indicate range// of allowed values for current node. Initially// these values are full range.boolean deadEnd(Node root, int min, int max){ // if the root is null or the recursion moves // after leaf node it will return false // i.e no dead end. if (root==null) return false; // if this occurs means dead end is present. if (min == max) return true; // heart of the recursion lies here. return deadEnd(root.left, min, root.data - 1)|| deadEnd(root.right, root.data + 1, max);} // Driver Program public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(3); tree.insert(7); tree.insert(11); tree.insert(4); if (tree.deadEnd(tree.root ,1 , Integer.MAX_VALUE) == true) System.out.println("Yes "); else System.out.println("No " ); }} // This code is contributed by Gitanjali.
# Python 3 Program to check if there# is a dead end in BST or not. class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # A utility function to insert a# new Node with given key in BSTdef insert(node, key): # If the tree is empty, # return a new Node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.data: node.left = insert(node.left, key) elif key > node.data: node.right = insert(node.right, key) # return the (unchanged) Node pointer return node # Returns true if tree with given# root contains dead end or not.# min and max indicate range# of allowed values for current node.# Initially these values are full range.def deadEnd(root, Min, Max): # if the root is null or the recursion # moves after leaf node it will return # false i.e no dead end. if root == None: return False # if this occurs means dead # end is present. if Min == Max: return True # heart of the recursion lies here. return (deadEnd(root.left, Min, root.data - 1) or deadEnd(root.right, root.data + 1, Max)) # Driver Codeif __name__ == '__main__': # 8 # / \ # 5 11 # / \ # 2 7 # \ # 3 # \ # 4 root = None root = insert(root, 8) root = insert(root, 5) root = insert(root, 2) root = insert(root, 3) root = insert(root, 7) root = insert(root, 11) root = insert(root, 4) if deadEnd(root, 1, 9999999999) == True: print("Yes") else: print("No") # This code is contributed by PranchalK
using System; // C# Program to check if there// is a dead end in BST or not.public class BinarySearchTree{ // Class containing left and right // child of current node and key value public class Node { private readonly BinarySearchTree outerInstance; public int data; public Node left, right; public Node(BinarySearchTree outerInstance, int item) { this.outerInstance = outerInstance; data = item; left = right = null; } } // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // This method mainly calls insertRec() public virtual void insert(int data) { root = insertRec(root, data); } // A recursive function // to insert a new key in BST public virtual Node insertRec(Node root, int data) { // If the tree is empty, // return a new node if (root == null) { root = new Node(this, data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) { root.left = insertRec(root.left, data); } else if (data > root.data) { root.right = insertRec(root.right, data); } /* return the (unchanged) node pointer */ return root; } // Returns true if tree with given root contains// dead end or not. min and max indicate range// of allowed values for current node. Initially// these values are full range.public virtual bool deadEnd(Node root, int min, int max){ // if the root is null or the recursion moves // after leaf node it will return false // i.e no dead end. if (root == null) { return false; } // if this occurs means dead end is present. if (min == max) { return true; } // heart of the recursion lies here. return deadEnd(root.left, min, root.data - 1) || deadEnd(root.right, root.data + 1, max);} // Driver Program public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(3); tree.insert(7); tree.insert(11); tree.insert(4); if (tree.deadEnd(tree.root,1, int.MaxValue) == true) { Console.WriteLine("Yes "); } else { Console.WriteLine("No "); } }} // This code is contributed by Shrikant13
<script>// javascript Program to check if there// is a dead end in BST or not. // Class containing left and right // child of current node and key value class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } // Root of BST var root = null; // This method mainly calls insertRec() function insert(data) { root = insertRec(root, data); } // A recursive function // to insert a new key in BST function insertRec(root , data) { // If the tree is empty, // return a new node if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); /* return the (unchanged) node pointer */ return root; } // Returns true if tree with given root contains// dead end or not. min and max indicate range// of allowed values for current node. Initially// these values are full range.function deadEnd(root , min , max){ // if the root is null or the recursion moves // after leaf node it will return false // i.e no dead end. if (root==null) return false; // if this occurs means dead end is present. if (min == max) return true; // heart of the recursion lies here. return deadEnd(root.left, min, root.data - 1)|| deadEnd(root.right, root.data + 1, max);} // Driver Program /* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ insert(8); insert(5); insert(2); insert(3); insert(7); insert(11); insert(4); if (deadEnd(root ,1 , Number.MAX_VALUE) == true) document.write("Yes "); else document.write("No " ); // This code contributed by Rajput-Ji</script>
Output:
Yes
vishal22091998
shrikanth13
PranchalKatiyar
Rajput-Ji
surinderdawra388
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "Given a Binary Search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.