code-rag-bench/online-tutorials huggingface dataset:
How to open chrome default profile with selenium?

We can open Chrome default profile with Selenium. To get the Chrome profile path, we need to input chrome://version/ in the Chrome browser and then press enter.
We need to use the ChromeOptions class to open the default Chrome profile. We need to use the add_argument method to specify the path of the Chrome profile.
o = webdriver.ChromeOptions()
o.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}
Code Implementation
from selenium import webdriver
#object of ChromeOptions class
o = webdriver.ChromeOptions()
#adding Chrome Profile Path
o.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", options=o)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#get browser title
print(driver.title)
#quit browser
driver.quit()
Python Pandas - Fill NaN values using an interpolation method

Use the interpolate() method to fill NaN values. Let’s say the following is our CSV file opened in Microsoft Excel with some NaN values −
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
Fill NaN values with interpolate() −
dataFrame.interpolate()
Following is the code −
import pandas as pd

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
print("DataFrame...\n",dataFrame)

# fill NaN values with interpolate()
res = dataFrame.interpolate()
print("\nDataFrame after interpolation...\n",res)


This will produce the following output −
DataFrame...
       Car   Reg_Price   Units
0      BMW        2500   100.0
1    Lexus        3500     NaN
2     Audi        2500   120.0
3   Jaguar        2000     NaN
4  Mustang        2500   110.0

DataFrame after interpolation...
       Car   Reg_Price   Units
0      BMW        2500   100.0
1    Lexus        3500   110.0
2     Audi        2500   120.0
3   Jaguar        2000   115.0
4  Mustang        2500   110.0
java.time.LocalDate.compareTo() Method Example

The java.time.LocalDate.compareTo(ChronoLocalDate other) method compares this date to another date.
Following is the declaration for java.time.LocalDate.compareTo(ChronoLocalDate other) method.
public int compareTo(ChronoLocalDate other)

other − the other date to compare to, not null.
the comparator value, negative if less, positive if greater.
The following example shows the usage of java.time.LocalDate.compareTo(ChronoLocalDate other) method.
package com.tutorialspoint;

import java.time.LocalDate;

