code-rag-bench/online-tutorials huggingface dataset:
Check For Star Graph

A graph is given; we have to check the given graph is a star graph or not.
By traversing the graph, we have to find the number of vertices has degree one, and number of vertices, whose degree is n-1. (Here n is the number of vertices in the given graph). When the number of vertices with degree 1 is n-1 and a number of vertices with a degree (n-1) is one, then it is a star graph.
Input:
The adjacency matrix:
0 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0

Output:
It is a star graph.
checkStarGraph(graph)
Input: The given Graph.
Output: True when the graph is a star graph.
Begin
   degOneVert := 0 and degNminOneGraph := 0
   if graph has only one vertex, then
      return true, if there is no self-loop
   else if graph has two vertices, then
      return true if there is only one vertex between two vertices
   else
      for all vertices i in the graph, do
         degree := 0
         for all vertices j, adjacent with i, do
            degree := degree + 1
         done
         if degree = 1, then
            degOneVert := degOneVert + 1
         else if degree = n-1, then
            degNminOneGraph := degNminOneGraph + 1
      done

   if degOneVert = n-1, and degNminOneGraph = 1, then
      return true
   otherwise return false
End
#include<iostream>
#define NODE 4
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 1, 1},
   {1, 0, 0, 0},
   {1, 0, 0, 0},
   {1, 0, 0, 0}
};

bool checkStarGraph() {
   int degOneVert = 0, degVert = 0;    //initially vertex with degree 1 and with degree n - 1 are 0
   if (NODE == 1)    //when there is only one node
      return (graph[0][0] == 0);

   if (NODE == 2)  
      return (graph[0][0] == 0 && graph[0][1] == 1 && graph[1][0] == 1 && graph[1][1] == 0 );

   for (int i = 0; i < NODE; i++) {    //for graph more than 2
      int degree = 0;
      for (int j = 0; j < NODE; j++)    //count degree for vertex i
         if (graph[i][j])
            degree++;
      if (degree == 1)
         degOneVert++;
      else if (degree == NODE-1)
         degVert++;
   }
   //when only vertex of degree n-1, and all other vertex of degree 1, it is a star graph
   return (degOneVert == (NODE-1) && degVert == 1);
}

int main() {
   if(checkStarGraph())
      cout << "It is a star graph.";
   else
     cout << "It is not a star graph.";
}
It is a star graph.
Bisect Algorithm Functions in Python

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion of new element. We will focus on two functions namely insort_left and insort_right.
This function returns the sorted list after inserting number in the required position, if the element is already present in the list, the element is inserted at the leftmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered. The default value of the beginning and end position is 0 and length of the string respectively.
This is similar to inser_left except that the new element is inserted after inserting existing entries without maintaining a strict sort order.
bisect.insort_left(a, x, lo=0, hi=len(a))
bisect.insort_left(a, x, lo=0, hi=len(a))
a is the given sequence
x is the number to be inserted
In the example below we see that we take a list and first apply bisect.insort_left function to it.
 Live Demo
import bisect

listA = [11,13,23,7,13,15]
print("Given list:",listA)
bisect.insort_left(listA,14)
print("Bisect left:\n",listA)

listB = [11,13,23,7,13,15]
print("Given list:",listB)
bisect.insort_right(listB,14,0,4)
print("Bisect righ:\n",listB)
Running the above code gives us the following result −
Given list: [11, 13, 23, 7, 13, 15]
Bisect left:
   [11, 13, 23, 7, 13, 14, 15]
Given list: [11, 13, 23, 7, 13, 15]
Bisect righ:
   [11, 13, 14, 23, 7, 13, 15]
Matplotlib – How to set xticks and yticks with imshow plot?

To set xticks and yticks with imshow() plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Get the current axis.
Create a random dataset.
Display the data as an image, i.e., on a 2D regular raster.
Set x and y ticks using set_xticks() and set_yticks() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

ax = plt.gca()
data = np.random.rand(6, 6)
ax.imshow(data)

