code-rag-bench/online-tutorials huggingface dataset:
How to declare Global Variables in JavaScript ?

21 May, 2021
Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. 
Global Variables are the variables that can be accessed from anywhere in the program. These are the variables that are declared in the main body of the source code and outside all the functions. These variables are available to every function to access. 
Global variables are declared at the start of the block(top of the program)
Var keyword is used to declare variables globally.
Global variables can be accessed from any part of the program.
Note: If you assign a value to a variable and forgot to declare that variable, it will automatically be considered as a global variable.
Example 1: In this example, we declare the variable at the start of the program outside every function using the var keyword. 
HTML
<!DOCTYPE html> <html>   <body>    <center>        <p id="geeks"></p>          <p id="Geeks"></p>                    <script>            var Marks = 10;               // Declaring global variable outside the function            myFunction();                // Global variable accessed from                 // Within a function              function myFunction() {                document.getElementById("geeks").innerHTML =                    "Marks = "+Marks;            }            // Changing value of global            // Variable from outside of function              document.getElementById("Geeks").innerHTML =               "Marks = "+Marks*20;        </script>    </center></body>  </html>
Output:
Example 2: Declare the Global variable within a function using a window object. Variable declared using window objects are global variables and can be accessed from any portion of the program.
HTML
<html><body>  <p id="geeks"></p>        <script>    function a(){        // Declaring global variable using window object        window.marks=10;    }      function b(){        // Accessing global variable from other function       document.getElementById("geeks").innerHTML ="Marks = "+window.marks     }      a();    b();  </script></body>    </html>
Output:
javascript-basics
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Duration toHoursPart() method in Java with Examples

26 Nov, 2018
The toHoursPart() method of Duration Class in java.time package is used get the value of this duration in number of hours by dividing the number of hours in a day.
Syntax:
public long toHoursPart()

Parameters: This method do not accepts any parameter.
Return Value: This method returns a long value which is the number of hours in this duration by dividing the number of hours in a day.
Below examples illustrate the Duration.toHoursPart() method:
Example 1:
// Java code to illustrate toHoursPart() method  import java.time.Duration;  public class GFG {    public static void main(String[] args)    {          // Duration using parse() method        Duration duration            = Duration.parse("P2DT3H4M");          System.out.println("Duration: "                           + duration);          // Get the number of hours        // using toHoursPart() method        System.out.println(duration.toHoursPart());    }}
Duration: PT51H4M
3

Example 2:
// Java code to illustrate toHoursPart() method  import java.time.Duration;  public class GFG {    public static void main(String[] args)    {          // Duration using ofHours() method        Duration duration            = Duration.ofHours(10);          System.out.println("Duration: "                           + duration);          // Get the number of hours        // using toHoursPart() method        System.out.println(duration.toHoursPart());    }}
Duration: PT10H
10

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#toHoursPart–
Java-Duration
Java-Functions
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split a column in Pandas dataframe and get part of it

21 Jan, 2019
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement.
We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is str.split, it can be used with split to get the desired part of the string. To get the nth part of the string, first split the column by delimiter and apply str[n-1] again on the object returned, i.e. Dataframe.columnName.str.split(" ").str[n-1].
Let’s make it clear by examples.
Code #1: Print a data object of the splitted column.
import pandas as pdimport numpy as npdf = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',                                          'Geek4_id', 'Geek5_id'],                'Geek_A': [1, 1, 3, 2, 4],                'Geek_B': [1, 2, 3, 4, 6],                'Geek_R': np.random.randn(5)})  # Geek_A  Geek_B   Geek_ID    Geek_R# 0       1       1  Geek1_id    random number# 1       1       2  Geek2_id    random number# 2       3       3  Geek3_id    random number# 3       2       4  Geek4_id    random number# 4       4       6  Geek5_id    random number  print(df.Geek_ID.str.split('_').str[0])
0    Geek1
1    Geek2
2    Geek3
3    Geek4
4    Geek5
dtype: object

 Code #2: Print a list of returned data object.
import pandas as pdimport numpy as npdf = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',                                         'Geek4_id', 'Geek5_id'],                'Geek_A': [1, 1, 3, 2, 4],                'Geek_B': [1, 2, 3, 4, 6],                'Geek_R': np.random.randn(5)})  # Geek_A  Geek_B   Geek_ID    Geek_R# 0       1       1  Geek1_id    random number# 1       1       2  Geek2_id    random number# 2       3       3  Geek3_id    random number# 3       2       4  Geek4_id    random number# 4       4       6  Geek5_id    random number  print(df.Geek_ID.str.split('_').str[0].tolist())
['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5']

 Code #3: Print a list of elements.
import pandas as pdimport numpy as np  df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',                                         'Geek4_id', 'Geek5_id'],                'Geek_A': [1, 1, 3, 2, 4],                'Geek_B': [1, 2, 3, 4, 6],                'Geek_R': np.random.randn(5)})  # Geek_A  Geek_B   Geek_ID    Geek_R# 0       1       1  Geek1_id    random number# 1       1       2  Geek2_id    random number# 2       3       3  Geek3_id    random number# 3       2       4  Geek4_id    random number# 4       4       6  Geek5_id    random number  print(df.Geek_ID.str.split('_').str[1].tolist())
['id', 'id', 'id', 'id', 'id']

pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Timestamp.quarter

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.quarter attribute return an integer value which represents the quarter in which the date of the given Timestamp object lies.
Syntax : Timestamp.quarter
Parameters : None
Return : quarter
Example #1: Use Timestamp.quarter attribute to find in which quarter the date of the given Timestamp object lies.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(2016, 1, 1, 12, 25, 16, 28, 32)  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.quarter attribute to print the quarter in which the date in the ts object falls.
# find the value of quarterts.quarter
Output :
As we can see in the output, the Timestamp.quarter attribute has returned 1 indicating that the date in the ts object falls in the first quarter of the year. Example #2: Use Timestamp.quarter attribute to find in which quarter the date of the given Timestamp object lies.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009,  month = 5, day = 31, hour = 4,                       nanosecond = 15, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.quarter attribute to print the quarter in which the date in the ts object falls.
# find the value of quarterts.quarter
Output :
As we can see in the output, the Timestamp.quarter attribute has returned 2 indicating that the date in the ts object falls in the second quarter of the year.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Determine the Month on a Specific Date in R Programming – months() Function

24 Jun, 2020
months() function in R Language is used to determine the month on a specific date passed to it as argument.
Syntax: months(date, abbreviate)
Parameters:date: Date to be checkedabbreviate: Boolean value to abbreviate month
Example 1:
# R program to find the month # on a specific date  # Specifying the datedate <- as.POSIXlt("2020-06-23")date  # Calling months() functionmonths(date)
Output:
[1] "2020-06-23 UTC"
[1] "June"

Example 2:
# R program to find the month # on a specific date  # Specifying the datedate <- as.POSIXlt("1994-01-17")date  # Calling months() functionmonths(date, abbreviate = TRUE)
Output:
[1] "1994-01-17 UTC"
[1] "Jan"

R Date-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Check if a given array can represent Preorder Traversal of Binary Search Tree in C++

Suppose we have a list of elements in an array, we have to check, whether the elements can be the preorder traversal of a binary search tree or not. Suppose a sequence is like {40, 30, 35, 80, 100}, then the tree will be like −
We can solve this using a stack. We have to follow these steps to solve this problem.
Define empty stack
set root as negative infinity
for every element in preorder sequence, do the following −if the element is smaller than current root, return falseKeep removing elements from stack while the element is greater than stack top, and make the lastly removed element as root.push the element into stack
if the element is smaller than current root, return false
Keep removing elements from stack while the element is greater than stack top, and make the lastly removed element as root.
push the element into stack
#include <iostream>
#include <stack>
using namespace std;
bool isValidPreorder(int pre[], int n) {
   stack<int> stk;
   int root = INT_MIN;
   for (int i=0; i<n; i++) {
      if (pre[i] < root)
         return false;
      while (!stk.empty() && stk.top()<pre[i]) {
         root = stk.top();
         stk.pop();
      }
      stk.push(pre[i]);
   }
   return true;
}
int main() {
   int pre[] = {40, 30, 35, 80, 100};
   int n = sizeof(pre)/sizeof(pre[0]);
   if(isValidPreorder(pre, n))
      cout << "This can form BST";
   else
      cout << "This can not form BST";
}
This can form BST
Add a border around histogram bars in Matplotlib - GeeksforGeeks

24 Jan, 2021
Prerequisites: Matplotlib
In this article, we will see how can we can add a border around histogram bars in our graph using matplotlib, Here we will take two different examples to showcase our graph.
Approach:
Import required module.
Create data.
Add border around histogram bars.
Normally plot the data.
Display plot.
Below is the Implementation:
Example 1:
In this example, we will Pass an edgecolor = ‘Black’ value as the edge color parameter to plt.hist() to change the bar border color.
Python3
# importing packagefrom matplotlib import pyplot as pltimport numpy as np  #create datafig,ax = plt.subplots(1,1)a = np.array([22, 87, 5, 43, 56, 73, 55,              54, 11, 20, 51, 5, 79, 31, 27])  b = (0, 25, 50, 75, 100)  # Adjust the border colorax.hist(a, b, edgecolor = "black")  ax.set_title("histogram - Geekforgeeks")ax.set_xlabel('Litracy Level(%)')ax.set_ylabel('Population(million)')  plt.show()
Output:
Example 2:
In this example, we will Pass a two edge color, edgecolor = ‘Black’ and ‘red’ value as the edge color parameter to plt.hist() to change the bar border color.
Python3
# importing packagefrom matplotlib import pyplot as pltimport numpy as np  #create datafig,ax = plt.subplots(1, 1)  a = np.array([20, 73, 55, 31, 51, 5, 79, 5,              43, 22, 87, 54, 11, 56, 27])  b = np.array([0, 25, 50, 75, 100])  # Adjust the border colorax.hist(a, edgecolor = "black", color = 'pink')ax.hist(b, edgecolor = "red", color = 'gray')  ax.set_title("Histogram - Geekforgeeks")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Lodash _.set() Method - GeeksforGeeks

16 Sep, 2020
The _.set() method is used to set the value at path of object and returns a new set object.
Syntax:
_.set(object, path, value)

Parameters: This method accepts three parameters as mentioned above and described below:
object: This parameter holds the object to modify.
path: This parameter holds the path of the property to set. It will be array or string.
value: This parameter holds the value to set.
Return Value: This method returns the new set object.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.  
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 2012 } }] };  // set the value by _.set() method _.set(obj, 'cpp[0].java.python', 2020);  // return the new set objectconsole.log(obj.cpp[0].java.python);
Output:
2020

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 2012 } }] };  // set the value by _.set() method _.set(obj, ['html', '0', 'css', 'javascript'], 2024);  // return the new set objectconsole.log(obj.html[0].css.javascript);
Output:
2024