public class LocalDateDemo {
   public static void main(String[] args) {

      LocalDate date = LocalDate.parse("2017-02-03");
      System.out.println(date);  
      LocalDate date1 = LocalDate.parse("2017-03-03");
      System.out.println(date1);  
      System.out.println(date1.compareTo(date));  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03
2017-03-03
1

 Print
 Add Notes
 Bookmark this page
How to fully change the color of a Tkinter Listbox?

Tkinter Listbox widgets are very useful in the case of representing a large set of data items in form of list items. To configure the properties such as change the background color of the entire Listbox, we can use configure(**options) method to change the properties of the Listbox widget.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Add a Listbox widget with number as the list items
listbox =Listbox(win)
listbox.insert(END,"C++", "Java", "Python", "Rust", "GoLang", "Ruby", "JavScript", "C# ", "SQL", "Dart")
listbox.pack(side=LEFT, fill=BOTH)

listbox.configure(background="skyblue4", foreground="white", font=('Aerial 13'))

win.mainloop()
Running the above code will display a customized Listbox with some list items in it.
How to use a global variable in a Python function?

The terms, global and local correspond to a variable's reach within a script or program. A global variable is one that can be accessed anywhere. A local variable can be accessed only within its frame. A local variable cannot be accessed globally.
Global variables are the one that are defined and declared outside a function and can be used anywhere.
If a variable with same name is defined inside the scope of a function then it will print the value given inside the function only and not the global value.
The given code is re-written to show how the global variable is accessed both inside and outside the function foo.
# This function uses global variable k
k = "I like green tea"
def foo():
    print k #accessing global variable inside function
foo()
print k #accessing global variable outside function
 
C:/Users/TutorialsPoint1/~.py
I like green tea
I like green tea
Spring Boot & H2 - Console

As in previous chapter Application Setup, we've created the required files in spring boot project. Now let's update the application.properties lying in src/main/resources and pom.xml to use a different version of maven-resources-plugin.
application.properties
spring.datasource.url=jdbc:h2:mem:testdb

pom.xml
...
<build>
   <plugins>
      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-resources-plugin</artifactId>
         <version>3.1.0</version>
      </plugin>
   </plugins>
</build>
...
In eclipse, run the Employee Application configuration as prepared during Application Setup
Eclipse console will show the similar output.
[INFO] Scanning for projects...
[INFO] 
[INFO] -----------------< com.tutorialspoint:sprint-boot-h2 >------------------
[INFO] Building sprint-boot-h2 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
...
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.2)

...
2021-07-24 20:51:11.347  INFO 9760 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat initialized with port(s): 8080 (http)
...
2021-07-24 20:51:11.840  INFO 9760 --- [  restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration 
: H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
...
2021-07-24 20:51:14.805  INFO 9760 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat started on port(s): 8080 (http) with context path ''
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

Once server is up and running, open localhost:8080/h2-console in a browser and click on Test Connection to verify the database connection.
Click on Connect button and H2 database window will appear as shown below −

    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
Program to Reverse a String using Pointers - GeeksforGeeks

12 Jan, 2019
Given a string, the task is to reverse this String using pointers.
Examples:
Input: Geeks
Output: skeeG

Input: GeeksForGeeks
Output: skeeGroFskeeG

Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two pointers.
Program:
#include <stdio.h>#include <string.h>  // Function to reverse the string// using pointersvoid reverseString(char* str){    int l, i;    char *begin_ptr, *end_ptr, ch;      // Get the length of the string    l = strlen(str);      // Set the begin_ptr and end_ptr    // initially to start of string    begin_ptr = str;    end_ptr = str;      // Move the end_ptr to the last character    for (i = 0; i < l - 1; i++)        end_ptr++;      // Swap the char from start and end    // index using begin_ptr and end_ptr    for (i = 0; i < l / 2; i++) {          // swap character        ch = *end_ptr;        *end_ptr = *begin_ptr;        *begin_ptr = ch;          // update pointers positions        begin_ptr++;        end_ptr--;    }}  // Driver codeint main(){      // Get the string    char str[100] = "GeeksForGeeks";    printf("Enter a string: %s\n", str);      // Reverse the string    reverseString(str);      // Print the result    printf("Reverse of the string: %s\n", str);      return 0;}
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG

C-String
cpp-pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
Substring in C++
Enumeration (or enum) in C
Structures in C
Display text on an OpenCV window by using the function putText()

In this program, we will write text on an image using the opencv function putText(). This function takes in the image, font, coordinates of where to put the text, color, thickness, etc.
Step 1: Import cv2
Step 2: Define the parameters for the puttext( ) function.
Step 3: Pass the parameters in to the puttext() function.
Step 4: Display the image.
import cv2
image = cv2.imread("testimage.jpg")
text = "TutorialsPoint"
coordinates = (100,100)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
color = (255,0,255)
thickness = 2
image = cv2.putText(image, text, coordinates, font, fontScale, color, thickness, cv2.LINE_AA)
cv2.imshow("Text", image)
Combine Multiple Excel Worksheets Into a Single Pandas Dataframe - GeeksforGeeks

05 Sep, 2020
Prerequisites: Working with excel files using Pandas
In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let’s suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file.
 Approach :
Import-Module
Read Excel file and store into a DataFrame
Concat both DataFrame into a new DataFrame
Export DataFrame into an Excel File with DataFrame.to_excel() function
Below is the implementation.
Python3
# import moduleimport pandas as pd  # Read excel file# and store into a DataFramedf1 = pd.read_excel('excel_work\sample_data\Book_1.xlsx')df2 = pd.read_excel('excel_work\sample_data\Book_2.xlsx')  # concat both DataFrame into a single DataFramedf = pd.concat([df1, df2])  # Export Dataframe into Excel filedf.to_excel('final_output.xlsx', index=False)
Output :
Python pandas-io
Python-pandas
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
Drawing an image in canvas using in JavaScript

Following is the code for drawing an image in canvas using JavaScript −
 Live Demo
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Drawing an image in canvas</h1>
<img class="flower" width="300" height="300"
   src="https://i.picsum.photos/id/976/300/300.jpg?hmac=Gwae8T0kvhjbWyNIAiYgOckWbK
BHGr2p_6EEE29uDDg" />
<canvas class="canvas1" width="300" height="300" style="border: 1px solid #d3d3d3;">
</canvas><br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to draw the image in canvas</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
      var c = document.querySelector(".canvas1");
      var ctx = c.getContext("2d");
      var img = document.querySelector(".flower");
      ctx.drawImage(img, 10, 10);
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Find objects between two dates in MongoDB?

Use operator gteandlt to find objects between two dates in MongoDB. To understand these
operators, let us create a collection.
Creating a collection here:
>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2019-02-19")};
WriteResult({ "nInserted" : 1 })

>db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2019-02-26")};
WriteResult({ "nInserted" : 1 })
Display all documents from the collection with the help of find() method. The query is as follows:
> db.order.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
}
{
   "_id" : ObjectId("5c6c073568174aae23f5ef58"),
   "OrderId" : 2,
   "OrderAddrees" : "UK",
   "OrderDateTime" : ISODate("2019-02-26T00:00:00Z")
}
Here is the query to find objects between two dates:
> db.order.find({"OrderDateTime":{ $gte:ISODate("2019-02-10"), $lt:ISODate("2019-02-21") }
}).pretty();
The following is the output:
{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
}
How to create a sphere in R?

To create a sphere, we can use spheres3d function of rgl package. The rgl package is specifically designed to create real-time interactive 3D plots. If we want to create a sphere then we need to pass the values for the three axes and the radius of the sphere. We can also change the color of the sphere by introducing color argument inside spheres3d function.
Loading rgl package and creating a sphere:
> library(rgl)
> spheres3d(x=1,y=1,z=1,radius=1)
> spheres3d(0,0,0,radius=1,color="blue")
> spheres3d(0,0,0,radius=1,color="red")
Binary Search Program in C

Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in a sorted form.
#include <stdio.h>

#define MAX 20

// array of items on which linear search will be conducted. 
int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};

