code-rag-bench/online-tutorials huggingface dataset:
Python Program to accept string ending with alphanumeric character

When it is required to check if a string ends with an alphanumeric character or not, the regular expression is used. A method is defined that checks to see an alphanumeric characters, and returns the string as output.
Below is a demonstration of the same
import re

regex_expression = '[a-zA-z0-9]$'

def check_string(my_string):

   if(re.search(regex_expression, my_string)):
      print("The string ends with alphanumeric character")

   else:
      print("The string doesnot end with alphanumeric character")


my_string_1 = "Python@"
print("The string is :")
print(my_string_1)
check_string(my_string_1)

my_string_2 = "Python1245"
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2)
The string is :
Python@
The string doesn’t end with alphanumeric character
The string is :
Python1245
The string ends with alphanumeric character
The required packages are imported.
The required packages are imported.
A regular expression string is defined.
A regular expression string is defined.
A method named ‘check_string’ is defined, and it takes the string as a parameter.
A method named ‘check_string’ is defined, and it takes the string as a parameter.
The ‘search’ method is called and checked to see if a string ends with a specific character.
The ‘search’ method is called and checked to see if a string ends with a specific character.
Outside the method, the string is defined and displayed on the console.
Outside the method, the string is defined and displayed on the console.
The method is called by passing this string.
The method is called by passing this string.
The output is displayed on the console.
The output is displayed on the console.
What is the difference between = and: = assignment operators?

Actually, they both are assignment operator and used to assign values but the significant difference between them is as follows −
= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator.
mysql> Update estimated_cost1 SET Tender_value = '8570.000' where id = 2;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> Update estimated_cost1 SET Tender_value := '8575.000' where id = 2;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
In the above two queries, we have used the = operator as well as: = operator to UPDATE the value of the table.
mysql> Set @A = 100;
Query OK, 0 rows affected (0.01 sec)

mysql> Select @A;
+------+
| @A   |
+------+
| 100  |
+------+
1 row in set (0.00 sec)

mysql> Set @B := 100;
Query OK, 0 rows affected (0.00 sec)

mysql> Select @B;
+------+
| @B   |
+------+
| 100  |
+------+
1 row in set (0.00 sec)
In the above two queries, we used = operator and: = operator to assign a value to a user variable. We can see that in both the situations = operator and: = operator have the same usage and functionality. But in the following query = operator, works as a comparison operator and give the result as ‘TRUE’ i.e. both the user variables @A and @B are having same values.
mysql> Select @A = @B;
+---------+
| @A = @B |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)
Add dictionary to tuple in Python

When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
The 'append' method adds elements to the end of the list.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)

print ("The tuple is : " )
print(my_tuple_1)

my_dict = {"Hey" : 11, "there" : 31, "Jane" : 23}

print("The dictionary is : ")
print(my_dict)

my_tuple_1 = list(my_tuple_1)
my_tuple_1.append(my_dict)
my_tuple_1 = tuple(my_tuple_1)

print("The tuple after adding the dictionary elements is : ")
print(my_tuple_1)
The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
The dictionary is :
{'Hey': 11, 'there': 31, 'Jane': 23}
The tuple after adding the dictionary elements is :
(7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})
A tuple is defined and is displayed on the console.
A dictionary is defined and is displayed on the console.
The tuple is converted to a list, and the dictionary is added to it using the 'append' method.
Then, this resultant data is converted to a tuple.
This result is assigned to a value.
It is displayed as output on the console.
GATE | GATE-CS-2015 (Set 2) | Question 29 - GeeksforGeeks

07 Sep, 2021
Match the following:
      List-I                  List-II
A. Lexical analysis       1. Graph coloring
B. Parsing                2. DFA minimization
C. Register allocation    3. Post-order traversal
D. Expression evaluation  4. Production tree
Codes:
    A B C D
(a) 2 3 1 4
(b) 2 1 4 3
(c) 2 4 1 3
(d) 2 3 4 1
(A) a(B) b(C) c(D) dAnswer: (C)Explanation:
Register allocation is a variation of Graph Coloring problem.

