code-rag-bench/online-tutorials huggingface dataset:
Serving html pages from node.js

So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code.
sendFile() function−
Response object gives a sendFile() function to return a html file to client.
How to provide path to html file in sendFile() ?
We import the path core module of node.js.
const path = require(‘path’);
path has a join function . __dirname is a global variable which holds the actual path to project main folder.
path.join(__dirname, ‘views’, ‘add-user.html’); This will refer to the actual file location of add-user html code.
App.js
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/test',route);
app.use((req, res,next)=>{
   res.status(404).send('<h1> Page not found </h1>');
});
const server = http.createServer(app);
server.listen(3000);
route.js
const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
   // res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username">    <button type="submit"> Send </button> </form>'); res.sendFile(path.join(__dirname, 'views', 'add-   user.html'));
});
router.post('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;
add-user.html
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
   <body>
      <form action="/test/post-username" method="POST">
      <input type="text" name="username">
      <button type="submit"> Send </button>
   </form>
</body>
</html>
On running app: npm start
Browser output: localhost:3000/test/add-username
With the use of path module, it will work on any type of operating system without error. Every OS has different way of handling path, so path module takes care of it.
Loop through array and edit string JavaScript

Let’s say, we have to write a function, say translate() that accepts a string as the first argument
and any number of words after that.
The string will actually contain n $ signs like this −
This $0 is more $1 just a $2.
Then there will be 3 strings which will replace the corresponding places.
For example −
If the function call is like this −
translate(‘This $0 is more $1 just a $2.’, ‘game’, ‘than’, ‘game’);
The output of the function should be −
This game is more than just a game.
This functionality is more or less like the template injecting in JavaScript.
Therefore, let’s write the code for this function −
We will use the String.prototype.replace() method here. We know that if we use a regex pattern
to match all occurrences and use a function as the second parameter, it gets executed for each
match. We will do exactly the same here.
The code for doing this will be −
const str = 'This $0 is more $1 just a $2';
const translate = (str, ...texts) => {
   const regex = /\$(\d+)/gi;
   return str.replace(regex, (item, index) => {
      return texts[index];
   });
};
console.log(translate(str, 'game', 'just', 'game'));
The output in the console will be −
This game is more just just a game
Find the count of EMPTY or NULL columns in a MySQL table?

Let us first create a table −
mysql> create table DemoTable781 (
   Name varchar(100)
);
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable781 values('');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable781 values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable781 values('');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable781 values(null);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable781 values(null);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable781 values('');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable781 values(null);
Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable781;
This will produce the following output -
+-------+
| Name  |
+-------+
|       |
| Chris |
|       |
| NULL  |
| NULL  |
|       |
| NULL  |
+-------+
7 rows in set (0.00 sec)
Here is the query to find the count of EMPTY or NULL columns in a MySQL table −
mysql> (select SUM(CASE when Name IS NULL THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781)
UNION ALL
(select SUM(CASE when Name='' THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781);
This will produce the following output -
+------------------------+
| NullCountAndEmptyCount |
+------------------------+
| 3                      |
| 3                      |
+------------------------+
2 rows in set (0.00 sec)
Find the cordinates of the fourth vertex of a rectangle with given 3 vertices in Python

Suppose we have a grid of size Q * P, this grid contains exactly three asterisk '*' and every other cell there is dot '.', where '*' is for a vertex of a rectangle. We have to find the coordinates of the missing vertex. Here we will consider 1-based indexing.
So, if the input is like grid = [ ".*.", "...", "*.*" ], then the output will be [1, 3], this is the missing coordinate.
To solve this, we will follow these steps −
p := number of rows
p := number of rows
q := number of columns
q := number of columns
row := make a map for all row number, and associated value is 0
row := make a map for all row number, and associated value is 0
col := make a map for all column number, and associated value is 0
col := make a map for all column number, and associated value is 0
for i in range 0 to p, dofor j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1for each k,v in row, doif v is same as 1, thenx_coord := k;for each k,v in col, doif v is same as 1, theny_coord := k;
for i in range 0 to p, do
for j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1
for j in range 0 to q, do
if grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1
if grid[i, j] is same as '*', then
row[i] := row[i] + 1
row[i] := row[i] + 1
col[j] := col[j] + 1
col[j] := col[j] + 1
for each k,v in row, doif v is same as 1, thenx_coord := k;
for each k,v in row, do
if v is same as 1, thenx_coord := k;
if v is same as 1, then
x_coord := k;
x_coord := k;
for each k,v in col, doif v is same as 1, theny_coord := k;
for each k,v in col, do
if v is same as 1, theny_coord := k;
if v is same as 1, then
y_coord := k;
y_coord := k;
return(x_coord + 1, y_coord + 1)
return(x_coord + 1, y_coord + 1)
Let us see the following implementation to get better understanding −
 Live Demo
def get_missing_vertex(grid) :
   p = len(grid)
   q = len(grid[0])
   row = dict.fromkeys(range(p), 0)
   col = dict.fromkeys(range(q), 0)
   for i in range(p) :
      for j in range(q) :
         if (grid[i][j] == '*') :
            row[i] += 1
            col[j] += 1
   for k,v in row.items() :
      if (v == 1) :
         x_coord = k;
   for k,v in col.items() :
      if (v == 1) :
         y_coord = k;
   return (x_coord + 1, y_coord + 1)
grid = [".*.", "...", "*.*"]
print(get_missing_vertex(grid))
[".*.", "...", "*.*"]
(1, 3)
Node.js Date.parse() API - GeeksforGeeks

12 Mar, 2021
The date-and-time.Date.parse() is a minimalist collection of functions for manipulating JS date and time module which is used to parse the date according to a certain pattern.
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
parse(dateString, arg)
Parameters: This method takes the following arguments as parameters:
dateString: It is the string object of the date
arg: It is the required date format.
Return Value: This method returns parsed date and time.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.parse() method  // Importing moduleconst date = require('date-and-time')  // Creating object of current date and time // by using Date() const now  =  new Date('07-03-2021');  // Parsing the date and time// by using date.parse() methodconst value = date.parse(now.toLocaleDateString(),'D/M/YYYY');  // Display the resultconsole.log("parsed date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
parsed date and time :
Thu Jan 01 1970 00:00:00 GMT+0530 (India Standard Time)
Example 2:
index.js
// Node.js program to demonstrate the  // Date.parse() method  // Importing moduleconst date = require('date-and-time')  // Parsing the date and time// by using date.parse() methodconst value = date.parse('23:14:05 GMT+0900','HH:mm:ss [GMT]Z');  // Display the resultconsole.log("Parsed date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
Parsed date and time :
Thu Jan 01 1970 19:44:05 GMT+0530 (India Standard Time)
Reference: https://github.com/knowledgecode/date-and-time
NodeJS date-time
NodeJS-API
Node.js
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
Mongoose find() Function
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
Python 3 - os.chmod() Method

The method chmod() changes the mode of path to the passed numeric mode. The mode may take one of the following values or bitwise ORed combinations of them −
stat.S_ISUID − Set user ID on execution.
stat.S_ISUID − Set user ID on execution.
stat.S_ISGID − Set group ID on execution.
stat.S_ISGID − Set group ID on execution.
stat.S_ENFMT − Record locking enforced.
stat.S_ENFMT − Record locking enforced.
stat.S_ISVTX − Save text image after execution.
stat.S_ISVTX − Save text image after execution.
stat.S_IREAD − Read by owner.
stat.S_IREAD − Read by owner.
stat.S_IWRITE − Write by owner.
stat.S_IWRITE − Write by owner.
stat.S_IEXEC − Execute by owner.
stat.S_IEXEC − Execute by owner.
stat.S_IRWXU − Read, write, and execute by owner.
stat.S_IRWXU − Read, write, and execute by owner.
stat.S_IRUSR − Read by owner.
stat.S_IRUSR − Read by owner.
stat.S_IWUSR − Write by owner.
stat.S_IWUSR − Write by owner.
stat.S_IXUSR − Execute by owner.
stat.S_IXUSR − Execute by owner.
stat.S_IRWXG − Read, write, and execute by group.
stat.S_IRWXG − Read, write, and execute by group.
stat.S_IRGRP − Read by group. 
stat.S_IRGRP − Read by group. 
stat.S_IWGRP − Write by group. 
stat.S_IWGRP − Write by group. 
stat.S_IXGRP − Execute by group.
stat.S_IXGRP − Execute by group.
stat.S_IRWXO − Read, write, and execute by others.
stat.S_IRWXO − Read, write, and execute by others.
stat.S_IROTH − Read by others.
stat.S_IROTH − Read by others.
stat.S_IWOTH − Write by others.
stat.S_IWOTH − Write by others.
stat.S_IXOTH − Execute by others.
stat.S_IXOTH − Execute by others.
Following is the syntax for chmod() method −
os.chmod(path, mode)

path − This is the path for which mode would be set.
path − This is the path for which mode would be set.
mode − This may take one of the above mentioned values or bitwise ORed combinations of them.
mode − This may take one of the above mentioned values or bitwise ORed combinations of them.
This method does not return any value.
Note − Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.
The following example shows the usage of chmod() method.
#!/usr/bin/python3
import os, sys, stat

# Assuming /tmp/foo.txt exists, Set a file execute by the group.
os.chmod("/tmp/foo.txt", stat.S_IXGRP)

# Set a file write by others.
os.chmod("/tmp/foo.txt", stat.S_IWOTH)

print ("Changed mode successfully!!")
When we run the above program, it produces the following result −
Changed mode successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
PL/SQL - Nested IF-THEN-ELSE Statements

It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).
IF( boolean_expression 1)THEN 
   -- executes when the boolean expression 1 is true  
   IF(boolean_expression 2) THEN 
      -- executes when the boolean expression 2 is true  
      sequence-of-statements; 
   END IF; 
ELSE 
   -- executes when the boolean expression 1 is not true 
   else-statements; 
END IF; 

DECLARE 
   a number(3) := 100; 
   b number(3) := 200; 
BEGIN 
   -- check the boolean condition  
   IF( a = 100 ) THEN 
   -- if condition is true then check the following  
      IF( b = 200 ) THEN 
      -- if condition is true then print the following  
      dbms_output.put_line('Value of a is 100 and b is 200' ); 
      END IF; 
   END IF; 
   dbms_output.put_line('Exact value of a is : ' || a ); 
   dbms_output.put_line('Exact value of b is : ' || b ); 
END; 
/ 
When the above code is executed at the SQL prompt, it produces the following result −
Value of a is 100 and b is 200 
Exact value of a is : 100 
Exact value of b is : 200  

PL/SQL procedure successfully completed. 

 Print
 Add Notes
 Bookmark this page
Angular10 getLocaleId() Function - GeeksforGeeks

30 Apr, 2021
In this article, we are going to see what is getLocaleId in Angular 10 and how to use it.
The getLocaleId is used to get the locale ID from the current locale.
Syntax:
getLocaleId(locale: string): string
NgModule: Module used by getLocaleId is:
CommonModule
Approach:
Create the angular app to be used
In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleId.
import { LOCALE_ID, NgModule } from '@angular/core';
In app.component.ts import getLocaleId and LOCALE_ID
inject LOCALE_ID as a public variable.
In app.component.html show the local variable using string interpolation
serve the angular app using ng serve to see the output.
Parameters:
locale: the locale code
Return value:
string: the locale code.
Example 1:
app.module.ts
import { LOCALE_ID, NgModule }         from '@angular/core';import { BrowserModule }         from '@angular/platform-browser';  import { AppRoutingModule }         from './app-routing.module';import { AppComponent }         from './app.component';  @NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    AppRoutingModule  ],  providers: [      { provide: LOCALE_ID, useValue: 'en-GB' },  ],  bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
import {FormStyle,        getLocaleId,         TranslationWidth}         from '@angular/common';  import { Component,          Inject,OnInit,          LOCALE_ID }          from '@angular/core';  @Component({    selector: 'app-root',    templateUrl: './app.component.html'})export class AppComponent {    for = getLocaleId(this.locale);    constructor(        @Inject(LOCALE_ID) public locale: string,){}      }
app.component.html
<h1>   GeeksforGeeks</h1><p>Locale id is: {{for}}</p>
Output:
Reference: https://angular.io/api/common/getLocaleId
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Angular PrimeNG Dropdown Component
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?
Changing the color of an axis in Matplotlib

First, we can get the axes. Then, ax.spines could help to set the color by specifying the name of the axes, i.e., top, bottom, right and left.
Add an axes to the current figure and make it the current axes.
Add an axes to the current figure and make it the current axes.
Using step 1 axes, we can set the color of all the axes.
Using step 1 axes, we can set the color of all the axes.
Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue.
Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue.
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
from matplotlib import pyplot as plt

ax = plt.axes()

ax.spines['bottom'].set_color('yellow')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('black')
ax.spines['left'].set_color('blue')

plt.show()
Marker interface in Java programming.

An empty interface in Java is known as a marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented. java.lang.Cloneable and java.io.Serializable are examples of marker interfaces.
Consider the following example, here we have a class with the name Student which implements the marking interface Cloneable. In the main method we are trying to create an object of the Student class and clone it using the clone() method.
 Live Demo
import java.util.Scanner;
public class Student implements Cloneable {
   int age;
   String name;
   public Student (String name, int age){
      this.age = age;
      this.name = name;
   }
   public void display() {
      System.out.println("Name of the student is: "+name);
      System.out.println("Age of the student is: "+age);
   }
   public static void main (String args[]) throws CloneNotSupportedException {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your age: ");
      int age = sc.nextInt();
      Student obj = new Student(name, age);
      Student obj2 = (Student) obj.clone();
      obj2.display();
   }
}
Enter your name:
Krishna
Enter your age:
29
Name of the student is: Krishna
Age of the student is: 29
In the following java program, the class Student has two instance variables name and age where age is declared transient. In another class named ExampleSerialize, we are trying to serialize and desterilize the Student object and display its instance variables. Since the age is made invisible (transient) only the name-value is displayed.
 Live Demo
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
   private String name;
   private transient int age;
   public Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public int getAge() {
      return this.age;
   }
}
public class ExampleSerialize {
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = new FileOutputStream("e:\\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std1);
      FileInputStream fis = new FileInputStream("e:\\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student std2 = (Student) ois.readObject();
      System.out.println(std2.getName());
   }
}
Krishna
Git - Patch Operation

Patch is a text file, whose contents are similar to Git diff, but along with code, it also has metadata about commits; e.g., commit ID, date, commit message, etc. We can create a patch from commits and other people can apply them to their repository.
Jerry implements the strcat function for his project. Jerry can create a path of his code and send it to Tom. Then, he can apply the received patch to his code.
Jerry uses the Git format-patch command to create a patch for the latest commit. If you want to create a patch for a specific commit, then use COMMIT_ID with the format-patch command.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project/src

[jerry@CentOS src]$ git status -s
M string_operations.c
?? string_operations

[jerry@CentOS src]$ git add string_operations.c

[jerry@CentOS src]$ git commit -m "Added my_strcat function"

[master b4c7f09] Added my_strcat function
1 files changed, 13 insertions(+), 0 deletions(-)

[jerry@CentOS src]$ git format-patch -1
0001-Added-my_strcat-function.patch

The above command creates .patch files inside the current working directory. Tom can use this patch to modify his files. Git provides two commands to apply patches git amand git apply, respectively. Git apply modifies the local files without creating commit, while git am modifies the file and creates commit as well.
To apply patch and create commit, use the following command −
[tom@CentOS src]$ pwd
/home/tom/top_repo/project/src

[tom@CentOS src]$ git diff

[tom@CentOS src]$ git status –s

[tom@CentOS src]$ git apply 0001-Added-my_strcat-function.patch

[tom@CentOS src]$ git status -s
M string_operations.c
?? 0001-Added-my_strcat-function.patch

The patch gets applied successfully, now we can view the modifications by using the git diff command.
[tom@CentOS src]$ git diff

The above command will produce the following result −
diff --git a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..f282fcf 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,5 +1,16 @@
#include <stdio.h>
+char *my_strcat(char *t, char *s)
diff --git a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..f282fcf 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,5 +1,16 @@
#include <stdio.h>
+char *my_strcat(char *t, char *s)
+
{
   +
   char *p = t;
   +
   +
   +
   while (*p)
   ++p;
   +
   while (*p++ = *s++)
   + ;
   + return t;
   +
}
+
size_t my_strlen(const char *s)
{
   const char *p = s;
   @@ -23,6 +34,7 @@ int main(void)
   {


    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
Count the Number of matching characters in a pair of string in Python

We are given two strings. We need to find the count it of the characters in the first string which are also present in a second string.
The set function gives us unique values all the elements in a string. We also use the the & operator which finds the common elements between the two given strings.
 Live Demo
strA = 'Tutorials Point'
uniq_strA = set(strA)
# Given String
print("Given String\n",strA)
strB = 'aeio'
uniq_strB = set(strB)
# Given String
print("Search character strings\n",strB)
common_chars = uniq_strA & uniq_strB
print("Count of matching characters are : ",len(common_chars))
Running the above code gives us the following result −
Given String
Tutorials Point
Search character strings
aeio
Count of matching characters are : 3
We use the search function from the re module. We use a count variable and keep incrementing it when the search result is true.
 Live Demo
import re
strA = 'Tutorials Point'
# Given String
print("Given String\n",strA)
strB = 'aeio'
# Given String
print("Search character strings\n",strB)
cnt = 0
for i in strA:
   if re.search(i, strB):
      cnt = cnt + 1
print("Count of matching characters are : ",cnt)
Running the above code gives us the following result −
Given String
Tutorials Point
Search character strings
aeio
Count of matching characters are : 5
Explain attributes and the different types of attributes in DBMS?

Attributes are the properties which describe an entity.
Example
The attributes of student entity are as follows −
Roll number
Roll number
Name
Name
Branch
Branch
Age
Age
The different types of attributes are as follows −
It can be divided into smaller sub parts, each sub part can form an independent attribute.
For example −
                                             Name
                                 FirstName MiddelName LastName
Attributes that cannot be further subdivided are called atomic attributes.
For example −
                        Phone number
                        PIN code
Attributes having a single value for a particular item is called a single valued attribute.
For example: Room Number
Attribute having a set of values for a single entity is called a multi-valued attribute.
For example −
               e-mail
               Tel.No
               Hobbies
When one attribute value is derived from the other is called a derived attribute.
For example: Age can be derived from date of birth, where,
Age is the derived attribute.
Age is the derived attribute.
DOB is the stored attribute.
DOB is the stored attribute.
Nesting of composite and multi-valued attributes forms a complex attribute.
For example
If a person has more than one house and each house has more than one phone. Then, that attribute phone is represented as a complex attribute.
Creating a Pandas Series from Lists - GeeksforGeeks

06 Jan, 2019
A Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type.
Let’s see how to create a Pandas Series from lists.
Method #1 : Using Series() method without any argument.
# import pandas as pdimport pandas as pd  # create Pandas Series with default index values# default index ranges is from 0 to len(list) - 1x = pd.Series(['Geeks', 'for', 'Geeks'])  # print the Seriesprint(x)
Output : Method #2 : Using Series() method with 'index' argument.
# import pandas lib. as pdimport pandas as pd  # create Pandas Series with define indexesx = pd.Series([10, 20, 30, 40, 50], index =['a', 'b', 'c', 'd', 'e'])  # print the Seriesprint(x)
Output :
Another example:
# import pandas lib. as pdimport pandas as pd  ind = [10, 20, 30, 40, 50, 60, 70]  lst = ['Geeks', 'for', 'Geeks', 'is',            'portal', 'for', 'geeks']              # create Pandas Series with define indexesx = pd.Series(lst, index = ind)  # print the Seriesprint(x)
Output:
Method #3: Using Series() method with multi-list
# importing pandas import pandas as pd  # multi-listlist = [ ['Geeks'], ['For'], ['Geeks'], ['is'],         ['a'], ['portal'], ['for'], ['geeks'] ]           # create Pandas Seriesdf = pd.Series((i[0] for i in list))  print(df)
Output:
pandas-series-program
Picked
Python pandas-series
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
Query a nested field within an array with MongoDB

To query a nested field within an array, use $elemMatch in MongoDB. Let us create a collection with documents −
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Chris","ClientProject":"Online Banking System"},{"ClientName":"David","ClientProject":"Online School Management"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e351957fdf09dd6d08539df")
}
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Carol","ClientProject":"Online Book System"},{"ClientName":"Mike","ClientProject":"Game Development"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0")
}
Display all documents from a collection with the help of find() method −
> db.demo153.find();
This will produce the following output −
{
   "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [
      { "ClientName" : "Chris", "ClientProject" : "Online Banking System" },
      { "ClientName" : "David", "ClientProject" : "Online School Management" }
   ]
}
{
   "_id" : ObjectId("5e3519c9fdf09dd6d08539e0"), "ClientDetails" : [
      { "ClientName" : "Carol", "ClientProject" : "Online Book System" },
      { "ClientName" : "Mike", "ClientProject" : "Game Development" }
   ]
}
Following is how to query a nested field within an array −
> db.demo153.find({"ClientDetails": { "$elemMatch" : {"ClientProject": { "$in": ["Online Banking System"] } } } });
This will produce the following output −
{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }
Ext.js - Class System