void printline(int count) {
   int i;
	
   for(i = 0;i <count-1;i++) {
      printf("=");
   }
	
   printf("=\n");
}

int find(int data) {
   int lowerBound = 0;
   int upperBound = MAX -1;
   int midPoint = -1;
   int comparisons = 0;      
   int index = -1;
	
   while(lowerBound <= upperBound) {
      printf("Comparison %d\n" , (comparisons +1) );
      printf("lowerBound : %d, intArray[%d] = %d\n",lowerBound,lowerBound,
         intArray[lowerBound]);
      printf("upperBound : %d, intArray[%d] = %d\n",upperBound,upperBound,
         intArray[upperBound]);
      comparisons++;
		
      // compute the mid point
      // midPoint = (lowerBound + upperBound) / 2;
      midPoint = lowerBound + (upperBound - lowerBound) / 2;	
		
      // data found
      if(intArray[midPoint] == data) {
         index = midPoint;
         break;
      } else {
         // if data is larger 
         if(intArray[midPoint] < data) {
            // data is in upper half
            lowerBound = midPoint + 1;
         }
         // data is smaller 
         else {
            // data is in lower half 
            upperBound = midPoint -1;
         }
      }               
   }
   printf("Total comparisons made: %d" , comparisons);
   return index;
}

void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i<MAX;i++) {
      printf("%d ",intArray[i]);
   }
	
   printf("]\n");
}