Lexical Analysis uses DFA.

Parsing makes production tree

Expression evaluation is done using tree traversal 
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:20 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 1) | Question 56
How to use PowerShell Break with the Label.

When the break statement is mentioned with the Label, PowerShell exits to the label instead of exiting the current loop.
$i = 1
while ($i -lt 10) {
   Write-Output "i = $i"
   if($i -eq 5){
      Write-Output "Break statement executed"
      Break :mylable
   }
   $i++
}
Write-Output "Entering to another loop"
$j = 1
:mylable while($j -lt 3){
   Write-Output "j = $j"
   $j++
}
i = 1
i = 2
i = 3
i = 4
i = 5
Break statement executed
Entering to another loop
j = 1
j = 2
As you can see in the above example when the value of 5 executed, the block containing label (mylable) is also executed and execution moves to another loop.
How to use Python Numpy to generate  Random Numbers?

The random module in Numpy package contains many functions for generation of random numbers
numpy.random.rand() − Create an array of the given shape and populate it with random samples
>>> import numpy as np
>>> np.random.rand(3,2)
array([[0.10339983, 0.54395499],
[0.31719352, 0.51220189],
[0.98935914, 0.8240609 ]])
numpy.random.randn() − Return a sample (or samples) from the “standard normal” distribution.
>>> np.random.randn()
-0.6808986872330651
numpy.random.randint() − Return random integers from low (inclusive) to high (exclusive).
>>> np.random.randint(5, size=(2, 4))
array([[2, 4, 0, 4],
[3, 4, 1, 2]])
numpy.random.random() − Return random floats in the half-open interval [0.0, 1.0).
>>> np.random.random_sample()
0.054638060174776126
DAX Time Intelligence - TOTALMTD function

Evaluates the value of the expression for the month to date, in the current context.
TOTALMTD (<expression>, <dates>, [<filter>]) 