# Set xticks and yticks
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([1, 2, 3, 4, 5])

plt.show()
It will produce the following output
How to remove only the first word from columns values with a MySQL query?

To remove only the first word from column values, use substring(). Following is the syntax −
select substring(yourColumnName,locate(' ',yourColumnName)+1) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
   Title text
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Java in Depth');
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable values('C++ is an object oriented programming language');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values('MySQL is a relational database');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Python with data structure');
Query OK, 1 row affected (0.24 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------------------------------------------+
| Title                                          |
+------------------------------------------------+
| Java in Depth                                  |
| C++ is an object oriented programming language |
| MySQL is a relational database                 |
| Python with data structure                     |
+------------------------------------------------+
4 rows in set (0.00 sec)
Following is the query to remove the first word from column values −
mysql> select substring(Title,locate(' ',Title)+1) AS RemoveFirstWord from DemoTable;
This will produce the following output −
+--------------------------------------------+
| RemoveFirstWord                            |
+--------------------------------------------+
| in Depth                                   |
| is an object oriented programming language |
| is a relational database                   |
| with data structure                        |
+--------------------------------------------+
4 rows in set (0.00 sec)
Java Program to Find the closest pair from two sorted arrays

To find the closest pair from two sorted array, the Java code is as follows −
 Live Demo
public class Demo {
   void closest_pair(int my_arr_1[], int my_arr_2[], int arr_1_len, int arr_2_len, int sum){
      int diff = Integer.MAX_VALUE;
      int result_l = 0, result_r = 0;
      int l = 0, r = arr_2_len-1;
      while (l<arr_1_len && r>=0){
         if (Math.abs(my_arr_1[l] + my_arr_2[r] - sum) < diff){
            result_l = l;
            result_r = r;
            diff = Math.abs(my_arr_1[l] + my_arr_2[r] - result_l);
         }
         if (my_arr_1[l] + my_arr_2[r] > result_l)
          r--;
         else
          l++;
      }
      System.out.print("The closest pair that matches two arrays is [" + my_arr_1[result_l] + ", " +
      my_arr_2[result_r] + "]");
   }
   public static void main(String args[]){
      Demo my_ob = new Demo();
      int my_arr_1[] = {56, 78, 99, 11};
      int my_arr_2[] = {33, 12, 69, 87};
      int arr_1_len = my_arr_1.length;
      int arr_2_len = my_arr_2.length;
      int val = 79;
      my_ob.closest_pair(my_arr_1, my_arr_2, arr_1_len, arr_2_len, val);
   }
}
The closest pair that matches two arrays is [56, 33]
A class named Demo contains a function named ‘closest_pair’, that iterates through both the arrays and checks to see which sum adds up to a number that is very near to a number previously specified. This pair from the array is returned as output. In the main function, a new instance of the Demo class is defined, the arrays are defined, and their lengths are assigned to two variables respectively. The function is called by passing the arrays, their lengths, and the value. The relevant message is displayed on the console.
Defining a discrete colormap for imshow in Matplotlib

To define a discrete colormap for imshow in matplotlib, we can take following the steps −
Create data using numpy.
Create data using numpy.
Initialize the data using get_cmap, so that scatter knows.
Initialize the data using get_cmap, so that scatter knows.
Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster.
Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster.
Create the colorbar using the colorbar() method.
Create the colorbar using the colorbar() method.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(10, 10)
cmap = matplotlib.cm.get_cmap('Paired_r', 10)
plt.imshow(data, cmap=cmap)
plt.colorbar()
plt.show()
How to clear an ImageView in Android using Kotlin?

This example demonstrates how to clear an ImageView in Android using Kotlin.
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/button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentBottom="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="10dp"
   android:onClick="clickHere"
   android:text="Click here" />
<ImageView
   android:id="@+id/imageView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_above="@+id/button"
   android:layout_centerInParent="true"
   android:background="@drawable/image" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
   lateinit var imageView: ImageView
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      imageView = findViewById(R.id.imageView)
   }
   fun clickHere(view: View) {
      imageView.setBackgroundDrawable(null)
      Toast.makeText(this, "Image cleared", Toast.LENGTH_SHORT).show()
   }
}
Step 4 − 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="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
Python - Extract words starting with K in String List - GeeksforGeeks