void main() {
   printf("Input Array: ");
   display();
   printline(50);
	
   //find location of 1
   int location = find(55);

   // if element was found 
   if(location != -1)
      printf("\nElement found at location: %d" ,(location+1));
   else
      printf("\nElement not found.");
}
If we compile and run the above program then it would produce following result −
Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]
==================================================
Comparison 1
lowerBound : 0, intArray[0] = 1
upperBound : 19, intArray[19] = 66
Comparison 2
lowerBound : 10, intArray[10] = 15
upperBound : 19, intArray[19] = 66
Comparison 3
lowerBound : 15, intArray[15] = 34
upperBound : 19, intArray[19] = 66
Comparison 4
lowerBound : 18, intArray[18] = 55
upperBound : 19, intArray[19] = 66
Total comparisons made: 4
Element found at location: 19


    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
Python Group by matching second tuple value in list of tuples

In this tutorial, we are going to write a program that groups all the tuples from a list that have same element as a second element. Let's see an example to understand it clearly.
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',
'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
We have to group the tuples from the list. Let's see the steps to solve the problem.
Initiate a list with required tuples.
Create an empty dictionary.
Iterate through the list of tuples.Check if the second element of the tuple is already present in the dictionary or not.If it already present, then append the current tuple to its list.Else initialize the key with a list with the current tuple.
Check if the second element of the tuple is already present in the dictionary or not.
If it already present, then append the current tuple to its list.
Else initialize the key with a list with the current tuple.
At the end, you will get a dictionary with the required modifications.
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict
result = {}
# iterating over the list of tuples
for tup in tuples:
   # checking the tuple element in the dict
   if tup[1] in result:
      # add the current tuple to dict
      result[tup[1]].append(tup)
   else:
      # initiate the key with list
      result[tup[1]] = [tup]
# priting the result
print(result)
If you run the above code, then you will get the following result.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}
We skip the if condition in the above program using defaultdict. Let's solve it using the defaultdict.
# importing defaultdict from collections
from collections import defaultdict
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict with defaultdict
result = defaultdict(list)
# iterating over the list of tuples
for tup in tuples:
   result[tup[1]].append(tup)
   # priting the result
   print(dict(result))
If you run the above code, then you will get the following result.
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}
You can solve it different in ways as you like. We have seen two ways here. If you have any doubts in the tutorial, mention them in the comment section.
MySQL query to return all records with a datetime older than 1 week

To get dates older than 1 week, you can use the following syntax −
select *from yourTableName where yourColumnName < now() - interval 1 week;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table DatesOfOneWeek
   −> (
   −> ArrivalTime datetime
   −> );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table −
mysql> insert into DatesOfOneWeek values(date_add(now(),interval 2 week));
Query OK, 1 row affected (0.11 sec)

mysql> insert into DatesOfOneWeek values('2018-11-04');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DatesOfOneWeek values('2018-11-25');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DatesOfOneWeek values(date_add(now(),interval -1 week));
Query OK, 1 row affected (0.14 sec)

mysql> insert into DatesOfOneWeek values(date_add(now(),interval 1 week));
Query OK, 1 row affected (0.11 sec)
Let us check the records which we have inserted above are present or not. The query to display all records from the table is as follows −
mysql> select *from DatesOfOneWeek;
The following is the output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2018-12-20 18:11:02 |
| 2018-11-04 00:00:00 |
| 2018-11-25 00:00:00 |
| 2018-11-29 18:11:40 |
| 2018-12-13 18:11:46 |
+---------------------+
5 rows in set (0.00 sec)
Here is the MySQL query to get a date which was in the past i.e. all the date before 1 week −
mysql> select *from DatesOfOneWeek where ArrivalTime < now() - interval 1 week;
The following is the output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2018-11-04 00:00:00 |
| 2018-11-25 00:00:00 |
| 2018-11-29 18:11:40 |
+---------------------+
3 rows in set (0.00 sec)
jQuery - Widget AutoComplete

