code-rag-bench/online-tutorials huggingface dataset:
Scala Map drop() method with example - GeeksforGeeks

13 Aug, 2019
The drop() method is utilized to delete the first ‘n’ elements.
Method Definition: def drop(n: Int): Map[A, B]
Return Type: It returns all the elements of the map except the first ‘n’ elements.
Example #1:
// Scala program of drop()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 5)                  // Applying drop method        val result = m1.drop(1)                  // Displays output        println(result)          }}
Map(for -> 3, cs -> 5)

Example #2:
// Scala program of drop()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map("geeks" -> 5, "for" -> 3, "geeks" -> 5)                  // Applying drop method        val result = m1.drop(1)                  // Displays output        println(result)          }}
Map(for -> 3)

So, both the identical keys are removed from the map.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Hello World in Scala
Scala | Case Class and Case Object
Scala | Functions - Basics
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala List map() method with example
Comments In Scala
Abstract Classes in Scala
How to access a local variable from a different function using C++ pointers?

You can't access a local variable once it goes out of scope. This is what it means to be a local variable. Though, Let us look at an example where you MIGHT be able to access a local variable's memory outside its scope.
#include<iostream>
int* foo() {
   int x = 3;
   return &x;
}
int main() {
   int* address = foo();
   cout << *address;
   *address = 12;
   cout << *address;
}
This might give the output −
3
12
As I've mentioned before, this code MIGHT work. We are simply reading and writing to memory that USED to be the address of x. In main, you're outside of foo's scope, the address is a pointer to some random memory area. In the above example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it(you won't be using another process' memory area or any other unauthorized memory area), and nothing else has overwritten it yet. Hence, the 3 is still there.
In a real program, that memory might have been re-used almost immediately and you'd break something by something like doing this. Such memory access bugs are very difficult to track and kill.
When you return from foo, the program tells the OS that x's memory is no longer being used and it can be reassigned to something else. If you're lucky and it gets reassigned, and the OS doesn't catch you using it again, then you can get away with it.
Lower case column names with MySQL SELECT?

Let us first create a table −
mysql> create table DemoTable
   (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserFirstName varchar(20),
   UserLastName varchar(20),
   UserAge int,
   UserCountryName varchar(20)
   );
Query OK, 0 rows affected (0.27 sec)
Now check the description of table.
mysql> desc DemoTable;
This will produce the following output −
+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| UserId          | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserFirstName   | varchar(20) | YES  |     | NULL    |                |
| UserLastName    | varchar(20) | YES  |     | NULL    |                |
| UserAge         | int(11)     | YES  |     | NULL    |                |
| UserCountryName | varchar(20) | YES  |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Following is the query to convert case to lower case column names while using SELECT.
mysql> SELECT LOWER(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'DemoTable';
This will produce the following output −
+--------------------+
| LOWER(COLUMN_NAME) |
+--------------------+
| userage            |
| usercountryname    |
| userfirstname      |
| userid             |
| userlastname       |
+--------------------+
5 rows in set (0.03 sec)
How to set the favicon size in CSS rather than HTML attributes?

A favicon is a little icon visible on the web browser tab, just before the page title. It is generally a logo with the smaller size.
You cannot add the size using CSS. The standards do not support adding Favicon size using CSS. Let’s add it using attributes,
<link rel="icon" type="image/png" href="https://tutorialspoint.com/favicon-16x16.png" sizes="16x16">
The result after adding Favicon above will be,
What is correct syntax to create Python lists?

List is a collection of comma separated objects, not necessarily of same type, and put inside square brackets []. List object is mutable and an item can appear more than once in the collection.
>>> L1=["Raaj", 23, ["Phy", "Che", "maths"],8.5]
Date toInstant() Method in Java with Examples - GeeksforGeeks

26 Mar, 2019
The toInstant() method of Date class in Java is used to convert a Date object to an Instant object. An Instant is created during the conversion which is used to represent the same point on the timeline as this Date.
Syntax:
public Instant toInstant()
Parameters: The method does not take any parameters.
Return Value: The method returns an Instant representing the same point on the timeline as this Date.
Below programs illustrate the use of toInstant() method in Java:Example 1:
// Java code to demonstrate// toInstant() method of Date class  import java.util.Date;import java.util.Calendar;import java.time.Instant;  public class GfG {    public static void main(String args[])    {        // Creating a Calendar object        Calendar c1 = Calendar.getInstance();          // Set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c1.set(Calendar.MONTH, 00);          // Set Date        c1.set(Calendar.DATE, 30);          // Set Year        c1.set(Calendar.YEAR, 2019);          // Creating a date object        // with specified time.        Date dateOne = c1.getTime();          Instant inst = dateOne.toInstant();          System.out.println(            "Original Date: "            + dateOne.toString());        System.out.println(            "Instant: " + inst);    }}
Original Date: Wed Jan 30 06:01:46 UTC 2019
Instant: 2019-01-30T06:01:46.730Z

Example 2:
// Java code to demonstrate// clone() method of Date class  import java.util.Date;import java.util.Calendar;import java.time.Instant;  public class GfG {    public static void main(String args[])    {        // Creating a Calendar object        Calendar c1 = Calendar.getInstance();          // Set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c1.set(Calendar.MONTH, 06);          // Set Date        c1.set(Calendar.DATE, 12);          // Set Year        c1.set(Calendar.YEAR, 1996);          // Creating a date object        // with specified time.        Date dateOne = c1.getTime();          Instant inst = dateOne.toInstant();          System.out.println(            "Original Date: "            + dateOne.toString());        System.out.println(            "Instant: " + inst);    }}
Original Date: Fri Jul 12 06:01:49 UTC 1996
Instant: 1996-07-12T06:01:49.766Z

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant–
Java - util package
Java-Functions
Java-util-Date
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Multithreading in Java
Retrieve property value selectively from array of objects in JavaScript

Suppose, we have an array of objects like this −
const arr = [
   { id : "23", name : "Item 1", isActive : true},
   { id : "25", name : "Item 2", isActive : false},
   { id : "26", name : "Item 3", isActive : false},
   { id : "30", name : "Item 4", isActive : true},
   { id : "45", name : "Item 5", isActive : true}
];
We are required to write a JavaScript function that takes in one such object and return an array of the value of "id" property of all those objects that have true value for the "isActive" property.
The code for this will be −
const arr = [
   { id : "23", name : "Item 1", isActive : true},
   { id : "25", name : "Item 2", isActive : false},
   { id : "26", name : "Item 3", isActive : false},
   { id : "30", name : "Item 4", isActive : true},
   { id : "45", name : "Item 5", isActive : true}
];
const findActive = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const obj = arr[i];
      const {
         id,
         isActive
      } = obj;
      if(isActive){
         res.push(id);
      }
   };
   return res;
};
console.log(findActive(arr));
And the output in the console will be −
[ '23', '30', '45' ]
Program to perform XOR operation in an array using Python