01 Aug, 2020
Given list of phrases, extract all the Strings with begin with character K.
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = lOutput : [‘learning’, ‘love’]Explanation : All elements with L as starting letter are extracted.
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = mOutput : []Explanation : No words started from “m” hence no word extracted.
Method #1 : Using loop + split()
This is brute way in which this problem can be solved. In this, we convert each phrase into list of words and then for each word, check if it’s initial character is K. 
Python3
# Python3 code to demonstrate working of # Extract words starting with K in String List# Using loop + split()  # initializing listtest_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = "g"  res = []for sub in test_list:    # splitting phrases    temp = sub.split()    for ele in temp:                  # checking for matching elements        if ele[0].lower() == K.lower():            res.append(ele)  # printing result print("The filtered elements : " + str(res))
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']


Method #2 : Using list comprehension + split() 
This is yet another way in which this task can be performed. In this we run double nested loops inside single list comprehension and perform required conditional checks.
Python3
# Python3 code to demonstrate working of # Extract words starting with K in String List# Using list comprehension + split()   # initializing listtest_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = "g"res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()]  # printing result print("The filtered elements : " + str(res))
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']


Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Check if binary representations of two numbers are anagram in Python

Suppose we have two numbers x and y we have to check whether the binary representation of x and y are anagram of each other or not.
So, if the input is like x = 9 y = 12, then the output will be True as binary representation of 9 is 1001 and binary representation of 12 is 1100, so these two are anagram of each other.
To solve this, we will follow these steps −
if number of 1s in x and y are same, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
 Live Demo
def set_bit_count(num) :
   cnt = 0
   while num:
      cnt += num & 1
      num >>= 1
   return cnt
def solve(x, y) :
   if set_bit_count(x) == set_bit_count(y):
      return True
   return False
x = 9
y = 12
print(solve(x, y))
9, 12
True
How to find set difference between two Numpy arrays?

In this program, we will find the set difference of two numpy arrays. We will use the setdiff1d() function in the numpy library. This function takes two parameters: array1 and array2 and returns the unique values in array1 that are not in array2.
Step 1: Import numpy.
Step 2: Define two numpy arrays.
Step 3: Find the set difference between these arrays using the setdiff1d() function.
Step 4: Print the output.
import numpy as np

array_1 = np.array([2,4,6,8,10,12])
print("Array 1: \n", array_1)

array_2 = np.array([4,8,12])
print("\nArray 2: \n", array_2)

set_diff = np.setdiff1d(array_1, array_2)
print("\nThe set difference between array_1 and array_2 is:\n",set_diff)
Array 1:
[ 2  4  6  8 10 12]
Array 2:
[ 4  8 12]
The set difference between array_1 and array_2 is:
[ 2  6 10]
Array 1 has elements 2, 6, and 10 which are not in Array 2. Hence [2 6 10] are is the set difference between the two arrays.
How to expire session after 1 min of inactivity in express-session of Express.js ? - GeeksforGeeks

09 Sep, 2021
In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js.
Prerequisites
Installation of Node.js on Windows
To set up Node Project in Editor see here.
Requires Modules:
npm install express
npm install express-session
Call API:
var session = require('express-session')
To expire the session after 1 min of inactivity in express-session of Express.js we use expires: 60000 in the middleware function.
Project Structure:
Below example illustrates above approach:
Example:
Filename: app.js
Javascript
// Call Express Api.var express = require('express'),     // Call express Session Api.    session = require('express-session'),     app = express(); // Session Setupapp.use(    session({         // It holds the secret key for session        secret: "I am girl",         // Forces the session to be saved        // back to the session store        resave: true,         // Forces a session that is "uninitialized"        // to be saved to the store        saveUninitialized: false,        cookie: {             // Session expires after 1 min of inactivity.            expires: 60000        }    })); // Get function in which send session as routes.app.get('/session', function (req, res, next) {     if (req.session.views) {         // Increment the number of views.        req.session.views++         // Session will expires after 1 min        // of in activity        res.write('<p> Session expires after 1 min of in activity: '+ (req.session.cookie.expires) + '</p>')        res.end()    } else {        req.session.views = 1        res.end(' New session is started')    }}) // The server object listens on port 3000.app.listen(3000, function () {    console.log("Express Started on Port 3000");});
Run index.js file using below command:
node app.js
Now to set your session, just open the browser and type this URL :
http://localhost:3000/session
 