The Widget AutoComplete function can be used with widgets in JqueryUI.The Autocomplete widgets provides suggestions while you type into the field.For suppose give Ja as an input, it will provides an output as Java or JavaScript.
Here is the simple syntax to use Autocomplete −
$( "#tags" ).autocomplete({
   source: availableTags
});

Following is a simple example showing the usage of Autocomplete −
<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Autocomplete - Default functionality</title>
		
      <link rel = "stylesheet" 
         href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
			
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
      </script>
  
      <script>
         $(function() {
            var availableTags = [
               "ActionScript",
               "AppleScript",
               "Asp",
               "BASIC",
               "C",
               "C++",
               "Clojure",
               "COBOL",
               "ColdFusion",
               "Erlang",
               "Fortran",
               "Groovy",
               "Haskell",
               "Java",
               "JavaScript",
               "Lisp",
               "Perl",
               "PHP",
               "Python",
               "Ruby",
               "Scala",
               "Scheme"
            ];
				
            $( "#tags" ).autocomplete({
               source: availableTags
            });
				
         });
      </script>
   </head>

   <body>
      <div class = "ui-widget">
         <label for = "tags">Tags: </label>
         <input id = "tags">
      </div>
 
   </body>
</html>
This will produce following result −

    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
Instant query() Method in Java with Examples - GeeksforGeeks

08 Jan, 2019
query() method of an Instant class used to query this instant using the specified query as parameter.The TemporalQuery object passed as parameter define the logic to be used to obtain the result from this instant.
Syntax:
public <R> R query(TemporalQuery<R> query)

Parameters: This method accepts only one parameter query which is the query to invoke.
Return value: This method returns the query result, null may be returned.
Exception: This method throws following Exceptions:
DateTimeException – if unable to query .
ArithmeticException – if numeric overflow occurs.
Below programs illustrate the query() method:
Program 1:
// Java program to demonstrate// Instant.query() method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // create Instant object        Instant instant            = Instant.parse("2018-12-31T10:15:30.00Z");          // apply query method of Instant class        String value            = instant.query(TemporalQueries.precision())                  .toString();          // print the result        System.out.println("Precision value for Instant is "                           + value);    }}
Precision value for Instant is Nanos

Program 2: Showing if query did not found the required object then it returns null.
// Java program to demonstrate// Instant.query() method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // create Instant object        Instant instant            = Instant.parse("2018-12-31T10:15:30.00Z");          // apply query method of Instant class        // print the result        System.out.println("Zone value for Instant is "                           + instant.query(TemporalQueries.offset()));    }}
Zone value for Instant is null

Reference:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#query(java.time.temporal.TemporalQuery)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
How do I declare and initialize an array in Java?

You can declare an array just like a variable −
int myArray[];
You can create an array just like an object using the new keyword −
myArray = new int[5];
You can initialize the array by assigning values to all the elements one by one using the index −
myArray [0] = 101;
myArray [1] = 102;
You can access the array element using the index values −
System.out.println("The first element of the array is: " + myArray [0]);
System.out.println("The first element of the array is: " + myArray [1]);
Alternatively, you can create and initialize an array using the flower braces ({ }):
Int [] myArray = {10, 20, 30, 40, 50}
TypeScript - Array some()

some() method tests whether some element in the array passes the test implemented by the provided function.
array.some(callback[, thisObject]);

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
If some element passes the test, then it returns true, otherwise false.
function isBigEnough(element, index, array) { 
   return (element >= 10); 
          
} 
          
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval ); 
          
var retval = [12, 5, 8, 1, 4].some(isBigEnough); 
console.log("Returned value is : " + retval );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned value is : false 
Returned value is : true


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Keywords in Java