Suppose we have an integer n and another integer start. We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums.
So, if the input is like n = 6, start = 2, then the output will be 14 because the array will be like [2+2*0, 2+2*1, ... 2+2*5] = [2,4,6,8,10,12], then XOR of each element present in the array is 14.
To solve this, we will follow these steps −
count := start
count := start
while n-1 > 0, docount := count XOR 2 + startn := n - 1start := start + 2
while n-1 > 0, do
count := count XOR 2 + start
count := count XOR 2 + start
n := n - 1
n := n - 1
start := start + 2
start := start + 2
return count
return count
Let us see the following implementation to get better understanding −
 Live Demo
def solve(n, start):
   count = start
   while n-1 > 0:
      count ^= 2 + start
      n -= 1
      start += 2
   return count

n = 6
start = 2
print(solve(n, start))
6, 2
14
numpy.ndarray.flat

This function returns a 1-D iterator over the array. It behaves similar to Python's built-in iterator.
import numpy as np 
a = np.arange(8).reshape(2,4) 
print 'The original array:' 
print a 
print '\n' 

print 'After applying the flat function:' 
# returns element corresponding to index in flattened array 
print a.flat[5]
Its output is as follows −
The original array:
[[0 1 2 3]
 [4 5 6 7]]

After applying the flat function:
5


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to append elements to a Pandas series?

In this program, we will append elements to a Pandas series. We will use the append() function for this task. Please note that we can only append a series or list/tuple of series to the existing series.
Step1: Define a Pandas series, s1.
Step 2: Define another series, s2.
Step 3: Append s2 to s1.
Step 4: Print the final appended series.
import pandas as pd

s1 = pd.Series([10,20,30,40,50])
s2 = pd.Series([11,22,33,44,55])

print("S1:\n",s1)
print("\nS2:\n",s2)

appended_series = s1.append(s2)
print("\nFinal Series after appending:\n",appended_series)
S1:
0    10
1    20
2    30
3    40
4    50
dtype: int64

S2:
0    11
1    22
2    33
3    44
4    55
dtype: int64

Final Series after appending:
0    10
1    20
2    30
3    40
4    50
0    11
1    22
2    33
3    44
4    55
dtype: int64
fopen() for an existing file in write mode - GeeksforGeeks

