code-rag-bench/online-tutorials huggingface dataset:
MongoEngine - QuerySet Methods

The QuerySet object possesses following useful methods for querying the database.
First document satisfying the query is returned. Following code will return first document in products collection, that has price < 20000.
qset=products.objects(price__lt=20000)
doc=qset.first()
print ('Name:',doc.Name, 'Price:',doc.price)

Name: Router Price: 2000

This will cause mentioned fields to be excluded from Query Set. Here, to_json() mehod of Document class is used to obtain JSONified version of Document. ProductID field will not appear in the result.
for product in products.objects.exclude('ProductID'):
   print (product.to_json())

{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop", "price": 25000}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "Name": "TV", "price": 50000}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "Name": "Router", "price": 2000}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner", "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer", "price": 12500}

Use this method to manipulate which fields to load in the query set. Use field names as keyword arguments and set to 1 to include, 0 to exclude.
for product in products.objects.fields(ProductID=1,price=1):
print (product.to_json())

{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "price": 25000}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "price": 50000}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "price": 2000}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "price": 12500}

Setting field keyword argument to 0 in fields() method works similar to exclude() method.
for product in products.objects.fields(price=0):
print (product.to_json())

{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "Name": "Laptop"}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "Name": "TV"}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "Name": "Router"}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "Name": "Printer"}

Effect of this method is similar to fields() method. Fields corresponding to keyword arguments only will appear in the query set.
for product in products.objects.only('Name'):
print (product.to_json())

{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop"}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "Name": "TV"}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "Name": "Router"}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer"}

This method computes sum of given field in the query set.
This method calculates average of given field in the query set.
avg=products.objects.average('price')
ttl=products.objects.sum('price')
print ('sum of price field',ttl)
print ('average of price field',avg)

sum of price field 94500
average of price field 18900.0

 Print
 Add Notes
 Bookmark this page
How to reverse a string in Python?

String slicing and range operators can be used to reverse a string in Python. For example:
>>> 'Hello'[::-1]
‘olleH’
>>>‘Halloween’[::-1]
‘neewollaH’
The [] operator can take 3 numbers separated by colon ‘:’. The first is start index, second is end index and third is the stride. Here we have specified the stride as -1 and left other 2 empty, which means we want to go in reverse direction one at a time from beginning to end.
We can also reverse a string using a more readable but slower approach as follows:
>>> ''.join(reversed('Hello'))
‘olleH’
>>> ''.join(reversed('Halloween'))
'neewollaH'
We need to use join as reversed() returns a list and we need to reconstruct string from it.
PHP phar://

The phar:// stream wrapper is available in all PHP versions after 5.3.0. Phar stands for PHP Archive. It is used to distribute PHP application or library and is executed as a normal PHP file. The phar:// wrapper supports opening file with fopen() for read/write, rename, and directory stream operations opendir() as well as create and remove directories.
Phar class allows packaging application resources contained inside a directory in a phar archive. To perform read operations, this archive is put in phar:// wrapper
To begin with, ensure that phar.readonly setting in php.ini is set to 0. Then, create a src folder in which all resources of an application are put. Create index.php file
<?php
echo "phar application started";
?>
Use object of Phar class to build phar archive containing files in src folder with buildFromDirectory() method. Specify index.php as setDefaultStub
<?php
// The php.ini setting phar.readonly must be set to 0
$pharFile = 'app.phar';
// clean up
if (file_exists($pharFile)) {
   unlink($pharFile);
}
if (file_exists($pharFile . '.gz')) {
   unlink($pharFile . '.gz');
}
// create phar
$p = new Phar($pharFile);
// creating our library using whole directory
$p->buildFromDirectory('src/');
// pointing main file which requires all classes
$p->setDefaultStub('index.php', '/index.php');
// plus - compressing it into gzip
$p->compress(Phar::GZ);
echo "$pharFile successfully created";
?>
Run above script from command line
php create-phar.php
This will create app.phar in working directory. To run the phar archive, use following command
php app.phar
<?php
echo file_get_contents('phar://app.phar/index.php');
?>
This will display contents of index.php file
Get the size of an ArrayList in Java

The size of an ArrayList can be obtained by using the java.util.ArrayList.size() method as it returns the number of elements in the ArrayList i.e. the size.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("Apple");
      aList.add("Mango");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Peach");
      System.out.println("The size of the ArrayList is: " + aList.size());
   }
}
The size of the ArrayList is: 5
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.size() returns the size of the ArrayList and that is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add("Apple");
aList.add("Mango");
aList.add("Guava");
aList.add("Orange");
aList.add("Peach");
System.out.println("The size of the ArrayList is: " + aList.size());
Seaborn - Plotting Wide Form Data