Note: This will not work in normal JavaScript because it requires the library lodash to be installed. 
Reference: https://lodash.com/docs/4.17.15#set
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Check if it possible to partition in k subarrays with equal sum in Python

Suppose we have an array of numbers called nums, and also have another value K. We have to check whether we can partition the array nums into K contiguous subarrays such that the elements sum of each subarrays is equal.
So, if the input is like nums = [2, 5, 3, 4, 7] k = 3, then the output will be True as we can make three partitions like [(2, 5), (3, 4), (7)] all have equal sum 7.
To solve this, we will follow these steps −
n := size of nums
cumul_sum := cumulative sum of all elements in nums
total_sum := cumul_sum[n - 1]
if total_sum not divisible by k, thenreturn False
return False
count := 0, pos := -1
for i in range 0 to n - 1, doif pos is same as -1, thensub := 0otherwise,sub := cumul_sum[pos]if cumul_sum[i] - sub is same as (total_sum / K), thenpos := icount := count + 1otherwise when cumul_sum[i] - cumul_sum[pos] > (total_sum / K), thencome out from loop
if pos is same as -1, thensub := 0
sub := 0
otherwise,sub := cumul_sum[pos]
sub := cumul_sum[pos]
if cumul_sum[i] - sub is same as (total_sum / K), thenpos := icount := count + 1
pos := i
count := count + 1
otherwise when cumul_sum[i] - cumul_sum[pos] > (total_sum / K), thencome out from loop
come out from loop
return true when count is same as K otherwise false
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums, k):
   n = len(nums)
   cumul_sum = [0 for i in range(n)]
   cumul_sum[0] = nums[0]
   for i in range(1, n):
      cumul_sum[i] = cumul_sum[i - 1] + nums[i]
   total_sum = cumul_sum[n - 1]
   if total_sum % k != 0:
      return False
   count = 0
   pos = -1
   for i in range(n):
      if pos == -1:
         sub = 0
      else:
         sub = cumul_sum[pos]
      if cumul_sum[i] - sub == total_sum / k:
         pos = i
         count += 1
      elif cumul_sum[i] - cumul_sum[pos] > total_sum / k:
         break
   return count == k