Keywords in Java are reserved words that represent predefined actions, internal processes etc. Because of this, keywords cannot be used as names of variables, functions, objects etc.
The main difference between keywords and identifiers is that keywords are reserved words that represent predefined actions while identifiers are the names of variables, functions, objects etc.
Some of the keywords in the Java are given as follows −
A program that demonstrates keywords is given as follows −
 Live Demo
public class Example {
public static void main(String[] args) {
int i = 5;
char c = 'A';
System.out.println("i = " + i);
System.out.println("c = " + c);
}
}
i = 5
c = A
Now let us understand the above program.
The keywords in the above program are int and char that specify integer and character data types respectively. Also i and c are identifiers.
In the above program, the values of i and c are defined and then they are printed. The code snippet that demonstrates this is given as follows.
int i = 5;
char c = 'A';
System.out.println("i = " + i);
System.out.println("c = " + c);
time.Now() Function in Golang With Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Now() function in Go language is used to find the current local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Now() Time

Return Value: It returns the current local time.
Example 1:
// Golang program to illustrate the usage of// time.Now() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Now() method    tm := time.Now()      // Prints current     // local time in UTC    fmt.Printf("%s", tm)}
Output:
2020-04-09 11:24:14.785868848 +0000 UTC m=+0.000187421

Here, current time is returned in UTC.
Example 2:
// Golang program to illustrate the usage of// time.Now() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Now() method    tm := time.Now()    tm1 := time.Now()      // Prints current local time in UTC    fmt.Printf("%s\n", tm)      // Sleep for 10 seconds    time.Sleep(10 * time.Second)      // Prints the current time after 10    // seconds of the sleep is over    fmt.Printf("%s", tm1)}
Output:
2020-04-09 11:37:59.087484568 +0000 UTC m=+0.000106559
2020-04-09 11:37:59.087484779 +0000 UTC m=+0.000106736

GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Defer Keyword in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Class and Object in Golang
Rune in Golang
Function Arguments in Golang
H2 Database - Commit

COMMIT is a command from the SQL grammar used to commit the transaction. We can either commit the specific transaction or we can commit the currently executed transaction.
There are two different syntaxes for COMMIT command.
Following is the generic syntax for the commit command to commit the current transaction.
COMMIT [ WORK ] 

Following is the generic syntax for the commit command to commit the specific transaction.
COMMIT TRANSACTION transactionName

In this example, let us commit the current transaction using the following command.
COMMIT

The above command produces the following output.
Committed successfully

In this example, we will commit the transaction named tx_test using the following command.
COMMIT TRANSACTION tx_test;

The above command produces the following output.
Committed successfully 


    14 Lectures 
     1 hours 

 Mahesh Kumar

    100 Lectures 
     9.5 hours 

 Hari Om Singh

    108 Lectures 
     8 hours 

 Pavan Lalwani

    10 Lectures 
     1 hours 

 Deepti Trivedi

    20 Lectures 
     2 hours 

 Deepti Trivedi

    14 Lectures 
     1 hours 

 Deepti Trivedi
 Print
 Add Notes
 Bookmark this page
Check if a number is perfect square without finding square root in C++

Suppose a number is given, we have to check whether the number is a perfect square or not. We will not use the square root operation to check it. Suppose a number 1024 is there, this is a perfect square, but 1000 is not a perfect square. The logic is simple, we have to follow this algorithm to get the result.
isPerfectSquare(n) −
input − The number n
output − true, if the number is a perfect square, otherwise, false
begin
   for i := 1, i2 ≤ n, increase i by 1:
      if n is divisible by i, and n / i = i, then
         return true
   done
   return false
end
 Live Demo
#include <iostream>
using namespace std;
bool isPerfectSquare(int number) {
   for (int i = 1; i * i <= number; i++) {
      if ((number % i == 0) && (number / i == i)) {
         return true;
      }
   }
   return false;
}
int main() {
   int n = 1024;
   if(isPerfectSquare(n)){
      cout << n << " is perfect square number";
   } else {
      cout << n << " is not a perfect square number";
   }
}
1024 is perfect square number
\qquad - Tex Command