28 May, 2017
In C, fopen() is used to open a file in different modes. To open a file in write mode, “w” is specified. When mode “w” is specified, it creates an empty file for output operations.
What if the file already exists?If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the following program, if “test.txt” already exists, its contents are removed and “GeeksforGeeks” is written to it.
#include <stdio.h>#include <stdlib.h>  int main(){    FILE *fp = fopen("test.txt", "w");    if (fp == NULL)    {        puts("Couldn't open file");        exit(0);    }    else    {        fputs("GeeksforGeeks", fp);        puts("Done");        fclose(fp);    }    return 0;}
The above behavior may lead to unexpected results. If programmer’s intention was to create a new file and a file with same name already exists, the existing file’s contents are overwritten.
The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with w, fopen() returns NULL if file already exists or could not open. Following is modified C11 program that doesn’t overwrite an existing file.
#include <stdio.h>#include <stdlib.h>  int main(){    FILE *fp = fopen("test.txt", "wx");    if (fp == NULL)    {        puts("Couldn't open file or file already exists");        exit(0);    }    else    {        fputs("GeeksforGeeks", fp);        puts("Done");        fclose(fp);    }    return 0;}
References:Do not make assumptions about fopen() and file creationhttp://en.wikipedia.org/wiki/C11_(C_standard_revision)http://www.cplusplus.com/reference/cstdio/freopen/
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-File Handling
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
Structures in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
std::string class in C++
Data Types in C
Batch Script - COPY

This batch command is used for copying files from one location to the other.
Copy [source] [destination]

The files will be copied from source to destination location.
The following example shows the different variants of the copy command.
@echo off
cd
Rem Copies lists.txt to the present working directory.
If there is no destination identified , it defaults to the present working directory.
copy c:\lists.txt
Rem The file lists.txt will be copied from C:\ to C:\tp location
copy C:\lists.txt c:\tp
Rem Quotation marks are required if the file name contains spaces
copy “C:\My File.txt”
Rem Copies all the files in F drive which have the txt file extension to the
current working directory copy
F:\*.txt
Rem Copies all files from dirA to dirB. Note that directories nested in dirA will not be copied
copy C:\dirA dirB
All actions are performed as per the remarks in the batch file.
 Print
 Add Notes
 Bookmark this page
Python PIL | MedianFilter() and ModeFilter() method - GeeksforGeeks

29 Jun, 2019
PIL.ImageFilter.MedianFilter() method creates a median filter. Picks the median pixel value in a window with the given size.
Syntax: PIL.ImageFilter.MedianFilter(size=3)

Parameters:
size: The kernel size, in pixels.

Image used:
# Importing Image and ImageFilter module from PIL package  from PIL import Image, ImageFilter      # creating a image object im1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")      # applying the median filter im2 = im1.filter(ImageFilter.MedianFilter(size = 3))      im2.show() 
Output:
PIL.ImageFilter.ModeFilter() method creates a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.
Syntax: PIL.ImageFilter.ModeFilter(size=3)

Parameters:
size: The kernel size, in pixels.

# Importing Image and ImageFilter module from PIL package  from PIL import Image, ImageFilter      # creating a image object im1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")      # applying the mode filter im2 = im1.filter(ImageFilter.ModeFilter(size = 3))      im2.show() 
Output:
Image-Processing
Python-pil
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
Retrieve a set of Map.Entry elements from a HashMap in Java

Create a HashMap and add elements to it −
HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));
The following is the code snippet to retrieve a set of Map.Entry elements −
Set s = hm.entrySet();
Iterator iter = s.iterator();
System.out.println("\nKey\tValue");
while (iter.hasNext()) {
   Map.Entry e = (Map.Entry) iter.next();
   System.out.println(e.getKey() + " " + e.getValue());
}
The following is an example to retrieve a set of Map.Entry elements from a HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      Set s = hm.entrySet();
      Iterator iter = s.iterator();
      System.out.println("\nKey\tValue");
      while (iter.hasNext()) {
         Map.Entry e = (Map.Entry) iter.next();
         System.out.println(e.getKey() + " " + e.getValue());
      }
   }
}
Map = {Backpack=1200, Belt=600, Wallet=700}

KeyValue
Backpack 1200
Belt 600
Wallet 700
How to change the color of links in HTML?

To change the color of links in HTML, use the CSS property color. Use it with the style attribute. The style attribute specifies an inline style for an element.
Use the style attribute with the CSS property color to change the link color. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code change the color of links in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Link Color</title>
   </head>
   <body>
      <h2>About</h2>
      <p>
         Our <a href="/about/about_team.htm" style="color: red">Team</a>
            comprises of programmers, writers, and analysts.
      </p>
   </body>
</html>
find_by_order() in C++ - GeeksforGeeks