Output: After 1 min of inactivity it will start the new session,old session is expired.
sagartomar9927
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
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?
How to create an array containing non-repeating elements in JavaScript ? - GeeksforGeeks

30 Nov, 2020
The following are the two approaches to generate an array containing n number of non-repeating random numbers.
Using do-while loop and includes() function.Using a set and checking with its size.
Using do-while loop and includes() function.
Using a set and checking with its size.
Using do-while loop and includes() function: Here, includes() function checks if an element is present in the array or not.
Filename: index.js
JavaScript
// You can take this value from userconst n = 5  // Initial empty arrayconst arr = [];  // Null checkif (n == 0) {    console.log(null)}  do {    // Generating random number    const randomNumber = Math        .floor(Math.random() * 100) + 1      // Pushing into the array only     // if the array does not contain it    if (!arr.includes(randomNumber)) {        arr.push(randomNumber);    }  } while (arr.length < n);  // Printing the array elementsconsole.log(arr)
Run the index.js file using the following command:
node index.js
Output:
[ 49, 99, 27, 86, 69 ]
Time complexity: 
O(n2)
Using a set and checking with its size: Remember that a set does not allow duplicate elements.
Filename: index.js
JavaScript
// You can take this value from userconst n = 5  // Initial empty arrayconst arr = [];  // Null Checkif (n == 0) {    console.log(null)}  let randomnumbers = new Set, ans;  // We keep adding elements till// size of set is equal to n while (randomnumbers.size < n) {      // Generating random number     // and adding it    randomnumbers.add(Math.floor(        Math.random() * 100) + 1);}  // Copying set elements into // the result arrayans = [...randomnumbers];  // Printing the arrayconsole.log(ans)
Run the index.js file using the following command:
node index.js
Output:
[ 52, 32, 50, 59, 95 ]
Time complexity:
O(n)
JavaScript-Misc
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
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?
Intersect two lists in C#

Firstly, set two lists.
List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };
Now, use the Intersect() method to get the intersection between two lists.
IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

class Demo {
   static void Main() {
      List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
      List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };
      IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
      Console.WriteLine("Intersection of both the lists...");
      foreach (int a in res) {
         Console.WriteLine(a);
      }
   }
}
Intersection of both the lists...
40
95
110
Calendar setTimeInMillis() Method in Java with Examples - GeeksforGeeks

06 Mar, 2019
The setTimeInMillis(long mill_sec) method in Calendar class is used to set Calendars time represented by this Calendar from the passed long value.
Syntax:
public void setTimeInMillis(long mill_sec)
Parameters: The method takes one parameter mill_sec of long datat-type and refers to the given date that is to be set.
Return Value: The method does not return any value.
Below programs illustrate the working of setTimeInMillis() Method of Calendar class:Example 1:
// Java code to illustrate// setTimeInMillis() method  import java.util.*;  public class Calendar_Demo {    public static void main(String args[])    {          // Creating calendar object        Calendar calndr = Calendar.getInstance();          // Getting the time in milliseconds        System.out.println("The Current"                           + " Time is: "                           + calndr.getTime());          // Changing time to 2000 milli-second        calndr.setTimeInMillis(2000);          // Displaying the new time        System.out.println("After setting"                           + " Time: "                           + calndr.getTime());    }}
The Current Time is: Fri Feb 22 08:00:54 UTC 2019
After setting Time: Thu Jan 01 00:00:02 UTC 1970