expression
An expression that returns a scalar value.
dates
A column that contains dates.
filter
Optional.
An expression that specifies a filter to apply to the current context.
A scalar value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
The filter parameter can be a Boolean expression or a table expression that defines a filter.
If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead.
Month Running Sum:= TOTALMTD (SUM (Sales[Sales Amount]),Sales[Date]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Return pointer from functions in C

We have seen in the last chapter how C programming allows to return an array from a function. Similarly, C also allows to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −
int * myFunction() {
   .
   .
   .
}
Second point to remember is that, it is not a good idea to return the address of a local variable outside the function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an array name which represents a pointer, i.e., address of first array element.
#include <stdio.h>
#include <time.h>
 
/* function to generate and return random numbers. */
int * getRandom( ) {

   static int  r[10];
   int i;
 
   /* set the seed */
   srand( (unsigned)time( NULL ) );
	
   for ( i = 0; i < 10; ++i) {
      r[i] = rand();
      printf("%d\n", r[i] );
   }
 
   return r;
}
 
/* main function to call above defined function */
int main () {

   /* a pointer to an int */
   int *p;
   int i;

   p = getRandom();
	
   for ( i = 0; i < 10; i++ ) {
      printf("*(p + [%d]) : %d\n", i, *(p + i) );
   }
 
   return 0;
}
When the above code is compiled together and executed, it produces the following result −
1523198053
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022

 Print
 Add Notes
 Bookmark this page
How to check if multiple strings exist in another string in Python?

To check if any of the strings in an array exists in another string, you can use the any function. 
arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(c in str for c in arr):
    print "Found a match"
This will give you the output:
Found a match
Though an overkill, you can also use regex to match the array. For example:
import re
arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(re.findall('|'.join(arr), str)):
    print 'Found a match'
This will give you the output:
Found a match
How to set background color of a view in Android App

This example demonstrates about How do I change the color of Button in Android when clicked.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="16dp"
      android:background="#046B5F"
      android:padding="16dp"
      android:text="My View Background color"
      android:textColor="#fff" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

23 Dec, 2020
Consider a non-pipelined processor with a clock rate of 2.5 gigahertz and average cycles per instruction of four. The same processor is upgraded to a pipelined processor with five stages; but due to the internal pipeline delay, the clock speed is reduced to 2 gigahertz. Assume that there are no stalls in the pipeline. The speed up achieved in this pipelined processor is __________.(A) 3.2(B) 3.0(C) 2.2(D) 2.0Answer: (A)Explanation:
Speedup = ExecutionTimeOld / ExecutionTimeNew

ExecutionTimeOld = CPIOld * CycleTimeOld
                  [Here CPI is Cycles Per Instruction]
                 = CPIOld * CycleTimeOld
                 = 4 * 1/2.5 Nanoseconds
                 = 1.6 ns

Since there are no stalls, CPInew can be assumed 1 on average.
ExecutionTimeNew = CPInew * CycleTimenew
                 = 1 * 1/2
                 = 0.5

Speedup = 1.6 / 0.5 = 3.2
Refer http://www.cs.berkeley.edu/~pattrsn/252F96/Lecture2a.pdf for more information on this topic.Quiz of this Question
vivekyemul786
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2016 (Set 2) | Question 61
RxJS - Transformation Operator groupBy

In groupBy operator, the output is grouped based on a specific condition and these group items are emitted as GroupedObservable.
groupBy(keySelector_func: (value: T) => K):GroupedObservables

keySelector_func − A function that gives the key for each item from the source observable.
The return value is an Observable that emits values as a GroupedObservables.
import { of , from} from 'rxjs';
import { groupBy } from 'rxjs/operators';

const data = [
   {groupId: "QA", value: 1},
   {groupId: "Development", value: 3},
   {groupId: "QA", value: 5},
   {groupId: "Development", value: 6},
   {groupId: "QA", value: 2},
];

from(data).pipe(
   groupBy(item => item.groupId)
)
.subscribe(x => console.log(x));
If you see the output, it is an observable wherein the items are grouped. The data we have given has 2 groups QA and Development. The output shows the grouping of the same as shown below −

    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
Peewee - Using MySQL

As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql.
First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/.
You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html ).
Next, we install pymysql module, DB-API compatible Python driver.
pip install pymysql

The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP.
If you choose to create database programmatically, use following Python script −
import pymysql

conn = pymysql.connect(host='localhost', user='root', password='')
conn.cursor().execute('CREATE DATABASE mydatabase')
conn.close()
Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it.
The MySQLDatabase object requires server credentials such as host, port, user name and password.
from peewee import *
db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
   age=IntegerField()
   class Meta:
      database=db
      db_table='MyUser'
db.connect()
db.create_tables([MyUser])
The Phpmyadmin web interface now shows myuser table created.
 Print
 Add Notes
 Bookmark this page
How to set python environment variable PYTHONPATH on Linux?

To set the PYTHONPATH on linux to point Python to look in other directories for module and package imports, export the PYTHONPATH variable as follows:
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
In this case we are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
time.Time.Hour() Function in Golang With Examples - GeeksforGeeks

19 Apr, 2020
The Time.Hour() function in Go language is used to check the hour within the day in which the stated “t” presents itself in the range [0, 23]. 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 (t Time) Hour() int

Here, “t” is the stated time.
Return Value: It returns the hour within the day in which the stated “t” occurs.
Example 1:
// Golang program to illustrate the usage of// Time.Hour() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t in UTC    t := time.Date(2020, 5, 36,       11, 45, 04, 0, time.UTC)      // Calling Hour method    hr := t.Hour()      // Prints hour as specified    fmt.Printf("The stated hour "+      "within the day is: %v\n", hr)}
Output:
The stated hour within the day is: 11

Example 2:
// Golang program to illustrate the usage of// Time.Hour() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t in UTC    t := time.Date(2020, 5, 36,       29, 45, 04, 0, time.UTC)      // Calling Hour method    hr := t.Hour()      // Prints hour as specified    fmt.Printf("The stated hour"+     " within the day is: %v\n", hr)}
Output:
The stated hour within the day is: 5