06 Apr, 2021
The find_by_order() is a built-in function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ Standard Template Library but the g++ compiler supports them.
Ordered Set is a policy-based data structure in g++ that maintains unique elements in sorted order. It performs all the operations as performed by Set in STL in O(logN) complexity. In addition to that, the following two operations are also performed in O(logN) complexity:
order_of_key (K): Number of items strictly smaller than K.
find_by_order(k): Kth element in a Set (counting from zero).
The find_by_order() function accepts a key, say K, as an argument and returns the iterator to the Kth largest element in the Set.
Examples:
Considering a Set S = {1, 5, 6, 17, 88}, s.find_by_order(0): Returns the 0th largest element, i.e. the minimum element, i.e. 1.s.find_by_order(2): Returns the 2nd largest element, i.e. 6.
Note: If K >= N, where N is the size of the set, then the function returns either 0 or in some compilers, the iterator to the smallest element. 
Below is the implementation of find_by_order() function in C++:
C++14
// C++ program to implement find_by_order()// for Policy Based Data Structures  #include <bits/stdc++.h>  // Importing header files#include <ext/pb_ds/assoc_container.hpp>using namespace std;using namespace __gnu_pbds;  // Declaring Ordered Settypedef tree<int, null_type, less<int>, rb_tree_tag,        tree_order_statistics_node_update>    pbds;  // Driver Codeint main(){          int arr[] = {1, 5, 6, 17, 88};     int n = sizeof(arr)/sizeof(arr[0]);        pbds S;          // Traverse the array    for (int i = 0; i < n; i++) {                  // Insert array elements          // into the ordered set        S.insert(arr[i]);    }          // Returns iterator to 0-th      // largest element in the set    cout << *S.find_by_order(0) << " ";        // Returns iterator to 2-nd      // largest element in the set    cout << *S.find_by_order(2);      return 0;}
1 6

cpp-advanced
cpp-set
Advanced Data Structure
Competitive Programming
Hash
Sorting
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extendible Hashing (Dynamic approach to DBMS)
Ternary Search Tree
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Advantages of Trie Data Structure
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Competitive Programming - A Complete Guide
Prefix Sum Array - Implementation and Applications in Competitive Programming
PostgreSQL - AUTO INCREMENT

PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases.
If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type.
The type name serial creates an integer columns. The type name bigserial creates a bigint column. bigserial should be used if you anticipate the use of more than 231 identifiers over the lifetime of the table. The type name smallserial creates a smallint column.
The basic usage of SERIAL dataype is as follows −
CREATE TABLE tablename (
   colname SERIAL
);

Consider the COMPANY table to be created as follows −
testdb=# CREATE TABLE COMPANY(
   ID  SERIAL PRIMARY KEY,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);
Now, insert the following records into table COMPANY −
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Paul', 32, 'California', 20000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Allen', 25, 'Texas', 15000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Teddy', 23, 'Norway', 20000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'David', 27, 'Texas', 85000.00 );


INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Kim', 22, 'South-Hall', 45000.00 );

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'James', 24, 'Houston', 10000.00 );
This will insert seven tuples into the table COMPANY and COMPANY will have the following records −
 id | name  | age | address    | salary
----+-------+-----+------------+--------
  1 | Paul  |  32 | California |  20000
  2 | Allen |  25 | Texas      |  15000
  3 | Teddy |  23 | Norway     |  20000
  4 | Mark  |  25 | Rich-Mond  |  65000
  5 | David |  27 | Texas      |  85000
  6 | Kim   |  22 | South-Hall |  45000
  7 | James |  24 | Houston    |  10000

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Ugly Numbers

Ugly numbers are those number whose prime factors are 2, 3 or 5. From 1 to 15, there are 11 ugly numbers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. The numbers 7, 11, 13 are not ugly because they are prime. The number 14 is not ugly because in its prime factor the 7 will come.
In this program, we will try to find the nth ugly number.
Input:
Take the term number. Say it is 10
Output:
The 10th ugly number is 12
getUglyNumbers(n)
Input: The number of terms.
Output: Find nth Ugly numbers.
Begin
   define array named uglyNum of size n
   i2 := 0, i3 := 0, i5 := 0
   next2mul := 2, next3mul := 3, next5Mul := 5
   next := 1
   ugluNum[0] := 1

   for i := 1 to n, do
      next := minimum of next2Mul, next3Mul and next5Mul
      uglyNum[i] := next
      if next = next2Mul, then
         i2 := i2 + 1
         next2mul := uglyNum[i2] * 2
      if next = next3Mul, then
         i3 := i3 + 1
         next3mul := uglyNum[i3] * 3
      if next = next5Mul, then
         i5 := i5 + 1
         next5mul := uglyNum[i5] * 5
   done
   return next
End
# include<iostream>
using namespace std;

int min(int x, int y, int z) {            //find smallest among three numbers
   if(x < y) {
      if(x < z)
         return x;
      else
         return z;
   }else {
      if(y < z)
         return y;
      else
         return z;
   }
}