Ext JS is a JavaScript framework having functionalities of object oriented programming. Ext is the namespace, which encapsulates all the classes in Ext JS.
Ext provides more than 300 classes, which we can use for various functionalities.
Ext.define() is used for defining the classes in Ext JS.
Ext.define(class name, class members/properties, callback function);

Class name is the name of the class according to app structure. For example,  appName.folderName.ClassName studentApp.view.StudentView.
Class properties/members defines the behavior of class.
Callback function is optional. It is called when the class has loaded properly.
Ext.define(studentApp.view.StudentDeatilsGrid, {
   extend : 'Ext.grid.GridPanel',
   id : 'studentsDetailsGrid',
   store : 'StudentsDetailsGridStore',
   renderTo : 'studentsDetailsRenderDiv',
   layout : 'fit',
   
   columns : [{
      text : 'Student Name',
      dataIndex : 'studentName'
   },{
      text : 'ID',
      dataIndex : 'studentId'
   },{
      text : 'Department',
      dataIndex : 'department'
   }]
});
As like other OOPS based languages, we can create objects in Ext JS as well.
Following are the different ways of creating objects in Ext JS.
var studentObject = new student();
studentObject.getStudentName();

Ext.create('Ext.Panel', {
   renderTo : 'helloWorldPanel',
   height : 100,
   width : 100,
   title : 'Hello world',
   html : 	'First Ext JS Hello World Program'		
});
Inheritance is the principle of using functionality defined in class A into class B.
In Ext JS, inheritance can be done using two methods −
Ext.define(studentApp.view.StudentDetailsGrid, {
   extend : 'Ext.grid.GridPanel',
   ...
});
Here, our custom class StudentDetailsGrid is using the basic features of Ext JS class GridPanel.
Mixins is a different way of using class A in class B without extend.
mixins : {
   commons : 'DepartmentApp.utils.DepartmentUtils'
},
Mixins are added in the controller where we declare all the other classes such as store, view, etc. In this way, we can call DepartmentUtils class and use its functions in the controller or in this application.
 Print
 Add Notes
 Bookmark this page
