code-rag-bench/online-tutorials huggingface dataset:
Out of memory exception in Java:


Whenever you create an object in Java it is stored in the heap area of the JVM. If the JVM is not able to allocate memory for the newly created objects an exception named OutOfMemoryError is thrown.
This usually occurs when we are not closing objects for long time or, trying to act huge amount of data at once.
There are 3 types of errors in OutOfMemoryError −
Java heap space.
GC Overhead limit exceeded.
Permgen space.
 Live Demo
public class SpaceErrorExample {
   public static void main(String args[]) throws Exception {
      Float[] array = new Float[10000 * 100000];
   }
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
   at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)
 Live Demo
import java.util.ArrayList;
import java.util.ListIterator;
public class OutOfMemoryExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      while(it.hasNext()) {
         it.add("");
      }
   }
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
   at sample.SpaceErrorExample.main(SpaceErrorExample.java:7)
Add delay in Arduino

In order to add time delays in Arduino, you can use the delay() function. It takes as an argument the value of the delay in milliseconds. An example execution is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
}
void loop() {
   // put your main code here, to run repeatedly:
   Serial.print("Hello!");
   delay(2000);
}
The above code prints "Hello!" every 2 seconds. As you may have guessed, the minimum delay you can introduce using the delay function is 1 milli-second. What if you want an even shorted delay? Arduino has a delayMicroseconds() function for that, which takes in the value of the delay in microseconds as the argument.
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
}
void loop() {
   // put your main code here, to run repeatedly:
   Serial.print("Hello!");
   delayMicroseconds(2000);
}
The above code prints "Hello!" every 2 milliseconds (2000 microseconds).
Can we use stored procedure to insert records into two tables at once in MySQL?

Yes, you can use stored procedure to insert into two tables in a single query. Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20)
);
Query OK, 0 rows affected (0.56 sec)
Here is the query to create second table −
mysql> create table DemoTable2
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(20),
   ClientAge int
);
Query OK, 0 rows affected (0.76 sec)
Following is the query to create stored procedure to insert into two tables created above −
mysql> DELIMITER //
   mysql> CREATE PROCEDURE insert_into_twoTables(name varchar(100),age int)
      BEGIN
         INSERT INTO DemoTable(StudentFirstName) VALUES(name);
         INSERT INTO DemoTable2(ClientName,ClientAge) VALUES(name,age);
      END
      //
   Query OK, 0 rows affected (0.14 sec)
mysql> DELIMITER ;
Now call the stored procedure with the help of CALL command −
mysql> call insert_into_twoTables('Tom',38);
Query OK, 1 row affected, 1 warning (0.41 sec)
Check the record is inserted into both tables or not.
The query to display all records from the first table is as follows −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
| 1         | Tom              |
+-----------+------------------+
1 row in set (0.00 sec)
Following is the query to display all records from the second table −
mysql> select *from DemoTable2;
This will produce the following output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
| 1        | Tom        | 38        |
+----------+------------+-----------+
1 row in set (0.00 sec)
How to use InputFilter to limit characters in an editText in Android?

This example demonstrates how do I use inputfilter to limit characters in an editText in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="40dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   EditText editText;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      editText = findViewById(R.id.editText);
      int maxTextLength = 15;
      editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxTextLength)});
      Toast.makeText(this, "EditText limit set to 15 characters", Toast.LENGTH_SHORT).show();
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
PHP strlen() Function - GeeksforGeeks

01 Dec, 2021
In this article, we will see how to get the length of the string using strlen() function in PHP, along with understanding its implementation through the examples.
The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters. 
Syntax:
strlen($string);
Parameters: The strlen() function accepts only one parameter $string which is mandatory. This parameter represents the string whose length is needed to be returned. 
Return Value: The function returns the length of the $string including all the whitespaces and special characters. 
Below programs illustrate the strlen() function in PHP:
Example 1: The below example demonstrates the use of the strlen() function in PHP.
PHP
<?php     // PHP program to find the    // length of a given string    $str = "GeeksforGeeks";         // prints the length of the string    // including the space    echo strlen($str);?>
Output:
13
Example 2: This example demonstrates the use of the strlen() function where the string has special characters and escape sequences.
PHP
<?php     // PHP program to find the    // length of a given string which has    // special characters    $str = "\n GeeksforGeeks Learning;";         // here '\n' has been counted as 1    echo strlen($str);?>
Output:
25
Reference: http://php.net/manual/en/function.strlen.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Akanksha_Rai
bhaskargeeksforgeeks
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Column Chart with negative values