Here, the stated hour is out of usual range but it is normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Explain the MUL() function in JavaScript ? - GeeksforGeeks

25 Jul, 2021
The MUL function is a miniature of the multiplication function. In this function, we call the function that required an argument as a first number, and that function calls another function that required another argument and this step goes on. 
The first function’s argument is x, the second function argument is y and the third is z, so the return value will be xyz.
Syntax:
function mul(x) {
  return function (y) {
    return function (z) {
      return x * y * z;
    };
  };
}
Example: Below example illustrates the MUL() function in JavaScript.
Javascript
<script>function mul(x) {  return function(y) {    return function(z) {      return x*y*z;    };  }}  console.log(mul(2)(3)(5));console.log(mul(2)(3)(4));</script>
Output:
30
24
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert string to bool in C#

To convert a string to a bool, use the Bool.parse method in C# −
Firstly, set a string −
string str = "false";
Now, convert it to bool −
bool.Parse(str);
Here is the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      string str = "false";
      bool res = bool.Parse(str);
      Console.WriteLine(res);
   }
}
False
Minimum number of operations on an array to make all elements 0 using C++.

Given an array of size N and each element is either 1 or 0. The task is to calculated the minimum number of operations to be performed to convert all elements to zero. One can perform below operations −
If an element is 1, You can change its value equal to 0 then −
If the next consecutive element is 1, it will automatically get converted to 0
If the next consecutive element is 1, it will automatically get converted to 0
If the next consecutive element is already 0, nothing will happen.
If the next consecutive element is already 0, nothing will happen.
If arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1} then 4
operation are required to make all elements zero
1.If the current element is 1 then increment the count and search for the next 0 as all consecutive 1’s will be automatically converted to 0.
2. Return final count
#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int performMinOperation(int *arr, int n){
   int i, cnt = 0;
   for (i = 0; i < n; ++i) {
      if (arr[i] == 1) {
         int j;
         for (j = i + 1; j < n; ++j) {
            if (arr[j] == 0) {
               break;
            }
         }
         i = j - 1;
         ++cnt;
      }
   }
   return cnt;
}
int main(){
   int arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1};
   cout << "Minimum required operations = " << performMinOperation(arr, SIZE(arr)) << endl;
   return 0;
}
When you compile and execute the above program. It generates the following output −
Minimum required operations = 4
Conversion Functions in SQL

There may be times when the SQL query was expecting some data type but it got another. In that case type conversion is done by SQL. This is implicit type conversion. However, sometimes the programmer explicitly converts one data type into another in a query. This is known as explicit type conversion. Both of these in detail are given as follows:
In implicit data type conversion, the SQL programmer does not specify anything. Rather the system converts one type of data to another as per its requirements. For example - a numeric data type can be converted to character if required and vice versa.
Implicit DataType Conversion only occurs if the data types used in the query are valid so that the system can recognise them and convert them as required. This is not possible with invalid or wrongly provided data types.
If the programmer wants,they can explicitly convert data types from one form to another. There are SQL functions provided  for this express purpose. These SQL functions are −
This function is used to explicitly convert a number or date data type to char.
The syntax of this function is given as follows −
TO_CHAR(number,format,parameters)
This function changes number to char with the specific format as provided according to the syntax. The parameters can be used to specify decimal characters, group separators etc.
For example −
SELECT CHAR(sysdate, “Month DD,YYYY”) FROM DUAL;
This returns the system date in the form of 31 July, 2018
This function is used to explicitly convert a string to number. If the string to be converted does not contain numeric characters then TO_NUMBER shows an error.
The syntax of this function is given as follows −
TO_NUMBER(number,format,parameters)
This function changes the given string to number with the specific format as provided according to the syntax.
The parameters and format are optional so to convert a string to a number
For example,
TO_NUMBER (‘353.78’);
This returns the string 353.78 in numerical format.
This function takes character values and returns the output in the date format.
The syntax of this function is given as follows −
TO_DATE(number, format, parameters)
This function changes the given string to number with the specific format as provided according to the syntax.
SELECT TO_DATE(‘2018/07/31’,’yyyy/mm/dd’) FROM DUAL;
This takes the values in character format and returns them in date format as specified.
How to determine the user IP address using node.js ? - GeeksforGeeks