Scala Stack take() method with example - GeeksforGeeks

03 Nov, 2019
In Scala Stack class, the take() method is utilized to return a stack consisting of the first ‘n’ elements of the stack.
Method Definition: def take(n: Int): Stack[A]
Return Type: It returns a stack consisting of the first ‘n’ elements of the stack.
Example #1:
// Scala program of take() // method   // Import Stack import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating stack        val s1 = Stack(1, 2, 3, 4)                   // Print the stack         println(s1)                    // Applying take method          val result = s1.take(2)                  // Display output         print("Stack containing first two elements: " + result)              } } 
Stack(1, 2, 3, 4)
Stack containing first two elements: Stack(1, 2)

Example #2:
// Scala program of take() // method   // Import Stack import scala.collection.mutable._  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating stack        val s1 = Stack(1, 2, 3, 4)                   // Print the stack         println(s1)                    // Applying take method          val result = s1.take(3)                  // Display output         print("Stack containing first three elements: " + result)              } } 
Stack(1, 2, 3, 4)
Stack containing first three elements: Stack(1, 2, 3)

Scala
scala-collection
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Operators in Scala
Class and Object in Scala
Scala String substring() method with example
Inheritance in Scala
Throw Keyword in Scala
Hello World in Scala
Scala | Arrays
PyQt5 – Setting and accessing WHATS THIS help text for Status Bar - GeeksforGeeks