int getUglyNum(int n) {
   int uglyNum[n];          // To store ugly numbers
   int i2 = 0, i3 = 0, i5 = 0;

   //find next multiple as 1*2, 1*3, 1*5

   int next2mul = 2;
   int next3mul = 3;
   int next5mul = 5;
   int next = 1;              //initially the ugly number is 1

   uglyNum[0] = 1;

   for (int i=1; i<n; i++) {
      next = min(next2mul, next3mul, next5mul);       //find next ugly number
      uglyNum[i] = next;

      if (next == next2mul) {
         i2++;             //increase iterator of ugly numbers whose factor is 2
         next2mul = uglyNum[i2]*2;
      }

      if (next == next3mul) {
         i3++;             //increase iterator of ugly numbers whose factor is 3
         next3mul = uglyNum[i3]*3;
      }

      if (next == next5mul) {
         i5++;              //increase iterator of ugly numbers whose factor is 5
         next5mul = uglyNum[i5]*5;
      }
   }
   return next;        //the nth ugly number
}

int main() {
   int n;
   cout << "Enter term: "; cin >> n;
   cout << n << "th Ugly number is: " << getUglyNum(n) << endl;
}
Enter term: 10
10th Ugly number is: 12
C++ Program to Find Minimum Value of any Algebraic Expression

This is a C++ Program to Find Minimum Value of any Algebraic Expression.An algebraic expression of the form (x1 + x2 + x3 + . . . + xa) * (y1 + y2 + . . . + yb) and (a + b) integers is given.consider all possible combinations of a numbers and remaining b numbers and calculating their values, from which minimum value can be derived.
Begin
   function MaxValue() :
   Arguments:
   a[] = array which store the elements.
   x,y = integers.
   Body of the function:
   1) Find the sum of array elements.
   2) Initialize s=0.
   3) Make for loop i = 0 to (x + y)-1 Shift the integers by 25 so that they become positive.
   4) Declare a boolean array p[i][j] that represents true if sum j can be reachable by choosing i numbers.
   5) Initialization of the array.
   6) Make for loop i = 0 to (x + y)-1 to determine If p[i][j] is true, that means it is possible to select i numbers from (x + y) numbers to sum upto j.
   7) Initialize min_value=INF.
   8) Make for loop i = 0 to (MAX * MAX + 1)-1 to Check if a particular sum can be reachable by choosing x numbers.
   if (p[x][i])
      Get the actual sum as we shifted the numbers by 25 to avoid negative indexing in array .
   9) Print the min_value.
End
#include <bits/stdc++.h>
using namespace std;
#define INF 1e9
#define MAX 25
int MinValue(int a[], int x, int y) {
   int s= 0;
   for (int i = 0; i < (x + y); i++) {
      s+= a[i];
      a[i] += 25;
   }
   bool p[MAX+1][MAX * MAX + 1];
   //Initialize the array to 01.
   memset(p, 0, sizeof(p));
   p[0][0] = 1;
   for (int i = 0; i < (x + y); i++) {
      // k can be at max x because the
      // left expression has x numbers
      for (int k = min(x, i + 1); k >= 1; k--) {
         for (int j = 0; j < MAX * MAX + 1; j++) {
            if (p[k - 1][j])
               p[k][j + a[i]] = 1;
         }
      }
   }
   int min_value = INF;
   for (int i = 0; i < MAX * MAX + 1; i++) {
      if (p[x][i]) {
         int tmp = i - 25 * x;
         min_value = min(min_value, tmp * (s - tmp));
      }
   }
   cout << "Minimum Value: " << min_value ;
}
int main() {
   int x = 2, y = 2; //input is taken of x and y.
   int ar[] = { 7,6,4,3 };
   MinValue(ar, x, y);
   return 0;
}
Minimum Value: 91
How to display an image/screenshot in a Python Tkinter window without saving it?

Tkinter is a standard Python library that is used to create and develop GUI-based applications. To display an image, we use the PIL or Pillow library.
Let us suppose that we want to create an application that will take a screenshot of the window and display the captured image in another window. To achieve this, we can follow the steps given below −
Import the required libraries.
Import the required libraries.
Create a universal button to take the screenshot.
Create a universal button to take the screenshot.
Define a function to take the screenshot.
Define a function to take the screenshot.
In the given function, define the coords and region through which we want to take the screenshot.
In the given function, define the coords and region through which we want to take the screenshot.
Create a Toplevel window and define a label image in it.
Create a Toplevel window and define a label image in it.
Pack the widget and display the output image.
Pack the widget and display the output image.
# Import the required libraries
from tkinter import *
import pyautogui
from PIL import ImageTk, Image

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

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