05 Feb, 2021
Node.js is an open-source, back-end JavaScript runtime environment that runs on the web engine and executes JavaScript code. There are various platforms such as Windows, Linux, Mac OS  where Node.js can run. The Domain Name System is a hierarchical and decentralized naming system for computers etc that are connected to the Internet. To find the IP address of the user in Node.js we use dns.lookup() method of dns module.
dns.lookup() function:
dns.lookup(hostname[, options], callback)
Parameters:
Hostname: It consists website link which is valid or active.Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error.
Hostname: It consists website link which is valid or active.
Option: Default value is 0. It can be 0, 4 or 6 which indicates IPv4 and IPv6 addresses.
Callback: This function has user’s IP address and family(i.e. IPv4 and IPv6) and error.
Approach to determine IP address:
Import dns module in the node.js file.Use dns.lookup() function to search for addresses and family of the client.Display address and family.
Import dns module in the node.js file.
Use dns.lookup() function to search for addresses and family of the client.
Display address and family.
Implementation:
index.js
// Import fileconst dns = require('dns');  // dns.lookup() function searches// for user IP address and family// if there is no errordns.lookup('www.geeksforgeeks.org', (err, addresses, family) => {      // Print the address found of user    console.log('addresses:', addresses);      // Print the family found of user      console.log('family:', family);});
Run  index.js file using the below command:
node client_ip.js
Output:
Reference:https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Can we call methods of the superclass from a static method in java?

Inheritance can be defined as the process where one (parent/super) class acquires the properties (methods and fields) of another (child/sub). With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties is known as a subclass and the class whose properties are inherited is called superclass.  In short, in inheritance, you can access the members (variables and methods) of the superclass using the subclass object.
 Live Demo
class SuperClass {
   public void display(){
      System.out.println("Hello this is the method of the superclass");
   }
}
public class SubClass extends SuperClass {
   public void greet(){
      System.out.println("Hello this is the method of the subclass");
   }
   public static void main(String args[]){
      SubClass obj = new SubClass();
      obj.display();
      obj.greet();
   }
}
Hello this is the method of the superclass
Hello this is the method of the subclass
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
 Live Demo
class SuperClass{
   public void display() {
      System.out.println("This is a static method of the superclass");
   }
}
public class SubClass extends SuperClass{
   public static void main(String args[]){
      //Calling methods of the superclass
      new SuperClass().display(); //superclass constructor
      new SubClass().display(); //subclass constructor
   }
}
This is a static method of the superclass
This is a static method of the superclass
3-way Merge Sort in C++

Merge sort involves recursively dividing the array into 2 parts, sorting and finally merging them. A variant of merge sort is treated as 3-way merge sort where instead of dividing the array into 2 parts we divide it into 3 parts.
Merge sort breaks down the arrays to subarrays of size half in recursive manner. In the same way, 3-way Merge sort breaks down the arrays to subarrays of size one third.
Input : 46, -1, -44, 79, 31, -41, 11, 20 , 74, 94
Output : -44 -41 -1 11 20 31 46 74 79 94