\qquad - Used to create 2em space.
{ \qquad}
\qquad command creates 2em space.

|\qquad\hphantom{|}|

|||



|\qquad\hphantom{|}|

|||


|\qquad\hphantom{|}|

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Solidity - Interfaces

Interfaces are similar to abstract contracts and are created using interface keyword. Following are the key characteristics of an interface.
Interface can not have any function with implementation.
Interface can not have any function with implementation.
Functions of an interface can be only of type external.
Functions of an interface can be only of type external.
Interface can not have constructor.
Interface can not have constructor.
Interface can not have state variables.
Interface can not have state variables.
Interface can have enum, structs which can be accessed using interface name dot notation.
Interface can have enum, structs which can be accessed using interface name dot notation.
Try the following code to understand how the interface works in Solidity.
pragma solidity ^0.5.0;

interface Calculator {
   function getResult() external view returns(uint);
}
contract Test is Calculator {
   constructor() public {}
   function getResult() external view returns(uint){
      uint a = 1; 
      uint b = 2;
      uint result = a + b;
      return result;
   }
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 3


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Python - HTTP Authentication

Authentication is the process of determining if the request has come from a valid user who has the required privileges to use the system. In the world of computer networking this is a very vital requirement as many systems keep interacting with each other and proper mechanism needs to ensure that only valid interactions happen between these programs.
The python module names requests has in-built feature to call various APIs provided by the serving web apps along with the user credentials. These credentials have to be embedded in the calling program. If the APIs verify it successfully then a valid login happens.
We install the required python module named requests for running the authentication program.
pip install requests
Below we see a simple authentication mechanism involving only the username and the password. A successful response indicates valid login.
import requests 
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print r
When we run the above program, we get the following output −


We can also run a program to use twitter's api and make a successful login by using the following code. We use the OAuth1 method available in the requests module to process the parameters required by Twitter API. As we can see the requests module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism.
import requests
from requests_oauthlib import OAuth1

url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
              'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

requests.get(url, auth=auth)
When we run the above program, we get the following output −
{
  "errors": [
    {
      "code": 215,
      "message": "Bad Authentication data."
    }
  ]
}


But using the proper values for OAuth1 parameters you get a successful response.

    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
String split(String regex, int limit) Method

This method has two variants and splits this string around matches of the given regular expression.
Here is the syntax of this method −
public String[] split(String regex, int limit)

Here is the detail of parameters −
regex − the delimiting regular expression.
regex − the delimiting regular expression.
limit − the result threshold, which means how many strings to be returned.
limit − the result threshold, which means how many strings to be returned.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome-to-Tutorialspoint.com");
      System.out.println("Return Value :" );
      
      for (String retval: Str.split("-", 2)) {
         System.out.println(retval);
      }
      System.out.println("");
      System.out.println("Return Value :" );
      
      for (String retval: Str.split("-", 3)) {
         System.out.println(retval);
      }
      System.out.println("");
      System.out.println("Return Value :" );
      
      for (String retval: Str.split("-", 0)) {
         System.out.println(retval);
      }
      System.out.println("");
   }
}
This will produce the following result −
Return Value :
Welcome
to-Tutorialspoint.com

Return Value :
Welcome
to
Tutorialspoint.com

Return Value:
Welcome
to
Tutorialspoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Convert JSON to another JSON format with recursion JavaScript