Following is an example of a Column Chart with negative values.
We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic column chart with negative values.
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart: {
         type: 'column'
      },
      title: {
         text: 'Column chart with negative values'
      },
      xAxis:{
         categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']        
      },     
      series: [
         {
            name: 'John',
            data: [5, 3, 4, 7, 2]
         }, 
         {
            name: 'Jane',
            data: [2, -2, -3, 2, 1]
         }, {
            name: 'Joe',
            data: [3, 4, 4, -2, 5]
         }
      ]
   };
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to convert byte array to an object stream in C#?

Stream is the abstract base class of all streams and it Provides a generic view of a sequence of bytes. The Streams Object involve three fundamental operations such as Reading, Writing and Seeking. A stream be can be reset which leads to performance improvements.
A byte array can be converted to a memory stream using MemoryStream Class.
MemoryStream stream = new MemoryStream(byteArray);
Let us consider a byte array with 5 values 1, 2, 3, 4, 5.
 Live Demo
using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         byte[] byteArray = new byte[5] {1, 2, 3, 4, 5 };
         using (MemoryStream stream = new MemoryStream(byteArray)) {
            using (BinaryReader reader = new BinaryReader(stream)) {
               for (int i = 0; i < byteArray.Length; i++) {
                  byte result = reader.ReadByte();
                  Console.WriteLine(result);
               }
            }
         }
         Console.ReadLine();
      }
   }
}
The output of the above code is
1
2
3
4
5
Lodash _.merge() Method - GeeksforGeeks

13 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.merge() method is used to merge two or more objects starting with the left-most to the right-most to create a parent mapping object. When two keys are the same, the generated object will have value for the rightmost key. If more than one object is the same, the newly generated object will have only one key and value corresponding to those objects.
Syntax:
_.merge( object, sources )

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the destination object.
sources: This parameter holds the source object. It is an optional parameter.
Return Value: This method returns the merged object.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Using the _.merge() method console.log(  _.merge({ cpp: "12" }, { java: "23" },          { python:"35" }) );  // When two keys are the sameconsole.log(  _.merge({ cpp: "12" }, { cpp: "23" },          { java: "23" }, { python:"35" }));  // When more than one object is the sameconsole.log(  _.merge({ cpp: "12" }, { cpp: "12" },          { java: "23" }, { python:"35" }));
Output:
{cpp: '12', java: '23', python: '35'}
{cpp: '23', java: '23', python: '35'}
{cpp: '12', java: '23', python: '35'}

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The destination objectvar object = {  'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]};  // The source objectvar other = {  'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]};  // Using the _.merge() methodconsole.log(_.merge(object, other));
Output:
{ 'amit': [{'chinmoy': 30, 'susanta': 20 }, 
{ 'durgam': 40, 'kripamoy': 50 }] }

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
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
How to insert spaces/tabs in text using HTML/CSS?
How to parse a JSON string using Streaming API in Java?

The Streaming API consists of an important interface JsonParser and this interface contains methods to parse JSON in a streaming way and provides forward, read-only access to JSON data. The Json class contains the methods to create parsers from input sources. We can parse a JSON using the static method createParser() of Json class.
public static JsonParser createParser(Reader reader)
import java.io.*;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

public class JSONParseringTest {
   public static void main(String[] args) {
      String jsonString = "{\"name\":\"Adithya\",\"employeeId\":\"115\",\"age\":\"30\"}";
      JsonParser parser = Json.createParser(new StringReader(jsonString));
      while(parser.hasNext()) {
         Event event = parser.next();
         if(event == Event.KEY_NAME) {
            switch(parser.getString()) {
               case "name":
                  parser.next();
                  System.out.println("Name: " + parser.getString());
                  break;
               case "employeeId":
                  parser.next();
                  System.out.println("EmployeeId: " + parser.getString());
                  break;
               case "age":
                  parser.next();
                  System.out.println("Age: " + parser.getString());
                  break;
            }
         }
      }
   }  
}
Name: Adithya
EmployeeId: 115
Age: 30
Python | Ways to sort letters of string alphabetically - GeeksforGeeks