nums = [2, 5, 3, 4, 7]
k = 3
print(solve(nums, k))
[2, 5, 3, 4, 7], 3
True
Python Code Objects

Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn’t yet been bound into a function. Though code objects represent some piece of executable code, they are not, by themselves, directly callable. To execute a code object, you must use the exec keyword.
In the below example we see how the code objects are created for a given piece of code and what are the various attributes associated with hat code object.
 Live Demo
code_str = """
print("Hello Code Objects")
"""
# Create the code object
code_obj = compile(code_str, '<string>', 'exec')
# get the code object
print(code_obj)
#Attributes of code object
print(dir(code_obj))
# The filename
print(code_obj.co_filename)
# The first chunk of raw bytecode
print(code_obj.co_code)
#The variable Names
print(code_obj.co_varnames)
Running the above code gives us the following result −
<code object <module> at 0x000001D80557EF50, file "<string>", line 2>
['__class__', '__delattr__', '__dir__', '__doc__', ......., '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', .....,posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
<string>
b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00'
()
Java - Interthread Communication

If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −
public void wait()
Causes the current thread to wait until another thread invokes the notify().
public void notify()
Wakes up a single thread that is waiting on this object's monitor.
public void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
class Chat {
   boolean flag = false;

   public synchronized void Question(String msg) {
      if (flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println(msg);
      flag = true;
      notify();
   }

   public synchronized void Answer(String msg) {
      if (!flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }

      System.out.println(msg);
      flag = false;
      notify();
   }
}

class T1 implements Runnable {
   Chat m;
   String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

   public T1(Chat m1) {
      this.m = m1;
      new Thread(this, "Question").start();
   }

   public void run() {
      for (int i = 0; i < s1.length; i++) {
         m.Question(s1[i]);
      }
   }
}

class T2 implements Runnable {
   Chat m;
   String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

   public T2(Chat m2) {
      this.m = m2;
      new Thread(this, "Answer").start();
   }

   public void run() {
      for (int i = 0; i < s2.length; i++) {
         m.Answer(s2[i]);
      }
   }
}
public class TestThread {
   public static void main(String[] args) {
      Chat m = new Chat();
      new T1(m);
      new T2(m);
   }
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!

Above example has been taken and then modified from [https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]

    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
Function borrowing in JavaScript.

The call(), apply() and bind() are used to borrow methods in JavaScript.
Following is the code for borrowing methods in 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;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Borrowing a method in JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to borrow the welcome method of object obj</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   let obj = {
      firstName: "Rohan",
      lastName: "Sharma",
      welcome() {
         return "Welcome " + this.firstName + " " + this.lastName;
      },
   };
   let obj1 = {
      firstName: "John",
      lastName: "Shaw",
   };
   sampleEle.innerHTML = "obj.welcome() = " + obj.welcome();
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML = "obj1.welcome() = " + obj.welcome.call(obj1);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
How to Fix: module ‘pandas’ has no attribute ‘dataframe’ - GeeksforGeeks

19 Dec, 2021

In this article, we are going to see how to fix errors while creating dataframe ” module ‘pandas’ has no attribute ‘dataframe’”.
To create dataframe we need to use DataFrame(). If we use dataframe it will throw an error because there is no dataframe attribute in pandas. The method is DataFrame(). We need to pass any dictionary as an argument. Since the dictionary has a key, value pairs we can pass it as an argument. Dataframe considers keys as attributes and pairs as tuples. Let us see why we get errors while creating a dataframe.
Python3
 

 
 










import pandas as pd 
  
data = {"id": [1, 2, 3], 
        "name": ["karthik", "nikhil", "bhagi"]} 
  
df = pd.dataframe(data) 
print(df) 






Output:
To fix the above error we need to use DataFrame instead of dataframe.
Python3
 

 
 










import pandas as pd 
  
data = {"id": [1, 2, 3], 
        "name": ["karthik", "nikhil", "bhagi"]} 
  
df = pd.DataFrame(data) 
df 






Output:
id        name
0    1        karthik
1    2        nikhil
2    3        bhagi
In this way, we can fix the module ‘pandas’ has no attribute ‘dataframe’  error .

Picked


Python How-to-fix


Python-pandas


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
PLSQL | EXTRACT Function - GeeksforGeeks

28 Oct, 2019
The PLSQL EXTRACT function is used for extracting a specific value such as year, month, day or hour from a date or an interval value.
Syntax:
EXTRACT(field FROM source)
Parameters Used:The EXTRACT function accepts two parameters :
field – It is used to specify the component that needs to be extracted.
source – It is used to specify a DATE, an INTERVAL, or a TIMESTAMP value from which a field is extracted.
The fields that can be extracted from various value types are:
DATE: YEAR, MONTH and DAY.
INTERVAL YEAR TO MONTH: YEAR and MONTH
INTERVAL DAY TO SECOND: DAY, HOUR, MINUTE and SECOND.
TIMESTAMP: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Extracting the value of the YEAR field from a DATE value.
SELECT
  EXTRACT(YEAR FROM DATE '2019-10-26')
FROM
  DUAL; 
Output:
2019 
Example-2: Extracting the value of the month field from a DATE value.
SELECT
  EXTRACT(YEAR FROM DATE '2019-10-26')
FROM
  DUAL; 
Output:
10 
Example-3: Extracting the value of the day field from a DATE value.
SELECT
  EXTRACT(YEAR FROM DATE '2019-10-26')
FROM
  DUAL; 
Output:
26 
Example-4: Extracting the value of the year field from an INTERVAL YEAR TO MONTH.
SELECT
  EXTRACT( YEAR FROM INTERVAL '7-3' YEAR TO MONTH )
FROM
  DUAL; 
Output:
7 
In the above example, the mentioned argument ‘7-3’ means 7 years and 3 months.
Example-5: Extracting the value of the day field from an INTERVAL DAY TO SECOND.
SELECT
  EXTRACT( DAY FROM INTERVAL '26 10:32:29.53' DAY TO SECOND )
FROM
  dual; 
Output:
26 
In the above example, the mentioned argument ’26 10:32:29.53′ means 26 days, 10hours, 32 minutes and 29 seconds.
Example-6: Extracting the value of the year field from a timestamp.
SELECT
  EXTRACT( YEAR FROM TIMESTAMP '2019-10-26 12:57:34.10' )
FROM
  dual; 
Output:
2019 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Python | Reversed Split Strings - GeeksforGeeks

01 May, 2019
The functionality of splitting is quite popular with manyfold applications and usages. With all, comes the scopes of many types of variations. This article discusses one among those variations in which one desires to get the split and reversal of element string order, both the operations at once. Let’s discuss certain ways to solve this particular problem.
Method #1 : Using join() + reversed() + split()
In this particular method, we first get the element words using the split function, perform the reversal of order of them using the reversed function and then perform the join to bind together the elements.
# Python3 code to demonstrate# Reverse string split# using join() + reversed() + split()  # initializing stringtest_string = "Gfg is best"  # printing original string print("The original string : " + str(test_string))  # using join() + reversed() + split()# Reverse string splitres =  ", ".join(reversed(test_string.split(" ")))  # print resultprint("The string after reverse split : " + str(res))
The original string : Gfg is best
The string after reverse split : best, is, Gfg

 
Method #2 : Using join() + split() + list slicing
This method is similar to the above method in which we perform split and join, but the only difference in this method is that we use list slicing to perform the reversal.
# Python3 code to demonstrate# Reverse string split# using join() + split() + list slicing  # initializing stringtest_string = "Gfg is best"  # printing original string print("The original string : " + str(test_string))  # using join() + split() + list slicing# Reverse string splitres =  ', '.join(test_string.split()[::-1])  # print resultprint("The string after reverse split : " + str(res))
The original string : Gfg is best
The string after reverse split : best, is, Gfg

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.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
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
Python | Pandas.pivot() - GeeksforGeeks

28 Sep, 2018
pandas.pivot(index, columns, values) function produces pivot table based on 3 columns of the DataFrame. Uses unique values from index / columns and fills with values.
Parameters:index[ndarray] : Labels to use to make new frame’s indexcolumns[ndarray] : Labels to use to make new frame’s columnsvalues[ndarray] : Values to use for populating new frame’s values
Returns: Reshaped DataFrameException: ValueError raised if there are any duplicates.
Code:
# Create a simple dataframe  # importing pandas as pdimport pandas as pd  # creating a dataframedf = pd.DataFrame({'A': ['John', 'Boby', 'Mina'],      'B': ['Masters', 'Graduate', 'Graduate'],      'C': [27, 23, 21]})  df
 
# values can be an object or a listdf.pivot('A', 'B', 'C')
 
# value is a listdf.pivot(index ='A', columns ='B', values =['C', 'A'])
 Raise ValueError when there are any index, columns combinations with multiple values.
# importing pandas as pdimport pandas as pd  # creating a dataframedf = pd.DataFrame({'A': ['John', 'John', 'Mina'],      'B': ['Masters', 'Masters', 'Graduate'],      'C': [27, 23, 21]})    df.pivot('A', 'B', 'C')
ValueError: Index contains duplicate entries, cannot reshape
Python pandas-dataFrame
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
YearMonth of(int, Month) method in Java with Examples - GeeksforGeeks

12 May, 2020
The of(int year, Month month) method of the YearMonth class in Java is used to get an instance of YearMonth from a year and month.Syntax:
public static YearMonth of(
    int year, Month month)
Parameters: This method accepts two parameters:
year: It represents year.
month: It represents the month of year.
Return value: This method returns the year-month.
Exceptions: This method throws DateTimeException if the value of any field is invalid.
Below programs illustrate the of(int year, Month month) method of YearMonth in Java:
Program 1:
// Java program to demonstrate// YearMonth.of(int year, Month month) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // apply of(int year, Month month) method        // of YearMonth class        YearMonth yearmonth            = YearMonth.of(2020, Month.MAY);          // print year and month        System.out.println("YearMonth: "                           + yearmonth);    }}
YearMonth: 2020-05

Program 2:
// Java program to demonstrate// YearMonth.of(int year, Month month) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // apply of(int year, Month month) method        // of YearMonth class        YearMonth yearmonth            = YearMonth.of(2020, Month.MAY);          // print only year        System.out.println("Year: "                           + yearmonth.getYear());    }}
Year: 2020

Program 3:
// Java program to demonstrate// YearMonth.of(int year, Month month) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // apply of(int year, Month month) method        // of YearMonth class        YearMonth yearmonth            = YearMonth.of(2020, Month.MAY);          // print only month        System.out.println("Month: "                           + yearmonth.getMonth());    }}
Month: MAY

References: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#of(int, java.time.Month)
Java-Functions
Java-YearMonth
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions 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
Internal Working of HashMap in Java
Strings in Java
Solidity - Comments

Solidity supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by Solidity Compiler.
Any text between a // and the end of a line is treated as a comment and is ignored by Solidity Compiler.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
The following example shows how to use comments in Solidity.
function getResult() public view returns(uint){
   // This is a comment. It is similar to comments in C++

   /*
      * This is a multi-line comment in solidity
      * It is very similar to comments in C Programming
   */
   uint a = 1;
   uint b = 2;
   uint result = a + b;
   return result;
}

    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
semget() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
 
#include <sys/types.h>
 
#include <sys/ipc.h>
 
#include <sys/sem.h>


int semget(key_t key, int nsems, int semflg); 

If
semflg specifies both
IPC_CREAT and
IPC_EXCL and a semaphore set already exists for
key, then
semget() fails with
errno set to
EEXIST. (This is analogous to the effect of the combination
O_CREAT | O_EXCL for
open(2).)


Upon creation, the least significant 9 bits of the argument
semflg define the permissions (for owner, group and others)
for the semaphore set.
These bits have the same format, and the same
meaning, as the
mode argument of
open(2)
(though the execute permissions are
not meaningful for semaphores, and write permissions mean permission
to alter semaphore values).


The values of the semaphores in a newly created set are indeterminate.
(POSIX.1-2001 is explicit on this point.) 
Although Linux, like many other implementations,
initialises the semaphore values to 0,
a portable application cannot rely on this:
it should explicitly initialise the semaphores to the desired values.


When creating a new semaphore set,
semget() initialises the set’s associated data structure,
semid_ds (see
semctl(2)),
as follows:


If the semaphore set already exists, the permissions are
verified.


The following limits on semaphore set resources affect the
semget() call:


The semaphores in a set are not initialised by
semget(). In order to initialise the semaphores,
semctl(2)
must be used to perform a
SETVAL or a
SETALL operation on the semaphore set.
(Where multiple peers do not know who will be the first to
initialise the set, checking for a non-zero
sem_otime in the associated data structure retrieved by a
semctl() IPC_STAT operation can be used to avoid races.)

semctl (2)
semctl (2)
semop (2)
semop (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
JavaScript String - charCodeAt() Method

This method returns a number indicating the Unicode value of the character at the given index.
Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match of the ASCII character encoding. charCodeAt() always returns a value that is less than 65,536.
Use the following syntax to find the character code at a particular index.
string.charCodeAt(index);

index − An integer between 0 and 1 less than the length of the string; if unspecified, defaults to 0.
Returns a number indicating the Unicode value of the character at the given index. It returns NaN if the given index is not between 0 and 1 less than the length of the string.
Try the following example.
<html>
   <head>
      <title>JavaScript String charCodeAt() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String( "This is string" );
         document.write("str.charCodeAt(0) is:" + str.charCodeAt(0)); 
         document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1)); 
         document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2)); 
         document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3)); 
         document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4)); 
         document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5)); 
      </script>      
   </body>