Suppose, we have the following JSON object −
const obj = {
   "context": {
      "device": {
         "localeCountryCode": "AX",
         "datetime": "3047-09-29T07:09:52.498Z"
      },
      "currentLocation": {
         "country": "KM",
         "lon": -78789486,
      }
   }
};
We are required to write a JavaScript recursive function that initially takes in one such array.The function should split the above object into a "label" - "children" format.
Therefore, the output for the above object should look like −
const output = {
   "label": "context",
   "children": [
      {
         "label": "device",
         "children": [
         {
            "label": "localeCountryCode"
         },
         {
            "label": "datetime"
         }
      ]
   },
   {
      "label": "currentLocation",
      "children": [
            {
               "label": "country"
            },
            {
               "label": "lon"
            }
         ]
      }
   ]
}
The code for this will be −
const obj = {
   "context": {
      "device": {
         "localeCountryCode": "AX",
         "datetime": "3047-09-29T07:09:52.498Z"
      },
      "currentLocation": {
         "country": "KM",
         "lon": -78789486,
      }
   }
};
const transformObject = (obj = {}) => {
   if (obj && typeof obj === 'object') {
      return Object.keys(obj).map((el) => {
         let children = transformObject(obj[el]); return children ? {
             label: el, children: children } : {
            label: el
         };
      });
   };
};
console.log(JSON.stringify(transformObject(obj), undefined, 4));
And the output in the console will be −
[
   {
      "label": "context",
      "children": [
         {
            "label": "device",
            "children": [
               {
                  "label": "localeCountryCode"
               },
               {
               "label": "datetime"
               }
            ]
         },
         {
            "label": "currentLocation",
            "children": [
                  {
                     "label": "country"
                  },
                  {
                     "label": "lon"
                  }
               ]
            }
      ]
   }
]
What is the difference between getWindowHandle() and getWindowHandles() methods in Selenium WebDriver?

There are difference between getWindowHandle() and getWindowHandles() methods in Selenium webdriver. The getWindowHandles
and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.
The getWindowHandle method is used to store the window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code.
By default, the driver object can only access the elements of the parent window. To switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child
window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
public class CloseSpecificWindow {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //window handle of parent window
      String m = driver.getWindowHandle();
      driver.findElement(By.id("login-google-button")).click();

      // store window handles in Set
      Set<String> w = driver.getWindowHandles();

      // iterate window handles
      for (String h: w)
      {
         // switching to each window
         driver.switchTo().window(h);
         String s= driver.getTitle();

         // checking specific window title
         if(s.equalsIgnoreCase("Sign in - Google Accounts"))
         {
            System.out.println("Window title to be closed: "+ driver.getTitle());
            driver.close();
         }
      }

      // switching parent window
      driver.switchTo().window(m);
      driver.quit();
   }
}
Solidity - Special Variables

Special variables are globally available variables and provides information about the blockchain. Following is the list of special variables −
blockhash(uint blockNumber) returns (bytes32)
Hash of the given block - only works for 256 most recent, excluding current, blocks.
block.coinbase (address payable)
Current block miner's address.
block.difficulty (uint)
current block difficulty.
block.gaslimit (uint)
Current block gaslimit.
block.number (uint)
Current block number.
block.timestamp
Current block timestamp as seconds since unix epoch.
gasleft() returns (uint256)
Remaining gas.
msg.data (bytes calldata)
Complete calldata.
msg.sender (address payable)
Sender of the message (current call).
msg.sig (bytes4)
First four bytes of the calldata (i.e. function identifier)
msg.value (uint)
Number of wei sent with the message.
now (uint)
Current block timestamp (alias for block.timestamp).
tx.gasprice (uint)
Gas price of the transaction.
tx.origin (address payable)
Sender of the transaction (full call chain).
Try the following code to see the use of msg, a special variable to get the sender address in Solidity.
pragma solidity ^0.5.0;

contract LedgerBalance {
   mapping(address => uint) public balances;

   function updateBalance(uint newBalance) public {
      balances[msg.sender] = newBalance;
   }
}
contract Updater {
   function updateBalance() public returns (uint) {
      LedgerBalance ledgerBalance = new LedgerBalance();
      ledgerBalance.updateBalance(10);
      return ledgerBalance.balances(address(this));
   }
}
Run the above program using steps provided in Solidity First Application chapter.
First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as − 
{
   "0": "uint256: 10"
}


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page