11 May, 2020
Given a string of letters, write a python program to sort the given string in an alphabetical order.
Examples:
Input : PYTHON
Output : HNOPTY

Input : Geeks
Output : eeGks

Method #1 : Using sorted() with join()
# Python3 program to sort letters # of string alphabetically  def sortString(str):    return ''.join(sorted(str))      # Driver codestr = 'PYTHON'print(sortString(str))
HNOPTY

 Method #2 : Using sorted() with accumulate()
# Python3 program to sort letters # of string alphabeticallyfrom itertools import accumulate  def sortString(str):    return tuple(accumulate(sorted(str)))[-1]      # Driver codestr = 'PYTHON'print(sortString(str))
HNOPTY

 Method #3 : Using sorted() with reduce()
Another alternative is to use reduce() method. It applies a join function on the sorted list using ‘+’ operator.
# Python3 program to sort letters # of string alphabeticallyfrom functools import reduce  def sortString(str):    return reduce(lambda a, b : a + b, sorted(str))      # Driver codestr = 'PYTHON'print(sortString(str))
HNOPTY

Using sorted() with join()
# Python3 program to sort letters # of string alphabeticallyfrom itertools import accumulate  def sortString(str):    return "".join(sorted(str, key = lambda x:x.lower()))      # Driver codestr = 'Geeks'print(sortString(str))
eeGks

Python-sort
Python-string-functions
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
HTML | <td> nowrap Attribute - GeeksforGeeks

31 Oct, 2019
The HTML <td> nowrap Attribute is used to specify that the content present inside the cell should not wrap. It contains the Boolean value. It is not supported by HTML 5.
Syntax:
<td nowrap>
Example:
<!DOCTYPE html><html>  <head>    <title>HTML nowrap Attribute</title>    <style>        table,        th,        td {            border: 1px solid black;            border-collapse: collapse;            padding: 6px;        }    </style></head>  <body style="text-align:center">      <h1 style="color: green;">GeeksforGeeks</h1>    <h2>HTML <td>nowrap Attribute</h2>    <center>        <table>            <tr>                <th>Name</th>                <th>Age</th>            </tr>            <tr>                <td nowrap>Ajay</td>                <!-- This cell will take up space on                     two rows -->                <td rowspan="2">24</td>            </tr>            <tr>                <td>Priya</td>            </tr>        </table>    </center>  </body>  </html>
Output:
Supported Browsers: The browsers supported by HTML <td> nowrap Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to check if a C/C++ string is an int?

There are several methods to check that string is an int or not and one of those method is to use isdigit() to check the string.
Here is an example to check whether a string is an int or not in C++ language,
 Live Demo
#include<iostream>
#include<string.h>

using namespace std;
int main() {
   char str[] = "3257fg";

   for (int i = 0; i < strlen(str); i++) {
      if(isdigit(str[i]))
      cout<<"The string contains int\n";
      else
      cout<<"The string does not contain int\n";
   }
   return 0;
}
Here is the output
The string contains int
The string contains int
The string contains int
The string contains int
The string does not contain int
The string does not contain int
In the above program, the actual code of checking the string is present in main() function. Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
for (int i = 0; i < strlen(str); i++) {
   if(isdigit(str[i]))
   printf("The string contains int\n");
   else
   printf("The string does not contain int\n");
}
Perform SUM and SUBTRACTION on the basis of a condition in a single MySQL query?