</html>
str.charCodeAt(0) is:84
str.charCodeAt(1) is:104
str.charCodeAt(2) is:105
str.charCodeAt(3) is:115
str.charCodeAt(4) is:32
str.charCodeAt(5) is:105 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
ReactJS – useContext hook

In this article, we are going to see how to access the data without passing it through every parent component in the React Lifecycle.
This hook is the better replacement of the Context API of the Class-based component which is used to set the global data and this data can now be accessed in any of the children components without the need to pass it through every parent Component.
const authContext = useContext(initialValue);
The useContext accepts the value provided by React.createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memoization.
In this example, we are going to build an authentication React application that logs in or logs out users in the children component and updates the state accordingly.
We will build an App Component which has two LogIn and LogOut Components which access the state provided by the Context Provider and updates it accordingly.
AuthContext.js
import React from 'react';

const authContext = React.createContext({
   auth: null,
   login: () => {},
   logout: () => {},
});
export default authContext;
App.jsx
import React, { useState } from 'react';
import LogIn from './Login';
import LogOut from './Logout';
import AuthContext from './AuthContext';

const App = () => {
   const [auth, setAuth] = useState(false);
   const login = () => {
      setAuth(true);
   };
   const logout = () => {
      setAuth(false);
   };
   return (
      <React.Fragment>
      <AuthContext.Provider
            value={{ auth: auth, login: login, logout: logout }}
      >
      <p>{auth ? 'Hi! You are Logged In' : 'Oope! Kindly Login'}</p>
      <LogIn />
      <LogOut />
      </AuthContext.Provider>
      </React.Fragment>
   );
};
export default App;
Login.js
import React, { useContext } from 'react';
import AuthContext from './AuthContext';