Example 2:
// Java code to illustrate// setTimeInMillis() method  import java.util.*;  public class Calendar_Demo {    public static void main(String args[])    {          // Creating calendar object        Calendar calndr = Calendar.getInstance();          // Getting the time in milliseconds        System.out.println("The Current"                           + " Time is: "                           + calndr.getTime());          // Changing time to 8000 milli-second        calndr.setTimeInMillis(8000);          // Displaying the new time        System.out.println("After setting"                           + " Time: "                           + calndr.getTime());    }}
The Current Time is: Fri Feb 22 08:01:02 UTC 2019
After setting Time: Thu Jan 01 00:00:08 UTC 1970

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long)
Java - util package
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
Set Theory & Algebra - GeeksforGeeks

21 Jan, 2014
*
a
b
c
d
a
a
b
c
d
b
b
a
d
c
c
c
d
b
a
d
d
c
a
b
Check for all:-
a1 = a ,
a2 = a * a = a
a3 = a2 * a = a * a = a
a is not the generator since we are not able to express 
other members of the group in powers of a

Check for c -
c1 = c
c2 = c * c = b
c3 = c2 * c = b * c = d
c4 = c2 * c2 = b * b = a
We are able to generate all the members of the group from c ,
Hence c is the generator

Similarly check for d

If P, Q, R are subsets of the universal set U, then 
   
U 
Pc U Qc U Rc 
P U Qc U Rc 
Qc U Rc 
Consider an example set, S = (1,2,3)

Equivalence property follows, reflexive, symmetric
and transitive

Largest ordered set are s x s = 
{ (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) 
(3,3) } which are 9 which equal to 3^2 = n^2

Smallest ordered set are { (1,1) (2,2) ( 3,3)}
which are 3 and equals to n. number of elements.
2 can be written as 2 power 2.
Number of partitioning of 2 = no. of non isomorphic
                              abelian groups
2 can be partitioned as {(2),(1,1)}
D 
C 
B 
A 
A partition is said to refine another partition if it splits the sets in the second partition to a larger number of sets. Corresponding Hasse diagram is Option C. 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Python – Fill list characters in String

29 Aug, 2020
Given String and list, construct a string with only list values filled.
Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’, ‘f’, k]Output : g__ksf__g__ksExplanation : All occurrences are filled in their position of g, s, f and k.
Input : test_str = “geeksforgeeks”, fill_list = [‘g’, ‘s’]Output : g___s___g___sExplanation : All occurrences are filled in their position of g and s.
Method #1 : Using loop
This is brute force approach to this problem. In this, we iterate for all the elements in string, if it’s in list we fill it, else fill with “space” value.
Python3
# Python3 code to demonstrate working of # Fill list characters in String # Using loop  # initializing stringtest_str = "geeksforgeeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing fill list fill_list = ['g', 's', 'f']  # loop to iterate through string res = ""for chr in test_str:          # checking for presence    if chr in fill_list:        temp = chr    else:        temp = "_"    res += temp  # printing result print("The string after filling values : " + str(res)) 
The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Method #2 : Using join() + list comprehension
The combination of above functions can be used to solve this problem. In this, we formulate logic using list comprehension and join() is used to perform join of required values using conditions.
Python3
# Python3 code to demonstrate working of # Fill list characters in String # Using join() + list comprehension  # initializing stringtest_str = "geeksforgeeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing fill list fill_list = ['g', 's', 'f']  # join() used to concatenate result # using conditionals in list comprehensionres = "".join([chr if chr in fill_list else "_"                for chr in list(test_str)])  # printing result print("The string after filling values : " + str(res)) 
The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Python list-programs
Python string-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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to get current_url using Selenium in Python?