# Define a function to take the screenshot
def take_screenshot():
   x = 500
   y = 500
   # Take the screenshot in the given corrds
   im1 = pyautogui.screenshot(region=(x, y, 700, 300))

   # Create a toplevel window
   top = Toplevel(win)
   im1 = ImageTk.PhotoImage(im1)

   # Add the image in the label widget
   image1 = Label(top, image=im1)
   image1.image = im1
   image1.place(x=0, y=0)

Button(win, text='Take ScreenShot', command=take_screenshot).pack(padx=10, pady=10)

win.mainloop()
When we run the code, it will display a window with a button to take a screenshot.
Now, click the button "Take ScreenShot" and it will capture the screen of size 700px wide and 300 px height, starting from the coordinates (x=500, y=500).
JavaScript program to check if a given year is leap year

12 Apr, 2019
Prerequisite:Understanding basic JavaScript codes.A year is leap year if following conditions are satisfied:
Year is multiple of 400.
Year is multiple of 4 and not multiple of 100.
Approach:
Get the value of input field by using document.getElementById(“year”).value
Check the given year is leap year or not by using JavaScript expression and display its value.
Example:
<!-- HTML code to implement the given year is     leap year or not --><!DOCTYPE html><html>  <head>    <title>        JavaScript to check leap year    </title></head>  <body>    Input Year: <input type="text" id = "year"/>          <input type="button" id="button" onClick="isLeapYear()"            value="Check Leap Year">          <p id="GFG"></p>          <!-- JavaScript code to check given year is        leap year or not -->    <script>        function isLeapYear() {            var year= document.getElementById("year").value;                          document.getElementById("GFG").innerHTML                 = (year % 100 === 0) ? (year % 400 === 0)                                     : (year % 4 === 0);        }    </script></body>  </html>                    
Output:
Before input year:
After input leap year:
After input not leap year:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++

12 Oct, 2021
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed hereThere is another interesting method to do the same without using the above methods,  using tuples (for returning multiple values ) and pairs (for two values).
We can declare the function with return type as pair or tuple (whichever is required) and can pack the values to be returned and return the packed set of values. The returned values can be unpacked in the calling function.
Tuple
A tuple is an object capable to hold a collection of elements where each element can be of a different type.
Class template std::tuple is a fixed-size collection of heterogeneous values
Pair
This class couples together a pair of values, which may be of different types
A pair is a specific case of a std::tuple with two elements
Note : Tuple can also be used to return two values instead of using pair .
#include<bits/stdc++.h>using namespace std;  // A Method that returns multiple values using// tuple in C++.tuple<int, int, char> foo(int n1, int n2){    // Packing values to return a tuple    return make_tuple(n2, n1, 'a');             }  // A Method returns a pair of values using pairstd::pair<int, int> foo1(int num1, int num2){    // Packing two values to return a pair     return std::make_pair(num2, num1);            }  int main(){    int a,b;    char cc;          // Unpack the elements returned by foo    tie(a, b, cc) = foo(5, 10);                // Storing  returned values in a pair     pair<int, int> p = foo1(5,2);            cout << "Values returned by tuple: ";    cout << a << " " << b << " " << cc << endl;          cout << "Values returned by Pair: ";    cout << p.first << " " << p.second;    return 0;}
Output:
Values returned by tuple: 10 5 a
Values returned by Pair: 2 5

This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
tanwarsinghvaibhav
CPP-Functions
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
Python PIL | ImageDraw.Draw.text()

05 Sep, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.text() Draws the string at the given position.
Syntax:ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)
Parameters:xy – Top left corner of the text.text – Text to be drawn. If it contains any newline characters, the text is passed on to multiline_text()fill – Color to use for the text.font – An ImageFont instance.spacing – If the text is passed on to multiline_text(), the number of pixels between lines.align – If the text is passed on to multiline_text(), “left”, “center” or “right”.
Return Type:returns an image with text.
Image Used:
Code : Using PIL | ImageDraw.Draw.text()
     # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw       # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\rose.jpg')   draw = ImageDraw.Draw(image)   # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20)   text = 'LAUGHING IS THE \n BEST MEDICINE'  # drawing text sizedraw.text((5, 5), text, font = font, align ="left")   image.show() 
Output:
Another Example:Here we changing parameter.
Image Used:
Code : Using PIL | ImageDraw.Draw.text()
     # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw       # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\flower.jpg')   draw = ImageDraw.Draw(image)   # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20)   text = 'LAUGHING IS THE \n BEST MEDICINE'  # drawing text sizedraw.text((5, 5), text, fill ="red", font = font, align ="right")   image.show() 
Output:
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Successor Graph