const Login = () => {
   const auth = useContext(AuthContext);
   return (
      <>
         <button onClick={auth.login}>Login</button>
      </>
   );
};
export default Login;
Logout.js
import React, { useContext } from 'react';
import AuthContext from './AuthContext';

const Logout = () => {
   const auth = useContext(AuthContext);
   return (
      <>
         <button onClick={auth.logout}>Click To Logout</button>
      </>
   );
};
export default Logout;
This will produce the following result.
Git - Commit Changes

Jerry has already committed the changes and he wants to correct his last commit. In this case, git amend operation will help. The amend operation changes the last commit including your commit message; it creates a new commit ID.
Before amend operation, he checks the commit log.
[jerry@CentOS project]$ git log

The above command will produce the following result.
commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530

Implemented my_strlen function


commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530

Initial commit

Jerry commits the new changes with -- amend operation and views the commit log.
[jerry@CentOS project]$ git status -s
M string.c
?? string

[jerry@CentOS project]$ git add string.c

[jerry@CentOS project]$ git status -s
M string.c
?? string

[jerry@CentOS project]$ git commit --amend -m 'Changed return type of my_strlen to size_t'
[master d1e19d3] Changed return type of my_strlen to size_t
1 files changed, 24 insertions(+), 0 deletions(-)
create mode 100644 string.c