For this, use CASE statement and set for both SUM and SUBTRACTION. Let us first create a table −
mysql> create table DemoTable866(
   Status varchar(100),
   Amount int
);
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable866 values('ACTIVE',50);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable866 values('INACTIVE',70);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable866 values('INACTIVE',20);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable866 values('ACTIVE',100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable866 values('ACTIVE',200);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable866;
This will produce the following output −
+----------+--------+
| Status   | Amount |
+----------+--------+
| ACTIVE   | 50     |
| INACTIVE | 70     |
| INACTIVE | 20     |
| ACTIVE   | 100    |
| ACTIVE   | 200    |
+----------+--------+
5 rows in set (0.00 sec)
Following is the query to perform SUM or SUBTRACTION in the same column with a single MySQL query −
mysql> select sum(CASE WHEN Status = 'ACTIVE' then Amount
   WHEN Status = 'INACTIVE' then -Amount
   END) AS RemainingAmount
   from DemoTable866;
This will produce the following output −
+-----------------+
| RemainingAmount |
+-----------------+
| 260             |
+-----------------+
1 row in set (0.06 sec)
VBA - Day Function

The Day function returns a number between 1 and 31 that represents the day of the specified date.
Day(date) 

Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox(Day("2013-06-30"))
End Sub
When you execute the above function, it produces the following output.
30


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
C++ program to implement Full Adder - GeeksforGeeks

19 Aug, 2021
Prerequisite : Full AdderWe are given three inputs of Full Adder A, B,C-IN. The task is to implement the Full Adder circuit and Print output i.e. sum and C-Out of three inputs.
Introduction : A Full Adder is a combinational circuit that performs an addition operation on three 1-bit binary numbers. The Full Adder has three input states and two output states. The two outputs are Sum and Carry.
Here we have three inputs A, B, Cin and two outputs Sum, Cout. And the truth table for Full Adder is 
Logical Expression :
SUM  =  C-IN  XOR  ( A XOR B )C-0UT= A B + B C-IN + A C-IN
Examples –
       Input :   A=1, B=0,C-In=0       Output : Sum=1, C-Out=0       Explanation –        Here from logical expression Sum= C-IN XOR (A XOR B )  i.e. 0 XOR (1 XOR 0) =1 , C-Out= A B + B C-IN + A C-IN              i.e.,  1 AND 0 + 0 AND 0 + 1 AND 0 = 0 .      Input :    A=1, B=1,C-In=0     Output:  Sum=0, C-Out=1
       Input :   A=1, B=0,C-In=0       Output : Sum=1, C-Out=0       Explanation –        Here from logical expression Sum= C-IN XOR (A XOR B )  i.e. 0 XOR (1 XOR 0) =1 , C-Out= A B + B C-IN + A C-IN              i.e.,  1 AND 0 + 0 AND 0 + 1 AND 0 = 0 . 
     Input :    A=1, B=1,C-In=0     Output:  Sum=0, C-Out=1
Approach :
Initialize the variables Sum and C_Out for storing outputs.
First we will take three inputs A ,B and C_In.
By applying  C-IN XOR (A XOR B ) we get the value of Sum.
By applying   A B + B C-IN + A C-IN we get the value of C_Out.
C++
// C++ program to implement full adder#include <bits/stdc++.h>using namespace std;// Function to print sum and C-Outvoid Full_Adder(int A,int B,int C_In){    int Sum , C_Out;    // Calculating value of sum    Sum = C_In ^ (A ^ B);        //Calculating value of C-Out    C_Out = (A & B) || (B & C_In) || (A & C_In);      // printing the values    cout<<"Sum = "<<Sum<<endl;    cout<<"C-Out = "<<C_Out<<endl;  }   // Driver code  int main() {    int A = 1;    int B = 0;    int C_In = 0;    // passing three inputs of fulladder as arguments to get result function    Full_Adder(A, B, C_In);    return 0;}
Sum = 1
C-Out = 0
C++ Programs
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
cin in C++
CSV file management using C++
Shallow Copy and Deep Copy in C++
Passing a function as a parameter in C++
C Program to Swap two Numbers
Program for Decimal to Binary Conversion
Full Adder in Digital Logic
Introduction of K-Map (Karnaugh Map)
IEEE Standard 754 Floating Point Numbers
Program for Binary To Decimal Conversion
Tryit Editor v3.7

CSS 2D Transforms
Tryit: The skew() method
C++ Pointers

You learned from the previous chapter, that we can get the memory 
address of a variable by using the & 
operator:
A pointer however, is a variable that stores the memory address as its value. 
A pointer variable points to a data type (like int or string) of the same 
type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:
Create a pointer variable with the name ptr, that points to a string variable, by using the 
asterisk sign 
* (string* ptr). 
Note that the type of the pointer has to match the type of the variable you're 
working with.
Use the & operator to store the memory address of the 
variable called food, and assign it to the pointer.
Now, ptr holds the value of food's memory address.
Tip: There are three ways to declare pointer variables, but the first way is preferred:
Create a pointer variable with the name ptr, that should point to a string variable named food:
string food = "Pizza";
  = &;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Querying the number of distinct colors in a subtree of a colored tree using BIT in C++

In this tutorial, we will be discussing a program to find querying the number of distinct colors in a subtree of a colored tree using BIT.
For this we will be provided with rooted tree where each node has a color denoted by given array. Our task is to find all the distinct coloured nodes below the given node in the tree.
 Live Demo
#include<bits/stdc++.h>
#define MAXIMUM_COLOUR 1000005
#define MAXIMUM_NUMBER 100005
using namespace std;
vector<int> tree[MAXIMUM_NUMBER];
vector<int> table[MAXIMUM_COLOUR];
int isTraversing[MAXIMUM_COLOUR];
int bit[MAXIMUM_NUMBER], getVisTime[MAXIMUM_NUMBER],
getEndTime[MAXIMUM_NUMBER];
int getFlatTree[2 * MAXIMUM_NUMBER];
bool vis[MAXIMUM_NUMBER];
int tim = 0;
vector< pair< pair<int, int>, int> > queries;
//storing results of each queryingTree
int ans[MAXIMUM_NUMBER];
void update(int idx, int val) {
   while ( idx < MAXIMUM_NUMBER ) {
      bit[idx] += val;
      idx += idx & -idx;
   }
}
int queryingTree(int idx) {
   int result = 0;
   while ( idx > 0 ) {
      result += bit[idx];
      idx -= idx & -idx;
   }
   return result;
}
void preformingDFS(int v, int color[]) {
   //marking the node visited
   vis[v] = 1;
   getVisTime[v] = ++tim;
   getFlatTree[tim] = color[v];
   vector<int>::iterator it;
   for (it=tree[v].begin(); it!=tree[v].end(); it++)
      if (!vis[*it])
         preformingDFS(*it, color);
   getEndTime[v] = ++tim;
   getFlatTree[tim] = color[v];
}
//adding an edge to the tree
void addingNewEdge(int u, int v) {
   tree[u].push_back(v);
   tree[v].push_back(u);
}
void markingFirstFind(int n) {
   for (int i = 1 ; i <= 2 * n ; i++) {
      table[getFlatTree[i]].push_back(i);
      if (table[getFlatTree[i]].size() == 1) {
         update(i, 1);
         isTraversing[getFlatTree[i]]++;
      }
   }
}
void calcQuery() {
   int j = 1;
   for (int i=0; i<queries.size(); i++) {
      for ( ; j < queries[i].first.first ; j++ ) {
         int elem = getFlatTree[j];
         update( table[elem][isTraversing[elem] - 1], -1);
         if ( isTraversing[elem] < table[elem].size() ){
            update(table[elem][ isTraversing[elem] ], 1);
            isTraversing[elem]++;
         }
      }
      ans[queries[i].second] = queryingTree(queries[i].first.second);
   }
}
//counting distinct color nodes
void calcAllColours(int color[], int n, int qVer[], int qn) {
   preformingDFS(1, color);
   for (int i=0; i<qn; i++)
      queries.push_back(make_pair(make_pair(getVisTime[qVer[i]] , getEndTime[qVer[i]]), i) );
   sort(queries.begin(), queries.end());
   markingFirstFind(n);
   calcQuery();
   for (int i=0; i<queries.size() ; i++) {
      cout << "All distinct colours in the given tree: " << ans[i] << endl;
   }
}
int main() {
   int number = 6;
   int color[] = {0, 2, 3, 3, 4, 1};
   addingNewEdge(1, 2);
   addingNewEdge(1, 3);
   addingNewEdge(2, 4);
   int queryVertices[] = {3, 2};
   int qn = sizeof(queryVertices)/sizeof(queryVertices[0]);
   calcAllColours(color, number, queryVertices, qn);
   return 0;
}
All distinct colours in the given tree: 1
All distinct colours in the given tree: 2
Check If the Rune is a Letter or not in Golang - GeeksforGeeks

27 Sep, 2019
Rune is a superset of ASCII or it is an alias of int32. It holds all the characters available in the world’s writing system, including accents and other diacritical marks, control codes like tab and carriage return, and assigns each one a standard number. This standard number is known as a Unicode code point or rune in the Go language.You are allowed to check the given rune is a letter or not with the help of IsLetter() function. This function returns true if the given rune is a letter, or return false if the given rune is not a letter. This function is defined under Unicode package, so for accessing this method you need to import the Unicode package in your program.
Syntax:
func IsLetter(r rune) bool
The return type of this function is boolean. Let us discuss this concept with the help of given examples:
Example 1:
// Go program to illustrate how to// check the given rune is a letterpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating rune    rune_1 := 'g'    rune_2 := 'e'    rune_3 := '1'    rune_4 := '4'    rune_5 := 'S'      // Checking the given rune     // is a letter or not    // Using IsLetter() function    res_1 := unicode.IsLetter(rune_1)    res_2 := unicode.IsLetter(rune_2)    res_3 := unicode.IsLetter(rune_3)    res_4 := unicode.IsLetter(rune_4)    res_5 := unicode.IsLetter(rune_5)      // Displaying results    fmt.Println(res_1)    fmt.Println(res_2)    fmt.Println(res_3)    fmt.Println(res_4)    fmt.Println(res_5)  }
Output:
true
true
false
false
true

Example 2:
// Go program to illustrate how to// check the given rune is a letterpackage main  import (    "fmt"    "unicode")  // Main functionfunc main() {      // Creating a slice of rune    val := []rune{'g', 'E', '3', 'K', '1'}      // Checking each element of the given     // slice of the rune is a letter or not    // Using IsLetter() function    for i := 0; i < len(val); i++ {          if unicode.IsLetter(val[i]) == true {              fmt.Println("It is a letter")                      } else {                      fmt.Println("It is not a letter")        }    }}
Output:
It is a letter
It is a letter
It is not a letter
It is a letter
It is not a letter

Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
Slices in Golang
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
Interfaces in Golang
Pointers in Golang
C program to print odd line contents of a File followed by even line content - GeeksforGeeks

08 Jul, 2020
Pre-requisite: Basics of File Handling in C
Given a text file in a directory, the task is to print all the odd line content of the file first then print all the even line content.
Examples:
Input: file1.txt:WelcometoGeeksforGeeksOutput:Odd line contents:WelcomeGeeksforGeeksEven line contents:to
Input: file1.txt:1. This is Line1.2. This is Line2.3. This is Line3.4. This is Line4.
Output:Odd line contents:1. This is Line1.3. This is Line3.Even line contents:2. This is Line2.4. This is Line4.
Approach:
Open the file in a+ mode.Insert a new line at the end of the file, so that the output doesn’t get effected.Print odd lines of the file by keeping a check, that doesn’t print even lines of the file.Rewind the file pointer.Reinitialize check.Print even lines of the file by keeping a check, that doesn’t print odd lines of the file.
Open the file in a+ mode.
Insert a new line at the end of the file, so that the output doesn’t get effected.
Print odd lines of the file by keeping a check, that doesn’t print even lines of the file.
Rewind the file pointer.
Reinitialize check.
Print even lines of the file by keeping a check, that doesn’t print odd lines of the file.
Below is the implementation of the above approach:
// C program for the above approach  #include <stdio.h>  // Function which prints the file content// in Odd Even mannervoid printOddEvenLines(char x[]){    // Opening the path entered by user    FILE* fp = fopen(x, "a+");      // If file is null, then return    if (!fp) {        printf("Unable to open/detect file");        return;    }      // Insert a new line at the end so    // that output doesn't get effected    fprintf(fp, "\n");      // fseek() function to move the    // file pointer to 0th position    fseek(fp, 0, 0);      int check = 0;    char buf[100];      // Print Odd lines to stdout    while (fgets(buf, sizeof(buf), fp)) {          // If check is Odd, then it is        // odd line        if (!(check % 2)) {            printf("%s", buf);        }        check++;    }    check = 1;      // fseek() function to rewind the    // file pointer to 0th position    fseek(fp, 0, 0);      // Print Even lines to stdout    while (fgets(buf, sizeof(buf), fp)) {          if (!(check % 2)) {            printf("%s", buf);        }        check++;    }      // Close the file    fclose(fp);      return;}  // Driver Codeint main(){    // Input filename    char x[] = "file1.txt";      // Function Call    printOddEvenLines(x);      return 0;}
Input File:Output File:
Akanksha_Rai
C-File Handling
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
Can we declare more than one class in a single Java program?


A single Java program contains two or more classes, it is possible in two ways in Java.
Nested Classes
Multiple non-nested classes
In the below example, the java program contains two classes, one class name is Computer and another is Laptop. Both classes have their own constructors and a method. In the main method, we can create an object of two classes and call their methods.
Live Demo
public class Computer {
   Computer() {
      System.out.println("Constructor of Computer class.");
   }
   void computer_method() {
      System.out.println("Power gone! Shut down your PC soon...");
   }
   public static void main(String[] args) {
      Computer c = new Computer();
      Laptop l = new Laptop();
      c.computer_method();
      l.laptop_method();
   }
}
class Laptop {
   Laptop() {
      System.out.println("Constructor of Laptop class.");
   }
   void laptop_method() {
      System.out.println("99% Battery available.");
   }
}
When we compile the above program, two .class files will be created which are Computer.class and Laptop.class. This has the advantage that we can reuse our .class file somewhere in other projects without compiling the code again. In short, the number of .class files created will be equal to the number of classes in the code. We can create as many classes as we want but writing many classes in a single file is not recommended as it makes code difficult to read rather we can create a single file for every class.
Constructor of Computer class.
Constructor of Laptop class.
Power gone! Shut down your PC soon...
99% Battery available.
Once the main class is compiled which has several inner classes, the compiler generates separate .class files for each of the inner classes.
Live Demo
// Main class
public class Main {
   class Test1 { // Inner class Test1
   }
   class Test2 { // Inner class Test2
   }
   public static void main(String [] args) {
      new Object() { // Anonymous inner class 1
      };
      new Object() { // Anonymous inner class 2
      };
      System.out.println("Welcome to Tutorials Point");
   }
}
In the above program, we have a Main class that has four inner classes Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class, it will generate the following class files.
Main.class
Main$Test1.class
Main$Test2.class
Main$1.class 
Main$2.class
Welcome to Tutorials Point
Python Getting sublist element till N

In this tutorial, we are going to write a program that returns a sublist element till nth sublist in a list. Let's say we have the following list with 5 sublists.
[['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#', 'C++'], ['React', 'Angular']] Now, we have to get the first element from the first three sublists. We can get the elements different approaches. Let's see some of them.
More generic and first thought of the most of programmers is to use loops. Let's see the code using loops.
 Live Demo
# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# empty list to store final elements from the sublists
desired_elements = []
# iterating over the list till 3rd element
for i in range(N):
   # storing the first element from the sublist
   desired_elements.append(random_list[i][0])
# printing the elements
print(desired_elements)
If you run the above code, then you will get the following result.
['Python', 'C', 'Javascript']
We can use the list comprehensions in place of for loop. Let's see the same code using list comprehensions.
 Live Demo
# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# getting first element from the sublists
desired_elements = [sublist[0] for sublist in random_list[:N]]
# printing the elements
print(desired_elements)
If you run the above code, then you will get the following result.
['Python', 'C', 'Javascript']
Python provides a lot of built-in modules and methods. Let's use them to solve our problem.are going to use the map, itemgetter, and islice methods to achieve the output as expected.Let's see the code.
 Live Demo
# importing the required methods
import operator # for itemgetter
import itertools # for islice
# initializing the list and N
random_list = [['Python', 'Java'], ['C', 'Pascal'], ['Javascript', 'PHP'], ['C#
C++'], ['React', 'Angular']]
N = 3
# getting first element from the sublists
desired_elements = list(map(operator.itemgetter(0), itertools.islice(random_list, N)))
# printing the elements
print(desired_elements)
If you run the above code, then you will get the following result.
['Python', 'C', 'Javascript']
You can take any element in place of the first element. We have taken the first element for the demonstration. If you have any doubts in the tutorial, mention them in the comment section.
Finding square root of a number without using library functions - JavaScript

We are required to write a JavaScript function that takes in a number and calculates its square root without using the Math.sqrt() function.
Following is the code −
const square = (n, i, j) => {
   let mid = (i + j) / 2;
   let mul = mid * mid;
   if ((mul === n) || (Math.abs(mul - n) < 0.00001)){
      return mid;
   }else if (mul < n){
      return square(n, mid, j);
   }else{
      return square(n, i, mid);
   }
}
// Function to find the square root of n
const findSqrt = num => {
   let i = 1;
   const found = false;
   while (!found){
      // If n is a perfect square
      if (i * i === num){
         return i;
      }else if (i * i > num){
         let res = square(num, i - 1, i);
         return res;
      };
      i++;
   }
}
console.log(findSqrt(33));
This will produce the following output in console −
5.744562149047852
We looped over from i = 1.
If i * i = n, then we returned i as n is a perfect square whose square root is i., else we find the smallest i for which i * i is just greater than n.
Now we know the square root of n lies in the interval i – 1 and i. And then we used the Binary Search algorithm to find the square root.
C library function - atexit()

The C library function int atexit(void (*func)(void)) causes the specified function func to be called when the program terminates. You can register your termination function anywhere you like, but it will be called at the time of the program termination.
Following is the declaration for atexit() function.
int atexit(void (*func)(void))
func − This is the function to be called at the termination of the program.
func − This is the function to be called at the termination of the program.
This function returns a zero value if the function is registered successfully, otherwise a non-zero value is returned if it is failed.
The following example shows the usage of atexit() function.
#include <stdio.h>
#include <stdlib.h>

void functionA () {
   printf("This is functionA\n");
}

int main () {
   /* register the termination function */
   atexit(functionA );
   
   printf("Starting  main program...\n");

   printf("Exiting main program...\n");

   return(0);
}
Let us compile and run the above program that will produce the following result −
Starting main program...
Exiting main program...
This is functionA


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
# and ## Operators in C ?

In this section we will see what are the Stringize operator(#) and Token Pasting operator(##) in C. The Stringize operator is a preprocessor operator. It sends commands to compiler to convert a token into string. We use this operator at the macro definition.
Using stringize operator we can convert some text into string without using any quotes.
 Live Demo
#include<stdio.h>
#define STR_PRINT(x) #x
main() {
   printf(STR_PRINT(This is a string without double quotes));
}
This is a string without double quotes
The Token Pasting operator is a preprocessor operator. It sends commands to compiler to add or concatenate two tokens into one string. We use this operator at the macro definition.
 Live Demo
#include<stdio.h>
#define STR_CONCAT(x, y) x##y
main() {
   printf("%d", STR_CONCAT(20, 50));
}
2050
Finding remainder of a large number - GeeksforGeeks

20 Jul, 2021
Number System is an important concept for solving GATE Aptitude questions and aptitude for entrance exams for different companies. 
The below is an important question which has been asked in many exams. 
Question : If 7126 is not divisible by 48, find the remainder? 
Normal Approach : For calculating the remainder we first calculate the original value for number 7126 and divide it by 48 and obtain the remainder. It is very long and time taking process and it is not at all feasible to solve it in this way. So we use some important mathematical concepts related to divisibility to solve this problem. 
Speedy approach : Important concepts for solving problem, 
(xn – an) divisible by (x – a) for every n (n belongs to integers)
(xn – an) divisible by (x + a) for every even number n (n belongs to integers)
(xn – an) divisible by (x + a) for every odd number n (n belongs to integers)
And we also use another basic formula;  
Dividend = divisor x quotient + remainder 
The given number is in a form such that the base is very near to 48. 
This is done by using the formula ( amn ) = (am)n  
7126 = (72)63 = 4963 
Now by using our mathematical formulae we should add or subtract a number to 4963 such that it is divisible by 48. 
(4963 – 1) = (4963 - 163) 
By comparing it with (xn – an) we can write, 
x = 49, n = 63 and a = 1
Therefore from the above we get that ( 4963 – 163) is divisible by (49-1) and (49+1) So, (4963 – 1) is divisible by 48 Let (4963 – 1)/48 = q (where q is the quotient ) 
4963 – 1 = 48 x q
4963 = 48 x q + 1 
7126 = 48 x q + 1 
Comparing with. 
Dividend = divisor * quotient + remainder 
So from above when the dividend = 7126 and the divisor = 48, then the remainder is 1. So when 7126 is divided by 48, the remainder is 1. 
In this way we can obtain the remainder for such large numbers. It takes very less time and is very useful in competitive exams. 
varmasuyash
gabaa406
Aptitude
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Newton's Divided Difference Interpolation Formula
Discrete Mathematics | Hasse Diagrams
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Set Notations in LaTeX
Mathematics | Graph Isomorphisms and Connectivity
Univariate, Bivariate and Multivariate data and its analysis
Logic Notations in LaTeX
Activation Functions
Various Implicants in K-Map