28 Jan, 2021
A Successor Graph is a directed graph in which each vertex has outdegree one, i.e., exactly one edge starts at each node. A successor graph consists of one or more components, each of which contains one cycle and some paths that lead to it.
Successor graphs are sometimes called functional graphs. The reason for this is that any successor graph corresponds to a function that defines the edges of the graph. The parameter for the function is a node of the graph, and the function gives the successor of that node. For Example, the function
The above function defines the below graph:
Since each node of a successor graph has a unique successor, a function succ(x, k) can also be defined that gives the node when a traversal begin at node x and walk k steps forward. For example, in the above graph succ(4, 6) = 2, because node 2 can be reached by walking 6 steps from node 4:
A straightforward way to calculate a value of succ(x, k) is to start at node x and walk k steps forward, which takes O(k) time. However, using preprocessing, any value of succ(x, k) can be calculated in only O(logk) time.
The idea is to precalculate all values of succ(x, k) where k is a power of two and at most u, where u is the maximum number of steps we will ever walk. This can be efficiently done because we can use the following recursion:
Precalculating the values takes O(n*log u) time because O(log u) values are calculated for each node. In the above graph, the first values are as follows:
After this, any value of succ(x, k) can be calculated by presenting the number of steps k as a sum of powers of two. For example, if we want to calculate the value of succ(x, 11), we first form the representation 11 = 8 + 2 + 1. Using that
For example, in the previous graph
Such a representation always consists of O(log k) parts, so calculating a value of succ(x, k) takes O(log k) time. 
Articles
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How SYSDATE function works in PL/SQL

30 Jan, 2019
The PLSQL SYSDATE function will returns current system date and time on your database. There is no any parameter or argument for the SYSDATE function. The SYSDATE function returns a date value. Note that the SYSDATE function return date and time as “YYYY-MM-DD HH:MM:SS” (string) or as YYYYMMDDHHMMSS (numeric).
Syntax:
SYSDATE

Example-1:
SELECT Sysdate AS System_dateFROM Dual
Explanation:Above example will display current date from system on database. It will execute the Syntax ‘Sysdate’ from dual, which act as dummy table and display date only in default format. In above query ‘System_date’ act as Alias Name i.e., Temporary Name of that specified column.
Output:
1. Display both Date and Time –
Syntax:
SELECT TO_CHAR(Sysdate, Format_Of_Date_and_Time) AS Alias_Name
FROM Dual 

Format_Of_Date_and_Time:
DD-MM-YYYY HH:MM:SS
MM-DD-YYYY HH:MM:SS
YYYY-MM-DD HH:MM:SS
DD-MON-YYYY HH:MM:SS
MON-DD-YY HH:MM:SS
DD-MM-YYYY HH24:MM:SS (For 24hr time Format) 
Example-2:
SELECT TO_CHAR (Sysdate, 'DD-MM-YYYY HH24:MI:SS') AS System_date_timeFROM Dual
Output:
Example-3:
SELECT TO_CHAR (Sysdate, 'YYYY-MON-DD HH24:MI:SS') AS System_date_timeFROM Dual
Output:
Explanation:In above example, it will display both date as well as time on database in specified format. TO_CHAR() Function is basically helpful to convert System date into date and time of specified format. Here ‘System_date_time’ also act as Alias Name and display both date and time in defined column.
2. Display Consecutive Dates from Current Date using Level –
Syntax:
SELECT Sysdate+Level-1
FROM Dual
CONNECT BY Level<=n 
Where n is consecutive number of days.
Example-4:
SELECT Sysdate+Level-1 AS Consecutive_datesFROM DualCONNECT BY Level<=5
Explanation:For display of consecutive number of dates, we can use SYSDATE with LEVEL. Level can be used as hierarchical structure having child nodes like 1 as root then 2 as child then 3. Level have initial value as 1, here Sysdate adds up with Level and act as multilevel structure, then could be helpful to display dates in consecutive manner.
Output:
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Views
Difference between DELETE, DROP and TRUNCATE
CTE in SQL
SQL Trigger | Student Database
SQL using Python
Difference between DELETE and TRUNCATE
SQL | DDL, DML, TCL and DCL
SQL Correlated Subqueries
Window functions in SQL
Difference between DDL and DML in DBMS
Networking in C#

The .NET Framework has a layered, extensible, and managed implementation of networking services. You can easily integrate them into your applications. Use the System.Net; namespace.
Let us see how to acess the Uri class:.In C#, it provides object representation of a uniform resource identifier (URI) −
Uri uri = new Uri("http://www.example.com/");
WebRequest w = WebRequest.Create(uri);
Let us now see the System.Net class. This is used to encorypt connections using using the Secure Socket Layer (SSL). If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.
The following is an example. For SSL with FTP, set the EnableSsl property to true before calling the GetResponse() method.
String uri = "https://www.example.com/";
WebRequest w = WebRequest.Create(uri);