Now, git log will show new commit message with new commit ID −
[jerry@CentOS project]$ git log

The above command will produce the following result.
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530

Changed return type of my_strlen to size_t


commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530

Initial commit


    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    23 Lectures 
     2 hours 

 Asif Hussain

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    125 Lectures 
     9 hours 

 John Shea

    13 Lectures 
     2.5 hours 

 Raghu Pandey

    13 Lectures 
     3 hours 

 Sebastian Sulinski
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Style guide
Tryit: JavaScript is case sensitive
JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on 
numbers.
Unlike other objects, the Math object has no constructor.
The Math object is static.
All methods and properties can be used without creating a Math object first.
The syntax for any Math property is : Math.property.
JavaScript provides 8 mathematical constants that can be accessed as Math properties:
The syntax for Math any methods is : Math.method(number)
There are 4 common methods to round a number to an integer:
Math.round(x) returns the nearest integer:
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Math.floor(x) returns the value of x rounded down to its nearest integer:
Math.trunc(x) returns the integer part of x:
Math.sign(x) returns if x is negative, null or positive:
Math.trunc() and Math.sign() were added to JavaScript 2015 - ES6.
Math.pow(x, y) returns the value of x to the power of y:
Math.sqrt(x) returns the square root of x:
Math.abs(x) returns the absolute (positive) value of x:
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
Math.random() returns a random number between 0 (inclusive), and 1 
(exclusive):
You will learn more about Math.random() in the next chapter of this tutorial.
Math.log(x) returns the natural logarithm of x.
The natural logarithm returns the time needed to reach a certain level of growth:
Math.E and Math.log() are twins.
How many times must we multiply Math.E to get 10?
Math.log2(x) returns the base 2 logarithm of x.
How many times must we multiply 2 to get 8?
Math.log10(x) returns the base 10 logarithm of x.
How many times must we multiply 10 to get 1000?
For a complete reference, go to our Complete Math Object Reference.
The reference contains descriptions and examples of all Math properties and methods.
Use the correct Math method to create a random number.
let r = ;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.