Input : 24, -18
Output : -18 24
The time complexity of 3 way merge sort is nlog3n.
// C++ Program for performing 3 way Merge Sort
#include <bits/stdc++.h>
usingnamespacestd;
voidmerge1(intgArray1[], intlow1, intmid1,
intmid2, inthigh1, intdestArray1[]){
   inti = low1, j = mid1, k = mid2, l = low1;
   // choose smaller of the smallest in the three ranges
   while((i < mid1) && (j < mid2) && (k < high1)){
      if(gArray1[i] < gArray1[j]){
         if(gArray1[i] < gArray1[k]){
            destArray1[l++] = gArray1[i++];
         }
         else{
               destArray1[l++] = gArray1[k++];
            }
      }
   else{
         if(gArray1[j] < gArray1[k]){
            destArray1[l++] = gArray1[j++];
         }
   else{
         destArray1[l++] = gArray1[k++];
      }
   }
}
while((i < mid1) && (j < mid2)){
   if(gArray1[i] < gArray1[j]){
      destArray1[l++] = gArray1[i++];
   }
   else{
      destArray1[l++] = gArray1[j++];
   }
}
while((j < mid2) && (k < high1)){
   if(gArray1[j] < gArray1[k]){
   destArray1[l++] = gArray1[j++];
}
else{
      destArray1[l++] = gArray1[k++];
   }
}
while((i < mid1) && (k < high1)){
         if(gArray1[i] < gArray1[k]){
            destArray1[l++] = gArray1[i++];
         }
   else{
         destArray1[l++] = gArray1[k++];
      }
   }
   while(i < mid1)
   destArray1[l++] = gArray1[i++];
   while(j < mid2)
   destArray1[l++] = gArray1[j++];
   while(k < high)
   destArray1[l++] = gArray1[k++];
}
voidmergeSort3WayRec(intgArray1[], intlow1,
inthigh1, intdestArray1[]){
   if(high1 - low1 < 2)
   return;
   intmid1 = low1 + ((high1 - low1) / 3);
   intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1;
   mergeSort3WayRec(destArray1, low1, mid1, gArray1);
   mergeSort3WayRec(destArray1, mid1, mid2, gArray1);
   mergeSort3WayRec(destArray1, mid2, high1, gArray1);
   merge(destArray1, low1, mid1, mid2, high1, gArray1);
}
voidmergeSort3Way(intgArray1[], intn1){
   if(n1 == 0)
   return;
   intfArray1[n];
   for(inti = 0; i < n1; i++)
   fArray1[i] = gArray1[i];
   // sort function
   mergeSort3WayRec(fArray1, 0, n, gArray1);
   for(inti = 0; i < n1; i++)
   gArray1[i] = fArray1[i];
}
// Driver Code
intmain(){
   intdata1[] = {46, -1, -44, 79, 31,
   -41, 11, 20, 74, 94};
   mergeSort3Way(data1,10);
   cout<< "After 3 way merge sort: ";
   for(inti = 0; i < 10; i++){
         cout<< data1[i] << " ";
      }
   return0;
}
After 3 way merge sort: -44 -41 -1 11 20 31 46 74 79 94
Print first m multiples of n without using any loop in Python

21 Nov, 2018
Given n and m, print first m multiples of a m number without using any loops in Python.
Examples:
Input : n = 2, m = 3
Output : 2 4 6 

Input : n = 3, m = 4
Output : 3 6 9 12 

We can use range() function in Python to store the multiples in a range.First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop.
Below is the Python implementation of the above approach:
# function to print the first m multiple# of a number n without using loop.def multiple(m, n):      # inserts all elements from n to     # (m * n)+1 incremented by n.    a = range(n, (m * n)+1, n)          print(*a)  # driver code m = 4n = 3multiple(m, n)
Output:
3 6 9 12