06 Mar, 2020
While doing work with selenium many URL get opened and redirected in order to keeping track of URL current_url method is used. The current_url method is used to retrieve the URL of the webpage the user is currently accessing. It gives the URL of the current webpage loaded by the driver in selenium.
URL : URL is the abbreviation of Uniform Resource Locator and is defined as the global address of documents and other resources on the World Wide Web, for example, to visit GeeksforGeeks website, you’ll go to the URL https://www.geeksforgeeks.org/ .
Syntax :
driver.current_url

Argument :
It takes no argument.
Return value :It return the URL in string format.
# Importing webdriver from seleniumfrom selenium import webdriver  # Here chrome webdriver is useddriver = webdriver.Chrome()  # URL of the website url = "https://www.geeksforgeeks.org/"  # Opening the URLdriver.get(url)  # Getting current URLget_url = driver.current_url  # Printing the URLprint(get_url)
Output :
https://www.geeksforgeeks.org/
Code 2:
# Importing webdriver from seleniumfrom selenium import webdriver  # Here chrome webdriver is useddriver = webdriver.Chrome()  # URL of the website url = "https://www.geeksforgeeks.org/"  # Getting current URLget_url = driver.current_url  # Printing the URLprint(get_url)  # Opening the URLdriver.get(url)  # Getting current URLget_url = driver.current_url  # Printing the URLprint(get_url)
Output :
data:,
https://www.geeksforgeeks.org/

Note: Here “data:, ” is printed because at that time no webpage is opened.
Python-selenium
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to align text content into center using JavaScript ?

05 Nov, 2021
In this article, we will align the text content into center by using JavaScript. TWe use HTML DOM style textAlign property to set the alignment of text.
Syntax:
object.style.textAlign = "center"
The above syntax set the text alignment into center dynamically.
Example:
HTML
<!DOCTYPE html><html> <head>    <title>        How to align text content into        center using JavaScript ?    </title></head> <body>    <h1 style="color: green;">GeeksforGeeks</h1>     <h3>        How to align text content into        center using JavaScript ?    </h3>     <p id="content">        GeeksforGeeks: A computer        science portal for geeks    </p>        <button onclick="myFunction();">        Set Alignment    </button>     <script type="text/javascript">         function myFunction() {            let txt = document.getElementById("content");            txt.style.textAlign = "center";        }    </script></body> </html>
Output:
Before Button Click:
After Button Click:
Supported Browsers: 
Google Chrome
Internet Explorer
Mozilla Firefox
Opera
Safari
ysachin2314
chhabradhanvi
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM lastModified Property

08 Jul, 2022
The DOM lastModified property in HTML is used to return the date and time of the current document that was last modified. This property is read-only. This property returns a string which contains the date and time when the document was last modified. 
Syntax:
document.lastModified
Example: 
html
<!DOCTYPE html><html> <head>    <title>      DOM lastModified Property    </title></head> <body style="text-align:center">     <h1 style="color:green;">            GeeksForGeeks        </h1>     <h2>            DOM lastModified Property        </h2>    <button onclick="geeks()">        Submit    </button>     <p id="sudo"></p>     <script>        /* Function to use lastModified property */        function geeks() {            var x = document.lastModified;            document.getElementById("sudo").innerHTML = x;        }    </script></body> </html>    
Output:
  
Supported Browsers: The browser supported by DOM lastModified Property are listed below:
Google Chrome 1
Edge 12
Internet Explorer 4
Firefox 1
Opera 12.1
Safari 1
geeksr3ap
HTML-DOM
HTML
Web Technologies
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
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 ?
Generating hash id’s using uuid3() and uuid5() in Python

21 Sep, 2021
Python’s UUID class defines four functions and each generates different version of UUIDs. Let’s see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID’s taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are :  
uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string.uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string.
uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string.
uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string.
uuid module defines the following namespace identifiers for use with uuid3() or uuid5() :  
NAMESPACE_DNS : Used when name string is fully qualified domain name. NAMESPACE_URL : Used when name string is a URL. NAMESPACE_OID : Used when name string is an ISO OID. NAMESPACE_X500 : Used when name string is an X.500 DN in DER or a text output format.  
  Code #1 :  