String uriServer = "ftp://ftp.example.com/new.txt"
FtpWebRequest r = (FtpWebRequest)WebRequest.Create(uriServer);
r.EnableSsl = true;
r.Method = WebRequestMethods.Ftp.DeleteFile;
The following is an example showing the usage of System.Net namespace and using the Dns.GetHostEntry, Dns.GetHostName methods and IPHostEntry property AddressList −
using System;
using System.Net;

class Program {
   static void Main() {

      String hostName = string.Empty;
      hostName = Dns.GetHostName();
      Console.WriteLine("Hostname: "+hostName);
      IPHostEntry myIP = Dns.GetHostEntry(hostName);

      IPAddress[] address = myIP.AddressList;

      for (int i = 0; i < address.Length; i++) {
         Console.WriteLine("IP Address {1} : ",address[i].ToString());
      }
      Console.ReadLine();
   }
}
Rexx - Stacks

The stack is sometimes called the external data queue, but we follow common usage and refer to it as the stack. It is a block of memory that is logically external to Rexx. Instructions like push and queue place data into the stack, and instructions like pull and parse pull extract data from it. The queued built-in function reports how many items are in the stack.
Let’s take a look at an example of a stack.
/* STACK: */
/* */ 
/* This program shows how to use the Rexx Stack as either a */ 

/* stack or a queue. */ 
do j = 1 to 3 
push ‘Stack: line #’ || j 

/* push 3 lines onto the stack */ 
end 
do j = 1 to queued() 

/* retrieve and display LIFO */ 
pull line 
say line 
end 
do j = 1 to 3 queue ‘Queue: line #’ || j 

/* queue 3 lines onto the stack */ 
end 
do queued() 

/* retrieve and display FIFO */ 
pull line 
say line 
end 
exit 0
The first do loop in the program places three lines of data onto the stack. It uses the push instruction to do this. We number the lines so that when they are retrieved in the LIFO order their order is apparent.
The items placed into the stack by the push instruction are retrieved in the LIFO order −
do j = 1 to 3 
push ‘Stack: line #’ || j     /* push 3 lines onto the stack */ 
end
The next code block shows the use of the queued built-in function to discover the number of lines on the stack, as well as a loop to retrieve all the lines from the stack −
do j = 1 to queued()    /* retrieve and display LIFO */ 
pull line 
say line 
end
Since the three items were placed on the stack via push, they are retrieved in the LIFO order.
The output of the above program will be as follows.
STACK: LINE #3 
STACK: LINE #2 
STACK: LINE #1
DirectX - Modeling

Source assets which is required for models stored in Autodesk FBX, Wavefront OBJ or other formats. A typical build process is used for conversion which is used in run-time friendly format which is easy to load and render.
For creating a model, Visual Studio includes a built-in system which includes a convert format of a Wavefront OBJ or Autodesk FBX which is considered as a part of the build process which is needed to CMO.
In this chapter, we will make use of the DirectXMesh meshconvert command line tool. The developer can start this activity by saving cup.obj, cup.mtl and cup.jpg into the project directory.
Following steps are required to implement the modeling −
Download the Meshconvert.exe from the official site and save the executable file into the user’s project folder.
Open the required command prompt and then change the project’s directory. Run the following command executed in below command prompt −
meshconvert cup._obj -cmo -nodds -flipz -y

With this, you can initiate a model creation. Now let us focus on updating effects settings on the mentioned model.
The model class creates the required effects automatically for the loaded materials which are set to lighting parameters. The updating procedure is possible with the Model::UpdateEffects method.
Following are the steps required to update effects settings in a specific model −
From the drop-down menu, select Project/Properties. Set to "All Configurations"/"All Platforms". On the left-hand tree view, select C/C++ Language. Then set "Enable Run-Time Type Information" to "Yes". Click "OK".
In the mentioned file Game.cpp, add the TODO of CreateDevice as shown below −
m_model->UpdateEffects([](IEffect* effect){
   auto lights = dynamic_cast<IEffectLights*>(effect);
   if (lights){
      lights->SetLightingEnabled(true);
      lights->SetPerPixelLighting(true);
      lights->SetLightEnabled(0, true);
      lights->SetLightDiffuseColor(0, Colors::Gold);
      lights->SetLightEnabled(1, false);
      lights->SetLightEnabled(2, false);
   }
   auto fog = dynamic_cast<IEffectFog*>(effect);
   if (fog){
      fog->SetFogEnabled(true);
      fog->SetFogColor(Colors::CornflowerBlue);
      fog->SetFogStart(3.f);
      fog->SetFogEnd(4.f);
   }
});
The above code is designed to build and run our cup with the colored light, per pixel rather than vertex lighting and the fogging was enabled.
 Print
 Add Notes
 Bookmark this page