Note : In Python 3, print(*(range(x)) is equivalent to print(" ".join([str(i) for i in range(x)]))
Python list-programs
python-list
python-puzzle
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operating Systems | Process Synchronization | Question 5

02 Feb, 2013
The atomic fetch-and-set x, y instruction unconditionally sets the memory location x to 1 and fetches the old value of x in y without allowing any intervening access to the memory location x. consider the following implementation of P and V functions on a binary semaphore .
void P (binary_semaphore *s) {
  unsigned y;
  unsigned *x = &(s->value);
  do {
     fetch-and-set x, y;
  } while (y);
}

void V (binary_semaphore *s) {
  S->value = 0;
}

Which one of the following is true?(A) The implementation may not work if context switching is disabled in P.(B) Instead of using fetch-and-set, a pair of normal load/store can be used(C) The implementation of V is wrong(D) The code does not implement a binary semaphoreAnswer: (A)Explanation: Let us talk about the operation P(). It stores the value of s in x, then it fetches the old value of x, stores it in y and sets x as 1. The while loop of a process will continue forever if some other process doesn’t execute V() and sets the value of s as 0. If context switching is disabled in P, the while loop will run forever as no other process will be able to execute V().
Operating Systems-Process Management
Process Management
Operating Systems Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operating Systems | Input Output Systems | Question 5
Operating Systems | Input Output Systems | Question 2
CPU Scheduling Numerical Questions
Operating Systems | Deadlock | Question 1
File System Inconsistency
Operating Systems | CPU Scheduling | Question 7
Operating Systems | CPU Scheduling | Question 6
Program to show that Linux provides time sharing environment to processes
Get to know Ubuntu 18.04 LTS | Welcome Bionic Beaver!!
Operating Systems | Deadlock | Question 2
PyQt5 – How to change size of the Label | label.resize method

26 Mar, 2020
While designing any GUI(Graphical User Interface) application we create labels that provide information, but sometimes there might be a case when the label size is not appropriate for the content then need of resizing of label arises.
In this tutorial, we will see how to change the size of the label in PyQt5. For this we will use resize() method.
Syntax : label.resize(width, height)
Argument : It takes two integers as the argument which are :1. Width to be set.2. Height to be set.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel('Normal Label', self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        self.label_2 = QLabel('====== extra width label =====', self)          # moving position        self.label_2.move(100, 150)          # setting up border        self.label_2.setStyleSheet("border: 1px solid black;")          # resizing the widget        self.label_2.resize(200, 20)          # creating a label widget        self.label_3 = QLabel('tiny label', self)          # moving position        self.label_3.move(100, 200)          # setting up border        self.label_3.setStyleSheet("border: 1px solid black;")          # resizing the widget        self.label_3.resize(60, 15)              # show all the widgets        self.show()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib – How to show the coordinates of a point upon mouse click?

To create a custom mouse cursor in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Bind the function *mouse_event* to the event *button_press_event*.
Bind the function *mouse_event* to the event *button_press_event*.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot the x and y data points using plot() method.
Plot the x and y data points using plot() method.
To display the figure, use Show() method.
To display the figure, use Show() method.
import numpy as np
from matplotlib import pyplot as plt

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

def mouse_event(event):
    print('x: {} and y: {}'.format(event.xdata, event.ydata))

fig = plt.figure()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)

x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y)

plt.show()

It will produce the following output −
Now, click different points on the plot and it will show their coordinates on the console.
x: -3.099305446290094 and y: -0.013811108549791173
x: -0.2865652183685867 and y: -0.2067543563498595
x: -3.0280968329249927 and y: -0.1844916739113902
x: -5.7696284474814 and y: 0.4240216460734405
x: -3.9182044999887626 and y: 0.6837529411889172
Python | Find missing elements in List

19 Jun, 2019
Sometimes, we can get elements in range as input but some values are missing in otherwise consecutive range. We might have a use case in which we need to get all the missing elements. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehensionWe can perform the task of finding missing elements using the range function to get the maximum element fill and then insert the elements if there is a miss.
# Python3 code to demonstrate# Finding missing elements in List# using list comprehension  # initializing listtest_list = [3, 5, 6, 8, 10]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension# Finding missing elements in Listres = [ele for ele in range(max(test_list)+1) if ele not in test_list]  # print resultprint("The list of missing elements : " + str(res))
The original list : [3, 5, 6, 8, 10]
The list of missing elements : [0, 1, 2, 4, 7, 9]

 
Method #2 : Using set()This problem can also be performed using the properties of difference of set and then getting the elements that are missing in a range.
# Python3 code to demonstrate# Finding missing elements in List# Using set()  # initializing listtest_list = [3, 5, 6, 8, 10]  # printing original listprint("The original list : " + str(test_list))  # Using set()# Finding missing elements in Listres = list(set(range(max(test_list) + 1)) - set(test_list))  # print resultprint("The list of missing elements : " + str(res))
The original list : [3, 5, 6, 8, 10]
The list of missing elements : [0, 1, 2, 4, 7, 9]