Python3
# Python3 code to demonstrate working# of uuid3() and uuid5()import uuid # initializing a stringurl = "https://www.geeksforgeeks.org/fibonacci-sum-subset-elements/" # using NAMESPACE_URL as namespace# to generate MD5 hash uuidprint ("The SHA1 hash value generated ID is : ",            uuid.uuid3(uuid.NAMESPACE_URL, url)) # using NAMESPACE_URL as namespace # to generate SHA-1 hash uuidprint ("The MD5 hash value generated ID is : ",            uuid.uuid5(uuid.NAMESPACE_URL, url))
The SHA1 hash value generated ID is :  e13a319e-16d9-3ff5-a83c-96564007998e
The MD5 hash value generated ID is :  dbe3178d-4b83-5024-9b26-9b8e1b280514
 
 Code #2 :  
Python3
# Python3 code to demonstrate working # of uuid3() and uuid5()import uuid # initializing a stringqualified_dns = "www.geeksforgeeks.org" # using NAMESPACE_DNS as namespace# to find MD5 hash idprint ("The SHA1 hash value generated ID is : ",    uuid.uuid3(uuid.NAMESPACE_DNS, qualified_dns)) # using NAMESPACE_DNS as namespace# to generate SHA-1 hash idprint ("The MD5 hash value generated ID is : ",    uuid.uuid5(uuid.NAMESPACE_DNS, qualified_dns))
The SHA1 hash value generated ID is :  adbed9f7-bbe3-376f-b88d-2018b8f6db07
The MD5 hash value generated ID is :  f72cdf8a-b361-50b2-9451-37a997f8675d
 
  Note : The ID generation is 2 step process. First, the concatenation of string and namespaces takes place, then given as input to the respective function to return a 128 UUID generated. If the same NAMESPACE value with a similar string is chosen again, ID generated will be same as well. Reference : https://docs.python.org/2/library/uuid.html 
simmytarika5
Python-Library
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Up-sampling in MATLAB

01 Oct, 2020
Interpolation or up-sampling is the specific inverse of decimation. It is a data saving operation, in that all examples of x[n] are available in the extended signal y[n]. Interpolation works by adding (L–1) zero-valued examples for each input sample. 
We will be using the interp() function to interpolate a signal. It is used to increase the sample rate of a signal by an integer factor.
Syntax: a = interp(x, r) Parameter:  
x: input signal
r: interpolation factor
Return Value: Returns interpolated signal  
MATLAB code for interpolation of a signal:
MATLAB
% time vectort = 0 : .00025 : 1;  # input signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t);  % increase the sample rate of i/p signal by factor of 4y = interp(x, 4);   subplot(2, 2, 1);  % plot few samples of the Original signalstem(x(1 : 75)) title('Original Signal');  subplot(2, 2, 2);  % plots few samples of the up-sampled signalstem(y(1 : 75)); title('Interpolated Signal');
Output:
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Decision Tree Introduction with example
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
How to Run a Python Script using Docker?
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Using range in switch case in C/C++

In C or C++, we have used the switch-case statement. In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement.
The syntax of using range in Case is like below −
case low ... high
After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.
In the following program, we will see what will be the output for the range based case statement.
#include <stdio.h>
main() {
   int data[10] = { 5, 4, 10, 25, 60, 47, 23, 80, 14, 11};
   int i;
   for(i = 0; i < 10; i++) {
      switch (data[i]) {
         case 1 ... 10:
            printf("%d in range 1 to 10\n", data[i]);
         break;
         case 11 ... 20:
            printf("%d in range 11 to 20\n", data[i]);
         break;
         case 21 ... 30:
            printf("%d in range 21 to 30\n", data[i]);
         break;
         case 31 ... 40:
            printf("%d in range 31 to 40\n", data[i]);
         break;
         default:
            printf("%d Exceeds the range\n", data[i]);
         break;
      }
   }
}
5 in range 1 to 10
4 in range 1 to 10
10 in range 1 to 10
25 in range 21 to 30
60 Exceeds the range
47 Exceeds the range
23 in range 21 to 30
80 Exceeds the range
14 in range 11 to 20
11 in range 11 to 20
Lodash _.isObject() Method