26 Mar, 2020
n PyQt5 there are lots of widgets and bars and when we tend to make an application, we end up putting lots of windows and for each window there exit status bar. Sometimes we can’t remember why this status bar is used and what is this status bar. That’s why for back-end purposes PyQt5 allows us to set help text. In this article we will see how to set and access help text for status bar.
In order to set help text we use setWhatsThis() method and for accessing the help text we use whatsThis() method.
Syntax :
self.statusBar().setWhatsThis()
self.statusBar().whatsThis()

Argument :setWhatsThis() takes string as argument.whatsThis() takes no argument.
Return :setWhatsThis() return NonewhatsThis() returns string.
Code:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)          # setting status bar message        self.statusBar().showMessage("This is status bar")          # setting  border        self.statusBar().setStyleSheet("border :3px solid black;")          # setting help text        self.statusBar().setWhatsThis("this is help text for status bar")          # creating a label widget        self.label_1 = QLabel(self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :1px solid blue;")          # accessing help text of status bar        help = self.statusBar().whatsThis()          # setting text to label        self.label_1.setText(help)          # resizing label        self.label_1.adjustSize()          # 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.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
Google Charts - Basic Timelines Chart

Following is an example of a basic timelines chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used Timeline class to show timelines diagram.
//Timeline chart
var chart = new google.visualization.Timeline(document.getElementById('container'));