It is always preferable to use ‘long-from’ or ‘tidy’ datasets. But at times when we are left with no option rather than to use a ‘wide-form’ dataset, same functions can also be applied to “wide-form” data in a variety of formats, including Pandas Data Frames or two-dimensional NumPy arrays. These objects should be passed directly to the data parameter the x and y variables must be specified as strings
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.boxplot(data = df, orient = "h")
plt.show()

Additionally, these functions accept vectors of Pandas or NumPy objects rather than variables in a DataFrame.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.boxplot(data = df, orient = "h")
plt.show()

The major advantage of using Seaborn for many developers in Python world is because it can take pandas DataFrame object as parameter.

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    11 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
Node.js dns.resolve4() Method - GeeksforGeeks

13 Oct, 2021
The dns.resolve4() method is an inbuilt application programming interface of the dns module which is used to resolve IPv4 address (‘A’ record) for the specified hostname using DNS protocol.
Syntax:
dns.resolve4( hostname, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
hostname: This parameter specifies a string which denotes the hostname to be resolved.
options: It is in the form of an object.ttl: It is a Boolean parameter specifies whether the Time-To-Live value (TTL) for each record to be retrieved or not. If set to true, TTL for each record is retrieved (in seconds).
ttl: It is a Boolean parameter specifies whether the Time-To-Live value (TTL) for each record to be retrieved or not. If set to true, TTL for each record is retrieved (in seconds).
callback: It specifies a function to be called after DNS resolution of the hostname.error: It specifies error if generated.address: It is a string or object that signifies the returned IPv4 address(es) for the hostname.
error: It specifies error if generated.
address: It is a string or object that signifies the returned IPv4 address(es) for the hostname.
Return Value: This method returns error, address through callback function. These data are passed as parameters to the callback function.
Below examples illustrate the use of dns.resolve4() Method in Node.js:
Example 1:
// Node.js program to demonstrate the   // dns.resolve4() method  // Accessing dns moduleconst dns = require('dns');  // Calling dns.resolve4() method for hostname// geeksforgeeks.org and display them in// console as a callbackdns.resolve4('geeksforgeeks.org', (err,    address) => console.log('address: %j', address));
Output:
address: ["34.218.62.116"]

Example 2:
// Node.js program to demonstrate the   // dns.resolve4() method  // Accessing dns moduleconst dns = require('dns');  // Setting options value for// dns.resolve4() methodconst options = {    ttl: true,};  // Calling dns.resolve4() method for hostname// geeksforgeeks.org and displaying them// in console as a callbackdns.resolve4('geeksforgeeks.org', options, (err,    address) => console.log('address: %j', address));
Output:
address: [{"address":"34.218.62.116", "ttl":9}]

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/dns.html#dns_dns_resolve4_hostname_options_callback
Node.js-dns-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to add not null constraint to existing column in MySQL?

To add not null constraint to an existing column in MySQL, we will use the ALTER command. This is a type of validation to restrict the user from entering null values.
Let us see an example. Firstly, we will create a table. The CREATE command is used to create a table.
mysql> create table AddNotNUlldemo
   - > (
   - > name varchar(100)
   - > );
Query OK, 0 rows affected (0.44 sec)
To insert records.
mysql> insert into AddNotNUlldemo values('John');
Query OK, 1 row affected (0.19 sec)

mysql> insert into AddNotNUlldemo values('Bob');
Query OK, 1 row affected (0.19 sec)
To display all the records.
mysql> select *from AddNotNUlldemo;
Here is the output.
+------+
| name |
+------+
| John |
| Bob  |
+------+
2 rows in set (0.00 sec)

The following is the syntax to add a constraint to an existing column.
ALTER table yourTableName  modify column_name data type constraint;

Let us now implement the above syntax to implement the below query. Here, we are including “not null” constraint.
mysql> ALTER table AddNotNUlldemo modify name varchar(100) not null;
Query OK, 0 rows affected (1.14 sec)
Records: 0  Duplicates: 0  Warnings: 0
Now, we cannot insert a null value into the table “AddNotNUlldemo” because we have set the constraint above as “not null”. If we try to add a null value, we will get an error. The following is an example.
mysql> INSERT into AddNotNUlldemo values(null);
ERROR 1048 (23000): Column 'name' cannot be null
To display all the records.
mysql> SELECT *from AddNotNUlldemo;
Here is the output.
+------+
| name |
+------+
| John |
| Bob  |
+------+
2 rows in set (0.00 sec)
Java program to print ASCII value of a particular character

ASCII stands for American Standard Code for Information Interchange. There are 128 standard ASCII codes, each of which can be represented by a 7-digit binary number: 0000000 through 1111111.
If you try to store a character into an integer value it stores the ASCII value of the respective character.
import java.util.Scanner;
public class ASCIIValue {
   public static void main(String args[]){
      System.out.println("Enter a character ::");
      Scanner sc = new Scanner(System.in);
      char ch = sc.next().charAt(0);
      int asciiValue = ch;
      System.out.println("ASCII value of the given character is ::"+asciiValue);
   }
}
Enter a character ::
e
ASCII value of the given character is ::101
How to import External Data from Excel or Text file into SAS Programming? - GeeksforGeeks

14 Dec, 2021
PROC IMPORT: It is a procedure to import external files into SAS. It automates importing process. There is no need to specify the variable type and variable-length to import an external file. It supports various formats of files such as excel, txt, etc.
Importing an Excel File into SAS:
The main keywords used in the following program are:
OUT: To specify name of a data set that SAS creates. In the program below, outdata is the data set saved in work library (temporary library)DBMS: To specify the type of data to import.REPLACE: To overwrite an existing SAS data set.SHEET: To import a specific sheet from an excel workbook.GETNAMES: To include variable names from the first row of data.
OUT: To specify name of a data set that SAS creates. In the program below, outdata is the data set saved in work library (temporary library)
DBMS: To specify the type of data to import.
REPLACE: To overwrite an existing SAS data set.
SHEET: To import a specific sheet from an excel workbook.
GETNAMES: To include variable names from the first row of data.
SQL
PROC IMPORT DATAFILE= "c:\shubh\gfg.xls"OUT= outdataDBMS=xlsREPLACE;SHEET="Sheet1";GETNAMES=YES;RUN
Input:
Output:
Importing a Delimited File with TXT extension:
To get comma separated file with a txt extension into SAS, specify delimiter = ‘, ‘
To get space separated file with a txt extension into SAS, specify delimiter = ‘ ‘
To get tab separated file with a txt extension into SAS, specify delimiter = ’09’x
SQL
PROC IMPORT DATAFILE= "c:\shubh\gfg.txt"OUT= outdataDBMS=dlmREPLACE;delimiter=', ';GETNAMES=YES;RUN;
Input:
Output:
 
saurabh1990aror
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Programming Languages to Learn in 2022
Shallow Copy and Deep Copy in C++
C# | Data Types
Difference between Shallow and Deep copy of a class
Kotlin Array
Advantages and Disadvantages of OOP
Java Swing | JComboBox with examples
Difference between while and do-while loop in C, C++, Java
Prolog | An Introduction
Top 10 Fastest Programming Languages
Display two-digit year in Java

Use the ‘y’ date conversion character to display two-digit year.
System.out.printf("Two-digit Year = %TY\n",d);
Above, d is a date object −
Date d = new Date();
The following is an example −
 Live Demo
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Demo {
   public static void main(String[] args) throws Exception {
      Date d = new Date();
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
      String format = dateFormat.format(d);
      System.out.println("Current date and time = " + format);
      System.out.printf("Four-digit Year = %TY\n",d);
      System.out.printf("Two-digit Year = %ty\n",d);
   }
}
Current date and time = 26/11/2018 12:00:51 PM
Four-digit Year = 2018
Two-digit Year = 18
Variable Declaration and Scope in C - GeeksQuiz

09 Aug, 2019
 x = 1, y = 2, z = 3
 x = 10, y = 20.000000, z = 3
 x = 1, y = 2, z = 100
 x = 1, y = 2, z = 3
 x = 10, y = 20.000000, z = 3
 x = 10, y = 20.000000, z = 100 
 x = 1, y = 2, z = 3
 x = 1, y = 2, z = 3
 x = 1, y = 2, z = 3
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Get Hired With GeeksforGeeks and Win Exciting Rewards!
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
Spring - REST Controller
Java program to reverse each word in a sentence

Each word in a sentence can be reversed and the sentence displayed with the words in the same order as before. An example of this is given as follows −
Original sentence = an apple is red
Modified sentence = na elppa si der
A program that demonstrates this is given as follows.
 Live Demo
public class Example {
public static void main(String[] args) {
String str = "the sky is blue";
System.out.println("The original string is: " + str);
String strWords[] = str.split("\\s");
String rev = "";
for(String sw : strWords) {
StringBuilder sb = new StringBuilder(sw);
sb.reverse();
rev += sb.toString() + " ";
}
System.out.println("The modified string is: " + rev.trim());
}
}
The original string is: the sky is blue
The modified string is: eht yks si eulb
Now let us understand the above program.
First, the original string is displayed. Then split() method is used to store all the words in array strWords[]. The code snippet that demonstrates this is given as follows −
System.out.println("The original string is: " + str);
String strWords[] = str.split("\\s");
The string rev contains all the words after they are reversed. This is done by using the reverse() method in for loop. Then rev is displayed. The code snippet that demonstrates this is given as follows −
String rev = "";
for(String sw : strWords) {
StringBuilder sb = new StringBuilder(sw);
sb.reverse();
rev += sb.toString() + " ";
}
System.out.println("The modified string is: " + rev.trim());
C Program for N-th term of Arithmetic Progression series

Given ‘a’ the First term, ‘d’ the common difference and ‘n’ for the number of terms in a series. The task is to find the nth term of the series.
So, before discussing how to write a program for the problem first we should know what is Arithmetic Progression.
Arithmetic progression or arithmetic sequence is a sequence of number where the difference between the two consecutive terms is same.
Like we have first term i.e a =5, difference 1 and nth term we want to find should be 3. So, the series would be: 5, 6, 7 so the output must be 7.
So, we can say that Arithmetic Progression for nth term will be like −
AP1 = a1
AP2 = a1 + (2-1) * d
AP3 = a1 + (3-1) * d
..APn = a1 + (n-1) *
APn = a1 + (n-1) *
So the formula will be AP = a + (n-1) * d.
Input: a=2, d=1, n=5
Output: 6
Explanation: The series will be:
2, 3, 4, 5, 6 nth term will be 6
Input: a=7, d=2, n=3
Output: 11
Approach we will be using to solve the given problem −
Take first term A, common difference D, and N the number of series.
Then calculate nth term by (A + (N - 1) * D)
Return the Output obtained from the above calculation.
Start
   Step 1 -> In function int nth_ap(int a, int d, int n)
      Return (a + (n - 1) * d)
   Step 2 -> int main()
      Declare and initialize the inputs a=2, d=1, n=5
      Print The result obtained from calling the function nth_ap(a,d,n)
Stop
#include <stdio.h>
int nth_ap(int a, int d, int n) {
   // using formula to find the
   // Nth term t(n) = a(1) + (n-1)*d
   return (a + (n - 1) * d);
}
//main function
int main() {
   // starting number
   int a = 2;
   // Common difference
   int d = 1;
   // N th term to be find
   int n = 5;
   printf("The %dth term of AP :%d\n", n, nth_ap(a,d,n));
   return 0;
}
The 5th term of the series is: 6
C++ New Library - nothrow

This is a nothrow constant and this constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure, but return a null pointer instead.
Following is the declaration for std::nothrow.
		
extern const nothrow_t nothrow;
none
none
No-throw guarantee − this member function never throws exceptions.
none
In below example for std::nothrow.
#include <iostream>
#include <new>

int main () {
   std::cout << "Attempting to allocate...";
   char* p = new (std::nothrow) char [1024*1024];
   if (p==0) std::cout << "Failed!\n";
   else {
      std::cout << "Succeeded!\n";
      delete[] p;
   }
   return 0;
}
The output should be like this −
Attempting to allocate...Succeeded!

 Print
 Add Notes
 Bookmark this page
Enum in Java

The java.lang.Enum class is the common base class of all Java language enumeration types.
Following is the declaration for java.lang.Enum class −
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
This class inherits methods from the following classes −
java.lang.Object
Let us look at an example.
public class Tester{
   public static void main(String args[]) {
      //print an Enum
      System.out.println(Mobile.Motorola);

      Mobile mobile = Mobile.Samsung;
      //Usage in IF statment
      if(mobile == Mobile.Samsung) {
         System.out.println("Matched");
      }
      //Usage in Swith statment
      switch(mobile) {
         case Samsung:
         System.out.println("Samsung");
         break;
         case Nokia:
         System.out.println("Nokia");
         break;
         case Motorola:
         System.out.println("Motorola");
      }
   }
}
enum Mobile {
   Samsung, Nokia, Motorola;
}
This will produce the following result −
Motorola
Matched
Samsung
Program to find the initials of a name in C++

In the program, we are given a string name that denotes the name of a
person. Our task is to create a Program to find the initials of a name in C++.
Code Description − Here, we have to find the initials of the name of the person given by the string.
Let’s take an example to understand the problem,
name = “ram kisan saraswat”
R K S
We will find all the first letters of words of the name.
A simple solution to the problem is by traversing the name string. And all
the characters that appear after the newline character or space character are
the initials and need to be printed in upperCase.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
void findNameInitials(const string& name) {
   cout<<(char)toupper(name[0]);
   for (int i = 0; i < name.length() - 1; i++)
      if(name[i] == ' ' || name[i] == '\n')
   cout << " " << (char)toupper(name[i + 1]);
}
int main() {
   string name = "ram kisan\nsaraswat";
   cout<<"The initials of the name are ";
   findNameInitials(name);
   return 0;
}
The initials of the name are R K S
Tryit Editor v3.7

Tryit: class on headers
Python - Numpy Array Column Deletion - GeeksforGeeks

27 Feb, 2020
Given a numpy array, write a programme to delete columns from numpy array.
Examples –
Input: [['akshat', 'nikhil'], ['manjeeet', 'akash']]
Output:  [['akshat']['manjeeet']]

Input:  [[1, 0, 0, 1, 0], [0, 1, 2, 1, 1]]
Output:  [[1 0 1 0][0 2 1 1]]

 
Given below are various methods to delete columns from numpy array.
Method #1: Using np.delete()
# Python code to demonstrate# deletion of columns from numpy array  import numpy as np  # initialising numpy arrayini_array = np.array([[1, 0, 0, 1, 0],                        [0, 1, 2, 1, 1]])                            # deleting second column from arrayresult = np.delete(ini_array, 1, 1)  # print resultprint ("Resultant Array :"+str(result))
Output:
Resultant Array :[[1 0 1 0]
 [0 2 1 1]]

Method #2: Using compress() and logical_not()
# Python code to demonstrate# deletion of columns from numpy array  import numpy as np  # initialising numpy arrayini_array = np.array([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]])z = [False, True, False, False, False]                            # deleting second column from arrayresult = ini_array.compress(np.logical_not(z), axis = 1)  # print resultprint ("Resultant Array :"+str(result))
Output:
Resultant Array :[[1 0 1 0]
 [1 0 0 1]]

Method #3: Using logical_not()
# Python code to demonstrate# deletion of columns from numpy array  import numpy as np  # initialising numpy arrayini_array = np.array([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]])z = [False, True, False, False, False]                            # deleting second column from arrayresult = ini_array[:, np.logical_not(z)]  # print resultprint ("Resultant Array :"+str(result))
Output:
Resultant Array :[[1 0 1 0]
 [1 0 0 1]]

Python numpy-arrayManipulation
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Tryit Editor v3.6 - Show C++

using namespace std;
​
int main () {
  // Create a text file
  ofstream MyWriteFile("filename.txt");
​
  // Write to the file
  MyWriteFile << "Files can be tricky, but it is fun enough!";
Concatenation of two strings in PHP


PHP offers different kinds of operators having distinctive functionalities. Operators enable us to perform arithmetic activities, string concatenation, compare values and to perform boolean operations, more...In this article, we will learn string operators given by PHP. Let's first learn the types of string operators in php. There are two string operators provided by PHP. 
 1.Concatenation Operator ("."): 
     This operator combines two string values and returns it as a new string.
 2.Concatenating Assignment operator (".="): 
     This operation attaches the argument on the right side to the argument on the left side.
 Let's demonstrate the utility of the above operators by following examples.
<?php
$a = 'Good';
$b = 'Morning';
$c = $a.$b;
echo " $c ";
?>
Goodmorning
Here we have taken two variables aandb s string. Then we have used the Concatenation operator(.) to concatenate those strings into a single string.
<?php
   $a = 'Hello';
   $b = [" Good morning"," Folks"];
   for($i = count($b)-1; $i >= 0;$i--) {
$a .= $b[$i];
}
echo " $a";
?>
Hello Folks Good morning
In this example, we have concatenated string values with array values with the help of the Concatenating Assignment operator (".="). arepresentsastringwhileb represents an array, we have concatenated string awiththevaluesofanarrayb by using a for loop.
The Concatenation Operator ('.') has a similar priority as "+" and " -" operator, which can produce unexpected results.
<?php
$val = 5;
echo "Result: " . $val + 5;
?>
5
The above will print out "5" rather than "Result: 10" since first the string "Result5" is created and then it is added to 5 yielding 5 because the non-empty non-numeric string "Result5 " will be converted to 0 and add with 5 to yield 5. To print "Result: 10", use parentheses to change precedence:
<?php
$var = 5;
echo "Result: " . ($var + 5);
?>
Result:10
New keyword in Java

Yes, it is similar to a new keyword of C++. a new keyword is used to initialize/create an object. See the following example −
Employee employee = new Employee();
Here new keyword is used to create an object of class Employee.
new Employee() invokes the constructor of the class Employee.
new keyword can also be used without assigning the object to a reference variable. See the example −
String name = new Employee().getName();
Here we are creating an object using new keyword and then invoked a method getName() on the object and passed the result to a variable.
HTTP headers | Retry-After

31 Oct, 2019
HTTP headers are used to pass additional information with HTTP request or response. HTTP Retry-After header is an HTTP response header which indicates how long to wait before making another request. Depending on different status codes, there are different use cases of the Retry-After response header.
Status code 503: 503 is used to indicate service unavailable. Retry-After is used with 503 which tells the user how long the service is expected to be unavailable. It is used to deal with scheduled downtime.
Status code 301: 301 is used to indicate that resource is moved permanently. Retry-After is used with 301 which tells the user about the minimum for which user should wait before issuing the redirect request.
Status code 429: 429 id is used to indicate too many request. Retry-After is used with 429 to tells the user how long to wait before making another request.
Syntax:
Retry-After: <http-date>
Retry-After: <delay-seconds>

Directives: This header accepts two directives as mentioned above and described below:
http-date: It indicated the date after which used should resend the request.
delay-seconds: It is an integer value indicating the no of seconds after which user should resend the request.
Example: This example will illustrates the HTTP Retry-After header:
Using date directive, after that date with the specified time client can retry the request.Retry-After: Sun, 27 Oct 2019 09:45:00 GMT
Retry-After: Sun, 27 Oct 2019 09:45:00 GMT
Using delay-second directive, after that specified second client can retry the request.Retry-After: 180
Retry-After: 180
Supported Browsers: The browsers compatible with HTTP Retry-After header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
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
How to fetch data from an API in ReactJS ?
Roadmap to Learn JavaScript For Beginners
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
REST API (Introduction)
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners
Moment.js isLeapYear() Function

29 Jul, 2020
It is used to check whether the given year is Leap Year or not in Moment.js using the isLeapYear() function that returns true if that year is a leap year, and false if it is not.
Syntax:
moment().isLeapYear();

Parameter: No parameters required.
Returns: True or False
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
// Requiring moduleconst moment = require('moment');  var bool1 = moment([2000]).isLeapYear() // trueconsole.log(bool1);
Steps to run the program:
The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:true

The project structure will look like this:
Make sure you have installed moment module using the following command:npm install moment
npm install moment
Run index.js file using below command:node index.jsOutput:true

node index.js
Output:
true

Example 2: Filename: index.js
// Requiring moduleconst moment = require('moment');  function checkLeapYear(year){   return moment([year]).isLeapYear();}  var bool = checkLeapYear(2001)console.log(bool);
Run index.js file using below command:
node index.js
Output:
false

Reference: https://momentjs.com/docs/#/query/is-leap-year/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Responsive Video or Slideshow Embeds in Bootstrap with Examples

24 Jan, 2019
Bootstrap allows creating responsive video or slideshow embeds based on the width of the display or parent element by creating a native ratio that scales with the device. Using responsive video or slideshow embeds the content can be scaled automatically as per the screen size or the parent container element, this makes the UI more responsive.
Bootstrap provides a class named embed-responsive for creating responsive embeds. This class is assigned to the parent which encloses any of the following embedding elements: <iframe>, <embed>, <video>, and <object>.
Optionally, along with the embed-responsive class, one more class embed-responsive-item can be used with the embedding elements.
Bootstrap also provides a few modifier classes to adjust the aspect ratio of the elements:
embed-responsive-16by9
embed-responsive-21by9
embed-responsive-1by1
embed-responsive-4by3
Below program illustrate the embed-responsive class:
<!DOCTYPE html><html><head>    <!-- Link Bootstrap CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">          <title>        Responsive Video    </title></head>  <body>    <div class="embed-responsive                 embed-responsive-21by9">        <iframe class="embed-responsive-item"                 src="https://www.youtube.com/embed/HMAwoMt3kek"                 allowfullscreen>        </iframe>    </div></body></html>                    
Output:
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – K length decimal Places

05 Sep, 2020
Given a Decimal Number, extent its digits to K length.
Input : num = 76.8, K = 5Output : 76.80000Explanation : Length of decimal places is 5.
Input : num = 76.8, K = 6Output : 76.800000Explanation : Length of decimal places is 6.
Method : Using format() 
This is way in which this task can be done. In this, we harness multiple format compatibilites to perform task of getting appropriate length of decimal places.
Python3
# Python3 code to demonstrate working of # K length decimal Places# Using format()  # initializing number num = 76.8  # printing original number print("The original number is : " + str(num))  # initializing K K = 7  # using format to solve this problemres = "{{:.{}f}}".format(K).format(num)  # printing result print("The resultant number : " + str(res))
The original number is : 76.8
The resultant number : 76.8000000

Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select only direct children from element with Sass?

02 Nov, 2020
Introduction:Sass is a scripting language that is compiled into Cascading style sheets (CSS). It is a kind of preprocessor language. It was initially designed by Hampton Catlin and then it was developed by Natalie Weizenbaum. After its initial versions, Weizenbaum and Chris Eppstein have continued to extend SASS with SassScript. It supports four data types and they are Numbers, Strings, Colors, and booleans. Nesting also works in this language.
Approach regarding the question:
First defined the content in a .html file.
In the HTML file in your content make sure that you are placing child tags or having child tags inside a parent tag.
Once you are done with the HTML tag then use ” & ” and ” > ” in the SCSS file to style the direct children.
Implementation By code:
app.component.html:
<h1>Welcome to My GeeksForGeeks</h1>  <div>  <p>One Stop solution for all the    Computer Science Concepts </p></div>  <div>  <span><p>It is reliable and rich    website for students.</p></span></div>  <p>It even has interview experiences which gives insights regarding every company interview</p>
app.component.scss:
div {    & > p {       background-color: yellow;    }}
app.module.ts:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';  import { AppComponent } from './app.component';    @NgModule({  imports:      [ BrowserModule, FormsModule ],  declarations: [ AppComponent],  bootstrap:    [ AppComponent ]})export class AppModule { }
Output:
If you clearly observe the above screenshot as the background color is applied only to the direct children.
SASS
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
OOP Concepts - GeeksforGeeks

11 Sep, 2014
Class P
{
    void f(int i)
    {
        print(i);
    }
}

Class Q subclass of P
{
    void f(int i)
    {
        print(2*i);
    }
}

P x = new Q();
Q y = new Q();
P z = new Q();
x.f(1); ((P)y).f(1); z.f(1); 
A publicly derived class is a subtype of its base class.
Inheritance provides for code reuse.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
HTML hidden Attribute

02 Jun, 2022
The hidden attribute in HTML is used to define the visibility of elements. It contains a boolean value. It is a semantic indicator of state in HTML code. If this attribute is used then browsers will not display elements that have the hidden attribute specified. The hidden attribute can be seen using some condition or JavaScript used to see the hidden content. This attribute can be beneficial to use in order to keep hiding the content or element to render it from the users, until some other condition is to be met such as selecting a checkbox, etc.
Syntax:
<element hidden>
Note: This attribute is new in HTML 5.
Supported Tags: This is a Global attribute, and can be used on any HTML element.
Example 1: This simple example illustrates hiding the content from the user by using the hidden attribute with the <div> element in HTML.
HTML
<!DOCTYPE html><html><head>    <title>hidden attribute</title></head> <body>    <h1>GeeksforGeeks</h1>    <h2>HTML hidden attribute</h2>         <!-- hidden paragraph -->    <div hidden>      This content will be hidden while      displaying the content    </div>    <h4>A computer science portal for geeks</h4></body></html>
Output:
HTML hidden Attribute
Example 2: In this example, we have used the hidden attribute that will hide the content while rendering it to the browser. 
HTML
<!DOCTYPE html><html><head>    <title>HTML hidden attribute</title></head> <body>    <h1>GeeksforGeeks</h1>    <h2>HTML hidden attribute</h2>         <!-- hidden paragraph -->    <p hidden>        We provide a variety of        services for you to learn,        thrive and also have fun!    </p>      <p>       Free Tutorials, Millions of       Articles, Live, Online and       Classroom Courses    </p>   </body></html>
 Output:
HTML hidden Attribute
Supported Browsers:
Google Chrome 
Internet Explorer 11.0 and above
Microsoft Edge 12 and above
Firefox 
Opera 
Safari 
ManasChhabra2
bhaskargeeksforgeeks
kumargaurav97520
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
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 ?
Difference between Token based and Non-Token based Algorithms in Distributed System

21 Jun, 2022
A distributed system is a system in which components are situated in distinct places, these distinct places refer to networked computers which can easily communicate and coordinate their tasks by just exchanging asynchronous messages with each other. These components can communicate with each other to conquer one common goal as a task. There are many algorithms are used to achieve Mutual Exclusion ,where there are multiple processes(or sites) requesting access for a single shared resource(often called as Critical Section)  ,and these are broadly divided into 2 categories: Token-Based Algorithms and Non-Token Based Algorithms. Difference between Token based and Non-Token based Algorithms in Distributed System:
Examples of Token-Based Algorithms are:
(i) Singhal’s Heuristic Algorithm
(ii) Raymonds Tree Based Algorithm
(iii) Suzuki-Kasami Algorithm    
Examples of Non-Token Based Algorithms are:
(i) Lamport’s Algorithm
(ii) Ricart-Agarwala Algorithm
(iii) Maekawa’s Algorithm 
mohansaitejat
Distributed System
Difference Between
Operating Systems
Operating Systems
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
map vs unordered_map in C++
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
Python | Pandas Series.to_numpy()

27 Feb, 2019
Pandas Series.to_numpy() function is used to return a NumPy ndarray representing the values in given Series or Index.
This function will explain how we can convert the pandas Series to numpy Array. Although it’s very simple, but the concept behind this technique is very unique. Because we know the Series having index in the output. Whereas in numpy arrays we only have elements in the numpy arrays.
Syntax: Series.to_numpy()
Parameters:dtype: Data type which we are passing like str.copy : [bool, default False] Ensures that the returned value is a not a view on another array.
To get the link to csv file, click on nba.csv
Code #1 :
Changing the Series into numpy array by using a method Series.to_numpy(). Always remember that when dealing with lot of data you should clean the data first to get the high accuracy. Although in this code we use the first five values of Weight column by using .head() method.
# importing pandasimport pandas as pd   # reading the csv  data = pd.read_csv("nba.csv")      data.dropna(inplace = True)  # creating series form weight columngfg = pd.Series(data['Weight'].head())  # using to_numpy() functionprint(type(gfg.to_numpy()))
Output :
[180. 235. 185. 235. 238.]

 Code #2 :In this code we are just giving the parameters in the same code. So we provide the dtype here.
# importing pandasimport pandas as pd   # read csv file  data = pd.read_csv("nba.csv")      data.dropna(inplace = True)  # creating series form weight columngfg = pd.Series(data['Weight'].head())  # providing dtypeprint(gfg.to_numpy(dtype ='float32'))
Output :
[180. 235. 185. 235. 238.]

 Code #3 : Validating the type of the array after conversion.
# importing pandas import pandas as pd   # reading csv  data = pd.read_csv("nba.csv")      data.dropna(inplace = True)  # creating series form weight columngfg = pd.Series(data['Weight'].head())  # using to_numpy()print(type(gfg.to_numpy()))
Output :
<class 'numpy.ndarray'>

Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tensorflow.js tf.reshape() Function

21 Jun, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or Node.js.
The tf.reshape() function is used to reshape a given tensor with the specified shape.
Syntax:
tf.reshape(x, shape)
Parameters: This function has the following parameters:
x: It is the input tensor that needs to be shaped.
shape: We need to pass array of numbers to define the output shape.
Return Value: It returns a tf.Tensor.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  const x = tf.tensor1d([10, 15, 16, 24]);  // Print the tensorx.reshape([2, 2]).print();
Output:
Tensor
    [[10, 15],
     [16, 24]]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Using 2dconst x = tf.tensor2d(  [1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]);x.reshape([3, 3]).print();  // Using 3dconst y = tf.tensor3d(  [[[1], [2]], [[3], [4]]]);y.reshape([2, 2]).print();  // Using 4dconst z = tf.tensor4d(  [11, 12, 13, 14], [1, 2, 2, 1]);z.reshape([2, 2]).print();
Output:
Tensor
    [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
Tensor
    [[1, 2],
     [3, 4]]
Tensor
    [[11, 12],
     [13, 14]]
Reference: https://js.tensorflow.org/api/latest/#reshape
Picked
Tensorflow.js
JavaScript
Web Technologies
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 ?
Python – Setting up the Bokeh Environment

22 Jun, 2020
Bokeh is supported on CPython versions 3.6+ only both with Standard distribution and Anaconda distribution. Other Python versions or implementations may or may not function. Current version of Bokeh is 2.0.2 . Bokeh package has the following dependencies:
1. Required Dependencies
PyYAML>=3.10
python-dateutil>=2.1
Jinja2>=2.7
numpy>=1.11.3
pillow>=4.0
packaging>=16.8
tornado>=5
typing_extensions >=3.7.4
2. Optional Dependencies
Jupyter
NodeJS
NetworkX
Pandas
psutil
Selenium, GeckoDriver, Firefox
Sphinx
There are a few different ways to install Bokeh. If you are using Anaconda distribution, use conda package manager as follows ?
conda install bokeh

This installs all the dependencies that are need to be run Bokeh. If all the above said dependencies such as NumPy, Pandas, and Redis are installed, then you can install the bokeh package from PyPI using pip at the command line:
pip install bokeh

To check whether the Bokeh is successfully installed, do the following:
Import bokeh package in Python terminal
Check the bokeh version
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Taking input in Python
Read a file line by line in Python
Python String | replace()