05 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise. 
Syntax:
_.isObject(value)
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is an object, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library  const _ = require("lodash");       // Use of _.isObject()  // method   console.log(_.isObject('GeeksforGeeks')); console.log(_.isObject(1)); console.log(_.isObject([1, 2, 3]));
Output:
false
false
true
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");       // Use of _.isObject()  // method   console.log(_.isObject({})); console.log(_.isObject(null)); console.log(_.isObject(_.noop)); 
Output:
true
false
true
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
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 ?
Angular7 - Modules

Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application.
In case you are developing a website, the header, footer, left, center and the right section become part of a module.
To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';

@NgModule({
   declarations: [
      AppComponent,
      NewCmpComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
The NgModule needs to be imported as follows −
import { NgModule } from '@angular/core';

The structure for the ngmodule is as shown below −
@NgModule({ 
   declarations: [
      AppComponent, 
      NewCmpComponent 
   ],
   imports: [ 
      BrowserModule, 
      AppRoutingModule 
   ], 
   providers: [], 
   bootstrap: [AppComponent] 
})
It starts with @NgModule and contains an object which has declarations, imports, providers and bootstrap.
It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below −
declarations: [ 
   AppComponent,  
   NewCmpComponent 
]

It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule, we see the Browser Module imported. In case your application needs forms, you can include the module with the below code −
import { FormsModule } from '@angular/forms';

The import in the @NgModule will be like the following −
imports: [ 
   BrowserModule, 
   FormsModule 
]

This will include the services created.
This includes the main app component for starting the execution.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Find maximum value from a VARCHAR column in MySQL

To find maximum value, use MAX() along with CAST(), since the values are of VARCHAR type. Let us first create a table −
mysql> create table DemoTable2030
   -> (
   -> Value varchar(20)
   -> );
Query OK, 0 rows affected (0.44 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2030 values('8');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2030 values('1');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable2030 values('10001');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable2030 values('901');
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement &miuns;
mysql> select *from DemoTable2030
This will produce the following output −
+-------+
| Value |
+-------+
| 8     |
| 1     |
| 10001 |
| 901   |
+-------+
4 rows in set (0.00 sec)
Following is the query to find maximum value from a VARCHAR column −
mysql> select max(cast(Value as unsigned)) from DemoTable2030;
This will produce the following output −
+------------------------------+
| max(cast(Value as unsigned)) |
+------------------------------+
| 10001                        |
+------------------------------+
1 row in set (0.00 sec)
Python - Check if all elements in a List are same

Sometimes we come across the need to check if we have one single value repeated in a list as list elements. We can check for such scenario using the below python programs. There are different approaches.
In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false.
 Live Demo
List = ['Mon','Mon','Mon','Mon']
result = True
# Get the first element
first_element = List[0]
# Compares all the elements with the first element
for word in List:
   if first_element != word:
      result = False
      print("All elements are not equal")
      break
   else:
      result = True
   if result:
      print("All elements are equal")
Running the above code gives us the following result −
All elements are equal
All elements are equal 
All elements are equal 
All elements are equal
The all() method applies the comparison for each element in the list. It is similar to what we have done in first approach but instead of for loop, we are using the all() method.
 Live Demo
List = ['Mon','Mon','Tue','Mon']
# Uisng all()method
result = all(element == List[0] for element in List)
if (result):
   print("All the elements are Equal")
else:
   print("All Elements are not equal")
Running the above code gives us the following result −
All the elements are not Equal
The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
 Live Demo
List = ['Mon','Mon','Mon','Mon']
# Result from count matches with result from len()
result = List.count(List[0]) == len(List)
if (result):
   print("All the elements are Equal")
else:
   print("Elements are not equal")
Running the above code gives us the following result −
All the elements are Equal