googlecharts_timelines_basic.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript" src = "https://www.google.com/jsapi">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['timeline']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = new google.visualization.DataTable();
            data.addColumn({ type: 'string', id: 'President' });
            data.addColumn({ type: 'date', id: 'Start' });
            data.addColumn({ type: 'date', id: 'End' });
            data.addRows([
            [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
            [ 'Adams',      new Date(1797, 2, 4),  new Date(1801, 2, 4) ],
            [ 'Jefferson',  new Date(1801, 2, 4),  new Date(1809, 2, 4) ]]);

            var options = {      
               width: '100%', 
               height: '100%'
            };
                  
            // Instantiate and draw the chart.
            var chart = new google.visualization.Timeline(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Python - Get Indices of Even Elements from list - GeeksforGeeks

23 Jan, 2020
Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Even elements.
Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for even element in list and append its index accordingly.
# Python3 code to demonstrate working of# Even Elements indices# using loop  # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19]  # printing original listprint("The original list is : " + str(test_list))  # Even Elements indices# using loopres = []for idx, ele in enumerate(test_list):    if ele % 2 == 0:        res.append(idx)          # printing resultprint("Indices list Even elements is : " + str(res))
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]

 
Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner.
# Python3 code to demonstrate working of# Even Elements indices# using list comprehension  # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19]  # printing original listprint("The original list is : " + str(test_list))  # Even Elements indices# using list comprehensionres = [idx for idx, ele in enumerate(test_list) if ele % 2 == 0]          # printing resultprint("Indices list Even elements is : " + str(res))
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
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 program to check whether a number is Prime or not
Haskell - Function Composition

Function Composition is the process of using the output of one function as an input of another function. It will be better if we learn the mathematics behind composition. In mathematics, composition is denoted by f{g(x)} where g() is a function and its output in used as an input of another function, that is, f().
Function composition can be implemented using any two functions, provided the output type of one function matches with the input type of the second function. We use the dot operator (.) to implement function composition in Haskell.
Take a look at the following example code. Here, we have used function composition to calculate whether an input number is even or odd.
eveno :: Int -> Bool 
noto  :: Bool -> String 

eveno x = if x `rem` 2 == 0 
   then True 
else False 
noto x = if x == True 
   then "This is an even Number" 
else "This is an ODD number" 

main = do 
   putStrLn "Example of Haskell Function composition" 
   print ((noto.eveno)(16))
Here, in the main function, we are calling two functions, noto and eveno, simultaneously. The compiler will first call the function "eveno()" with 16 as an argument. Thereafter, the compiler will use the output of the eveno method as an input of noto() method.
Its output would be as follows −
Example of Haskell Function composition                
"This is an even Number"

Since we are supplying the number 16 as the input (which is an even number), the eveno() function returns true, which becomes the input for the noto() function and returns the output: "This is an even Number".
 Print
 Add Notes
 Bookmark this page
RPAD() Function in MySQL - GeeksforGeeks

21 Jun, 2021
RPAD() function in MySQL is used to pad or add a string to the right side of the original string. 
Syntax :  
RPAD(str, len, padstr)
Parameter : This function accepts three parameter as mentioned above and described below :  
str : The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string.  
 
len : This is the length of a final string after the right padding.  
 
padstr : String that to be added to the right side of the Original Str.  
Returns : It returns a new string of length len after padding. 
Example-1 : Applying RPAD() Function to a string to get a new padded string.  
SELECT RPAD("geeksforgeeks", 20, "*") AS RightPaddedString;
Output : 
 
Example-2 : Applying RPAD() Function to a string when the original string is larger than the len parameter.  
SELECT RPAD("geeksforgeeks", 10, "*") AS RightPaddedString;
Output : 
 
Example-3 : Applying RPAD() Function to a string column in a table : 
Table – Student_Details : 
 
 
SELECT RPAD(Name, 15, "#") AS RightPadStudentName
FROM Student_Details;
Output : 
 
 
abhishek0719kadiyan
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
How does MySQL handle out of range numeric values?

Handling of MySQL numeric value that is out of allowed range of column data type depends upon the SQL mode in following ways −
(A) Enabled SQL strict mode - When strict SQL mode is enabled, MySQL returns the error on entering the put-of-range value. In this case, the insertion of some or all the values got failed.
For example, we have created a table with two columns having TINYINT and UNSIGNED TINYINT as their data types on columns.
mysql> Create table counting(Range1 Tinyint, Range2 Tinyint Unsigned);
Query OK, 0 rows affected (0.14 sec)
Now with the help of the following command, we enabled the strict SQL mode
mysql> Set SQL_MODE ='traditional';
Query OK, 0 rows affected (0.00 sec)
Now, if we will try to insert the out-of-range values into the columns, MySQL reflects the error and both the insertions failed which can be checked by the query below −
mysql> Insert into Counting(Range1, Range2) Values(256,256);
ERROR 1264 (22003): Out of range value for column 'Range1' at row 1

mysql> Select * from counting;
Empty set (0.00 sec)
(B) Disabled SQL strict mode -  When the restrictive SQL mode is disabled, the value is clipped by MySQL up to the suitable endpoint of that column data type and accumulate the resulting value. MySQL reflects warnings which are the result of column-assignment conversion that occurs due to clipping.
For example, if we will insert the values in the column after disabling the SQL strict mode, MySQL will reflect the warnings and stores the values after trimming them up to the suitable end-point. It can be understood with the queries below −
mysql> Set SQL_MODE = '';
Query OK, 0 rows affected (0.00 sec)

mysql> Insert Into Counting(Range1,Range2) values (256,256);
Query OK, 1 row affected, 2 warnings (0.02 sec)

mysql> Show Warnings;
+---------+------+-------------------------------------------------+
| Level   | Code | Message                                         |
+---------+------+-------------------------------------------------+
| Warning | 1264 | Out of range value for column 'Range1' at row 1 |
| Warning | 1264 | Out of range value for column 'Range2' at row 1 |
+---------+------+-------------------------------------------------+
2 rows in set (0.00 sec)

mysql> Select * from Counting;
+--------+--------+
| Range1 | Range2 |
+--------+--------+
| 127    | 255    |
+--------+--------+
1 row in set (0.00 sec)
Convert from any base to decimal and vice versa in C++

In this tutorial, we will be discussing a program to convert from any base to a decimal and vice versa.
For this we will be provided with an integer and its base. Our task is to convert the number to its decimal equivalent. Further we will also be performing the reverse of this procedure as well.
 Live Demo
#include <stdio.h>
#include <string.h>
//returning values of a character
int val(char c) {
   if (c >= '0' && c <= '9')
      return (int)c - '0';
   else
      return (int)c - 'A' + 10;
}
//converting number to decimal equivalent
int convert_decimal(char *str, int base) {
   int len = strlen(str);
   int power = 1;
   int num = 0;
   int i;
   for (i = len - 1; i >= 0; i--) {
      if (val(str[i]) >= base) {
         printf("Invalid Number");
         return -1;
      }
      num += val(str[i]) * power;
      power = power * base;
   }
   return num;
}
int main() {
   char str[] = "11A";
   int base = 16;
   printf("Decimal equivalent of %s in base %d is " " %d\n", str, base, convert_decimal(str, base));
   return 0;
}
Decimal equivalent of 11A in base 16 is 282
Now performing the reverse of the operation.
 Live Demo
#include <stdio.h>
#include <string.h>
//returning values of a character
char reVal(int num) {
   if (num <= 0 && num >= 9)
      return (char)(num + '0');
   else
      return (char)(num - 10 + 'A');
}
//reversing a given string
void reverse_string(char *str) {
   int len = strlen(str);
   int i;
   for (i = 0; i < len/2; i++) {
      char temp = str[i];
      str[i] = str[len-i-1];
      str[len-i-1] = temp;
   }
}
//converting to equivalent number with base 'b'
char* convert_base(char res[], int base, int inputNum) {
   int index = 0;
   while (inputNum > 0) {
      res[index++] = reVal(inputNum % base);
      inputNum /= base;
   }
   res[index] = '\0';
   //reversing the result
   reverse_string(res);
   return res;
}
int main() {
   int inputNum = 282, base = 16;
   char res[100];
   printf("Equivalent of %d in base %d is "" %s\n", inputNum, base, convert_base(res, base, inputNum));
   return 0;
}
Equivalent of 282 in base 16 is 11A