Akanksha_Rai
Python list-programs
Python
Python Programs
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()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Null Pointer Exception in Java Programming

NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value.
For example, using a method on a null reference.
 Live Demo
public class Tester {
   public static void main(String[] args) {
      Object ref = null;
      ref.toString(); // this will throw a NullPointerException
   }
}
Exception in thread "main" java.lang.NullPointerException
	at Tester.main(Tester.java:4)
How to draw a circular gradient in HTML5?

This method returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2.
createRadialGradient(x0, y0, r0, x1, y1, r1)
Here are the parameter values of the createRadialGradient() method −
You can try to run the following code to learn how to draw a radial/circular gradient in HTML5 −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML5 Radial Gradient</title>
   </head>

   <body>
      <canvas id="newCanvas" width="450" height="250" style="border:1px solid
         #d3d3d3;"></canvas>
      <script>
         var c = document.getElementById("newCanvas");
         var ctxt = c.getContext("2d");
         var linegrd = ctxt.createRadialGradient(75, 50, 5, 90, 60, 100);
         linegrd.addColorStop(0, "#FFFFFF");
         linegrd.addColorStop(1, "#66CC00");
         ctxt.fillStyle = linegrd;
         ctxt.fillRect(20, 10, 200, 150);
      </script>
   </body>
</html>
How to zoom a portion of an image and insert in the same plot in Matplotlib?

To zoom a portion of an image and insert in the same plot, we can take the following steps −
Create x and y points, using numpy.
Create x and y points, using numpy.
To zoom a part of an image, we can make data for x and y points, in that range.
To zoom a part of an image, we can make data for x and y points, in that range.
Plot x and y points (Step 1), using the plot() method with lw=2, color red and label.
Plot x and y points (Step 1), using the plot() method with lw=2, color red and label.
Use the legend() method to place text for the plot, Main curve.
Use the legend() method to place text for the plot, Main curve.
Create the axes using the axes() method by putting the rectangle’s coordinate.
Create the axes using the axes() method by putting the rectangle’s coordinate.
Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot.
Plot x and y points (Step 2), using the plot() method with lw=1, color='green' and label, i.e., subpart of the plot.
Use the legend() method to place text for the plot, zoomed curve.
Use the legend() method to place text for the plot, zoomed curve.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 1000)
y = np.sin(x)
x_zoom = np.linspace(-1, 1, 50)
y_zoom = np.sin(x_zoom)
plt.plot(x, y, c='red', lw=2, label="Main curve")
plt.legend()
axes = plt.axes([.30, .6, .20, .15])
axes.plot(x_zoom, y_zoom, c='green', lw=1, label="Zoomed curve")
axes.legend()
plt.show()
How to use __dir__ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
Consider the following directory structure −
A directory called "master", that has two files named 'worker_1', and 'worker_2'. The master directory itself is a subfolder of the main project directory.
The project directory also contains an index.php file.
Consider having two files in a directory called inc, which is a subfolder of our project's directory, where the index.php file lies −
project_directory
├── master
│ ├── worker_1.php
│ └── worker_2.php
└── index.php
If we execute the code −
include "master/worker_1.php";
from the index.php, it runs successfully.
But to run worker_1.php by including worker_2.php, a relative include to the index.php file has to be done, as shown below −
include "master/worker_2.php";
Using __DIR__ will get this running. From worker_1.php the below code can be executed −
<?php
include __DIR__ . "/worker_2.php";
How to set viewport height and width in CSS

To set viewport height in CSS:
h1 {
   font-size: 4.0vh;
}
To set viewport width in CSS:
h1 {
   font-size: 5.5vw;
}