code-rag-bench/online-tutorials huggingface dataset:
Kotlin Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Kotlin has a Boolean data type, which can take the values true or false.
A boolean type can be declared with the Boolean keyword and can only take the values true or false:
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false 
Just like you have learned with other data types in the previous chapters, the example above can also be written without specifying the type, as Kotlin is smart enough to understand that the variables are Booleans:
val isKotlinFun = true
val isFishTasty = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false 
A Boolean expression returns a Boolean value: true or false.
You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
val x = 10
val y = 9println(x > y) // Returns true, because 10 is greater than 9
Or even easier:
println(10 > 9) // Returns true, because 10 is greater than 9
In the examples below, we use the equal to (==) operator to evaluate an expression:
val x = 10;
println(x == 10); // Returns true, because the value of x is equal to 10
println(10 == 15); // Returns false, because 10 is not equal to 15
The Boolean value of an expression is the basis for all Kotlin comparisons and conditions.
You will learn more about conditions in the next chapter.
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.
How to remove everything before values starting after underscore from column values of an R data frame?

If a column in an R data frame contain string values that are separated with an underscore and stretches the size of the column values that also contain common values then it would be wise to remove underscore sign from all the values at once along with the values that is common. This will help us to read the data properly as well as analysis will become easy. For this purpose, we can use gsub function
Consider the below data frame −
 Live Demo
set.seed(191)
ID<-c("ID_1","ID_2","ID_3","ID_4","ID_5","ID_6","ID_7","ID_8","ID_9","ID_10","ID_11","ID_12","ID_13","ID_14","ID_15","ID_16","ID_17","ID_18","ID_19","ID_20")
Salary<-sample(20000:50000,20)
df1<-data.frame(ID,Salary)
df1
   ID   Salary
1  ID_1  33170
2  ID_2  22747
3  ID_3  42886
4  ID_4  22031
5  ID_5  45668
6  ID_6  32584
7  ID_7  34779
8  ID_8  20471
9  ID_9  38689
10 ID_10 29660
11 ID_11 49664
12 ID_12 24284
13 ID_13 36537
14 ID_14 37693
15 ID_15 30265
16 ID_16 36004
17 ID_17 48247
18 ID_18 20750
19 ID_19 27400
20 ID_20 20553
Removing everything before and including underscore sign from ID values in column ID −
df1$ID<-gsub("^.*\\_","",df1$ID)
df1
   ID Salary
1  1  48769
2  2  26002
3  3  37231
4  4  24437
5  5  43311
6  6  47494
7  7  21029
8  8  28069
9  9  41108
10 10 29363
11 11 23371
12 12 25898
13 13 42434
14 14 22210
15 15 48969
16 16 21640
17 17 36175
18 18 21210
19 19 43374
20 20 29367
Let’s have a look at another example −
 Live Demo
Group<-c("GRP_1","GRP_2","GRP_3","GRP_4","GRP_5","GRP_6","GRP_7","GRP_8","GRP_9","GRP_10","GRP_11","GRP_12","GRP_13","GRP_14","GRP_15","GRP_16","GRP_17","GRP_18","GRP_19","GRP_20")
 Ratings<-sample(0:10,20,replace=TRUE)
df2<-data.frame(Group,Ratings)
df2
 Group Ratings
1  GRP_1  6
2  GRP_2  9
3  GRP_3  7
4  GRP_4 10
5  GRP_5 10
6  GRP_6  9
7  GRP_7  9
8  GRP_8  3
9  GRP_9  2
10 GRP_10 0
11 GRP_11 3
12 GRP_12 7
13 GRP_13 6
14 GRP_14 10
15 GRP_15 1
16 GRP_16 3
17 GRP_17 10
18 GRP_18 2
19 GRP_19 9
20 GRP_20 0
Removing everything before and including underscore sign from GRP values in column Group −
df2$Group<-gsub("^.*\\_","",df2$Group)
df2
   Group Ratings
1   1     4
2   2     8
3   3     7
4   4     0
5   5    10
6   6    10
7   7     5
8   8     4
9   9     3
10 10     7
11 11     4
12 12     4
13 13     3
14 14    10
15 15     7
16 16     2
17 17     3
18 18     8
19 19     9
20 20     5
Program to find largest perimeter triangle using Python

Suppose we have an array nums of positive lengths, we have to find the largest perimeter of a triangle, by taking three values from that array. When it is impossible to form any triangle of non-zero area, then return 0.
So, if the input is like [8,3,6,4,2,5], then the output will be 19.
To solve this, we will follow these steps −
sort the list nums
sort the list nums
a := delete last element from nums
a := delete last element from nums
b := delete last element from nums
b := delete last element from nums
c := delete last element from nums
c := delete last element from nums
while b+c <= a, doif not nums is non-zero, thenreturn 0a := bb := cc := delete last element from nums
while b+c <= a, do
if not nums is non-zero, thenreturn 0
if not nums is non-zero, then
return 0
return 0
a := b
a := b
b := c
b := c
c := delete last element from nums
c := delete last element from nums
return a+b+c
return a+b+c
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums):
   nums.sort()
   a, b, c = nums.pop(), nums.pop(), nums.pop()
   while b+c<=a:
      if not nums:
         return 0
      a, b, c = b, c, nums.pop()
   return a+b+c
nums = [8,3,6,4,2,5]
print(solve(nums))
[8,3,6,4,2,5]
19
What are type specifiers in C++?

When you first declare a variable in a statically typed language such as C++ you must declare what that variable is going to hold.
int number = 42;
In that example, the "int" is a type specifier stating that the variable "number" can only hold integer numbers. In dynamically typed languages such as ruby or javascript, you can simply declare the variable.
var number = 42;
There are a lot of built-in type specifiers like double, char, float, etc in C++. You can also create your own specifiers by creating class and structs.
Best way to find length of JSON object in JavaScript

Suppose we have an object like this −
const obj = {
   name: "Ramesh",
   age: 34,
   occupation: "HR Manager",
   address: "Tilak Nagar, New Delhi",
   experience: 13
};
We are required to write a JavaScript function on Objects that computes their size (i.e., the
number of properties in it).
The code for this will be −
const obj = {
   name: "Ramesh",
   age: 34,
   occupation: "HR Manager",
   address: "Tilak Nagar, New Delhi",
   experience: 13
};
Object.prototype.size = function(obj) {
   let size = 0, key;
   for (key in obj) {
      if (obj.hasOwnProperty(key)){
         size++
      };
   };
   return size;
};
const size = Object.size(obj);
console.log(size);
The output in the console will be −
5
How to catch syntax errors in JavaScript?

You cannot use try-catch blocks for handling syntax errors in JavaScript since it is thrown while the code is being parsed.
Use window.onerror as in the following code −
<html>
   <head>
      <script>
         window.onerror = function(e) {
            document.write('Error: ', e, '</br>')
         };
      </script>
     
      <script>
         document.write('x'x')
      </script>
   </head>
 
   <body>
   </body>
</html>
Note − Ensure that the error function is defined in a separate <script> tag.
C++ Library - <typeinfo>

It defines in header and related to operators typeid and dynamic_cast.
Following is the declaration for std::type_info.
class type_info;
class type_info;
It contains type information.
It throws an exception on failure to dynamic cast.
It throws an exception on typeid of null point.
 Print
 Add Notes
 Bookmark this page
Python Number atan() Method

Python number  method atan() returns the arc tangent of x, in radians.
Following is the syntax for atan() method −
atan(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns arc tangent of x, in radians.
The following example shows the usage of atan() method.
#!/usr/bin/python
import math

print "atan(0.64) : ",  math.atan(0.64)
print "atan(0) : ",  math.atan(0)
print "atan(10) : ",  math.atan(10)
print "atan(-1) : ",  math.atan(-1)
print "atan(1) : ",  math.atan(1)
When we run above program, it produces following result −
atan(0.64) :  0.569313191101
atan(0) :  0.0
atan(10) :  1.4711276743
atan(-1) :  -0.785398163397
atan(1) :  0.785398163397


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to unzip a file using PHP ?

22 Jun, 2020
To unzip a file with PHP, we can use the ZipArchive class. ZipArchive is a simple utility class for zipping and unzipping files. We don’t require any extra additional plugins for working with zip files. ZipArchive class provides us a facility to create a zip file or to extract the existing zip file. The ZipArchive class has a method called extractTo to extract the contents of the complete archive or the given files to the specified destination. The ZipArchive class also has a lot of other methods and properties to help you get more information about the archive before extracting all its contents.
Syntax:
bool ZipArchive::extractTo( string $destination, mixed $entries )
Parameters:
destination: The $destination parameter can be used to specify the location where to extract the files.
entries: The $entries parameter can be used to specify a single file name which is to be extracted, or you can use it to pass an array of files.
Example 1: This example unzip all the files from specific folder.
<?php  $zip = new ZipArchive;  // Zip File Nameif ($zip->open('GeeksforGeeks.zip') === TRUE) {      // Unzip Path    $zip->extractTo('/Destination/Directory/');    $zip->close();    echo 'Unzipped Process Successful!';} else {    echo 'Unzipped Process failed';}?>
Description: Create an object of the ZipArchive class and open a given zip file using $zip->open() method.
If it returns TRUE then extract the file to the specified path with extractTo() method by passing path address as an argument in it.
Example 2: This example unzip the specific file from the folder.
<?php  $zip = new ZipArchive;  // Zip File Name$res = $zip->open('GeeksForGeeks.zip');  if ($res === TRUE) {          // Unzip Path     $zip->extractTo('/Destination/Directory/',        array('H_W.gif', 'helloworld.php'));              $zip->close();    echo 'Unzipped Process Successful!';} else {    echo 'Unzipped Process failed';}
Description: With the file element, you can select the zip file that you want to extract. If a selected file is valid then pass to open() method and extract it to the specified path using extractTo() method.
PHP-Misc
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C strings conversion to Python

02 Apr, 2019
For C strings represented as a pair char *, int, it is to decide whether or not – the string presented as a raw byte string or as a Unicode string.
Byte objects can be built using Py_BuildValue() as
// Pointer to C string datachar *s;   // Length of data int len;   // Make a bytes objectPyObject *obj = Py_BuildValue("y#", s, len);
 To create a Unicode string and is it is known that s points to data encoded as UTF-8, the code given below can be used as –
PyObject *obj = Py_BuildValue("s#", s, len);
 If s is encoded in some other known encoding, a string using PyUnicode_Decode() can be made as:
PyObject *obj = PyUnicode_Decode(s, len, "encoding", "errors");  // Exampleobj = PyUnicode_Decode(s, len, "latin-1", "strict");obj = PyUnicode_Decode(s, len, "ascii", "ignore");
 If a wide string needs to be represented as wchar_t *, len pair. Then are few options as shown below –
// Wide character stringwchar_t *w;  // Lengthint len;   // Option 1 - use Py_BuildValue()PyObject *obj = Py_BuildValue("u#", w, len);  // Option 2 - use PyUnicode_FromWideChar()PyObject *obj = PyUnicode_FromWideChar(w, len);
The data from C must be explicitly decoded into a string according to some codec
Common encodings include ASCII, Latin-1, and UTF-8.
If you’re encoding is not known, then it is best off to encode the string as bytes instead.
Python always copies the string data (being provided) when making an object.
Also, for better reliability, strings should be created using both a pointer and a size rather than relying on NULL-terminated data.
Python-ctype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Information and Knowledge

04 Oct, 2019
Information:Information is delineate because the structured, organized and processed data, conferred inside context, that makes it relevant and helpful to the one who desires it. Data suggests that raw facts and figures regarding individuals, places, or the other issue, that is expressed within the type of numbers, letters or symbols.
Information is that the knowledge that is remodeled and classified into an intelligible type, which may be utilized in the method of deciding. In short, once knowledge end up to be purposeful when conversion, it’s referred to as info. it’s one thing that informs, in essence, it provides a solution to a specific question. It may be obtained from numerous sources like newspaper, internet, television, people, books etc.
Knowledge:Knowledge refers to the familiarity and awareness of a person, place, events, thoughts, issues, things or anything that is gathered through learning, knowing or discovering. it’s the state of knowing one thing with cognizance through the understanding of ideas, study and skill.
Knowledge pointed at the assured theoretical or sensible understanding of associate entity together with the potential of exploitation it for a selected purpose. Combination of information, expertise and intuition ends up in knowledge that has the potential to draw inferences and develop insights, supported our expertise and so it will assist in higher cognitive process and taking actions.
Difference between Information and Knowledge:
Difference Between
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL Select Multiple VALUES?

To select multiple values, you can use where clause with OR and IN operator.
The syntax is as follows −
select *from yourTablename where yourColumnName = value1 or yourColumnName = value2 or yourColumnName = value3,.........N;
select *from yourTableName where yourColumnName IN(value1,value2,....N);
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table selectMultipleValues
−> (
−> BookId int,
−> BookName varchar(200)
−> );
Query OK, 0 rows affected (1.68 sec)
Now you can insert some records in the table with the help of insert command. The query to insert records is as follows −
mysql> insert into selectMultipleValues values(100,'Introduction to C');
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectMultipleValues values(101,'Introduction to C++');
Query OK, 1 row affected (0.19 sec)

mysql> insert into selectMultipleValues values(103,'Introduction to java');
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectMultipleValues values(104,'Introduction to Python');
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectMultipleValues values(105,'Introduction to C#');
Query OK, 1 row affected (0.13 sec)

mysql> insert into selectMultipleValues values(106,'C in Depth');
Query OK, 1 row affected (0.15 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from selectMultipleValues;
The following is the output −
+--------+------------------------+
| BookId | BookName               |
+--------+------------------------+
| 100    | Introduction to C      |
| 101    | Introduction to C++    |
| 103    | Introduction to java   |
| 104    | Introduction to Python |
| 105    | Introduction to C#     |  
| 106    | C in Depth             |
+--------+------------------------+
6 rows in set (0.00 sec)
The following is the query to select multiple values with the help of OR operator.
mysql> select *from selectMultipleValues where BookId = 104 or BookId = 106;
The following is the output −
+--------+------------------------+
| BookId | BookName |
+--------+------------------------+
| 104 | Introduction to Python |
| 106 | C in Depth |
+--------+------------------------+
2 rows in set (0.00 sec)
The following is the query to select multiple values with the help of IN operator.
mysql> select *from selectMultipleValues where BookId in(104,106);
The following is the output −
+--------+------------------------+
| BookId | BookName               |
+--------+------------------------+
| 104    | Introduction to Python |
| 106    | C in Depth             |  
+--------+------------------------+
2 rows in set (0.00 sec)
Insert more than one element at once in a C# List

Use the InsertRange() method to insert a list in between the existing lists in C#. Through this, you can easily add more than one element to the existing list.
Let us first set a list −
List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
Now, let us set an array. The elements of this array are what we will add to the above list −
int[] arr2 = new int[4];
arr2[0] = 60;
arr2[1] = 70;
arr2[2] = 80;
arr2[3] = 90;
We will add the above elements to the list −
arr1.InsertRange(5, arr2);
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      int[] arr2 = new int[4];
      arr2[0] = 60;
      arr2[1] = 70;
      arr2[2] = 80;
      arr2[3] = 90;
      arr1.InsertRange(5, arr2);
      Console.WriteLine("After adding elements ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
   }
}
Initial List ...
10
20
30
40
50
After adding elements ...
10
20
30
40
50
60
70
80
90
How to find absolute difference between two numbers in MySQL?

To get the difference between two number in MySQL, let us first create a demo table
mysql> create table findDifferenceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstNumber float,
   -> SecondNumber float
   -> );
Query OK, 0 rows affected (0.60 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(4.2,2.3);
Query OK, 1 row affected (0.20 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(23.4,5.6);
Query OK, 1 row affected (0.14 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(5.8,34.56);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(7.8,7.2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(12.8,10.2);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from findDifferenceDemo;
The following is the output
+----+-------------+--------------+
| Id | FirstNumber | SecondNumber |
+----+-------------+--------------+
| 1  | 4.2         |          2.3 |
| 2  | 23.4        |          5.6 |
| 3  | 5.8         |        34.56 |
| 4  | 7.8         |          7.2 |
| 5  | 12.8        |         10.2 |
+----+-------------+--------------+
5 rows in set (0.00 sec)
The following is the query to find absolute difference between two numbers in MySQL
mysql> SELECT ABS(FirstNumber - secondNumber) AS diff
   -> from findDifferenceDemo
   -> order by diff desc;
The following is the output
+--------------------+
| diff               |
+--------------------+
| 28.760001182556152 |
| 17.799999713897705 |
| 2.6000003814697266 |
| 1.8999998569488525 |
| 0.6000003814697266 |
+--------------------+
5 rows in set (0.00 sec)
How to install the MSI package using PowerShell DSC?

To install the MSI package using DSC, we need to use the DSC resource “Package”. Let see which properties are available for this resource.
PS C:\> Get-DscResource -Name Package | Select -ExpandProperty Properties

Name PropertyType IsMandatory Values
---- ------------ ----------- ------
Name [string] True {}
Path [string] True {}
ProductId [string] True {}
Arguments [string] False {}
Credential [PSCredential] False {}
DependsOn [string[]] False {}
Ensure [string] False {Absent, Present}
LogPath [string] False {}
PsDscRunAsCredential [PSCredential] False {}
ReturnCode [UInt32[]] False {}
Name, Path, and ProductID parameters are mandatory for this DSC resource.
The best way to retrieve the above details is to install the sample package on the test machine and then get the details. We will use here the 7Zip MSI package installed on one computer.
Get-Package 7-zip* | fl *
From the above output, we can grab here the name of the Package after installation, ProductID (i.e. ProductCode).
Configuration Install7zip{
   Node @("LabMachine2k16","AD"){
      Package 7zip{
         Name = '7-Zip 19.00 (x64 edition)'
         ProductId = '23170F69-40C1-2702-1900-000001000000'
         Path = '\\ad\shared\7z1900-x64.msi'
         Ensure = 'Present'
      }
   }
}
In the above example, the source package is located at the source location and we want to install 7zip on the two nodes.
To generate the MOF file at the specific location so we can use them later to start the configuration,
Install7zip -OutputPath C:\Temp\7zipInstall -Verbose
Once the MOF file is generated, we can start the configuration to apply DSC,
Start-DscConfiguration -Path C:\Temp\7zipInstall -Wait -Force -Verbose
Once the above command runs successfully, check if the configuration is applied or not using,
Test-DscConfiguration -Path C:\Temp\7zipInstall
You should get output like below, which shows that both the servers are in the desired state, which means the MSI package is installed.
If the InDesiredState property is false, it means the server has missed the configuration.
How to find which Python modules are being imported from a package?

To find all the python modules from a particular package that are being used in an application, you can use the sys.modules dict. sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules.
For example,
>>> from datetime import datetime
>>> import sys
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', 'locale', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'datetime', 'sysconfig', 'operator', '__main__', 'types', 'encodings.encodings', 'abc', 'encodings.cp437', '_weakrefset', 'errno', 'encodings.codecs', 'backports', 'sre_constants', 're', '_abcoll', 'ntpath', '_codecs', 'zope', 'nt', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'mpl_toolkits', 'warnings', 'UserDict', 'encodings.cp1252', 'sys', 'codecs', 'os.path', '_functools', '_locale', 'signal', 'traceback', 'linecache', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
You could also use python -v, which will emit messages about every imported module. For example, if you have the python code in hello.py, then,
$ python -v hello.py
Entity Framework - Explicit Loading

When you disabled the lazy loading, it is still possible to lazily load related entities, but it must be done with an explicit call.
Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run.
Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run.
To do so you use the Load method on the related entity’s entry.
To do so you use the Load method on the related entity’s entry.
For a one-to-many relationship, call the Load method on Collection.
For a one-to-many relationship, call the Load method on Collection.
And for a one-to-one relationship, call the Load method on Reference.
And for a one-to-one relationship, call the Load method on Reference.
Let’s take a look at the following example in which lazy loading is disabled and then the student whose first name is Ali is retrieved.
Student information is then written on console. If you look at the code, enrollments information is also written but Enrollments entity is not loaded yet so foreach loop will not be executed.
After that Enrollments entity is loaded explicitly now student information and enrollments information will be written on the console window.
class Program {

   static void Main(string[] args) {

      using (var context = new UniContextEntities()) {

         context.Configuration.LazyLoadingEnabled = false;

         var student = (from s in context.Students where s.FirstMidName == 
            "Ali" select s).FirstOrDefault<Student>();

         string name = student.FirstMidName + " " + student.LastName;
         Console.WriteLine("ID: {0}, Name: {1}", student.ID, name);

         foreach (var enrollment in student.Enrollments) {
            Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", 
               enrollment.EnrollmentID, enrollment.CourseID);
         }

         Console.WriteLine();
         Console.WriteLine("Explicitly loaded Enrollments");
         Console.WriteLine();

         context.Entry(student).Collection(s ⇒ s.Enrollments).Load();
         Console.WriteLine("ID: {0}, Name: {1}", student.ID, name);

         foreach (var enrollment in student.Enrollments) {
            Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", 
               enrollment.EnrollmentID, enrollment.CourseID);
         }

         Console.ReadKey();
      }
   }
}
When the above example is executed, you will receive the following output. First only student information is displayed and after explicitly loading enrollments entity, both student and his related enrollments information is displayed.
ID: 1, Name: Ali Alexander
Explicitly loaded Enrollments
ID: 1, Name: Ali Alexander
       Enrollment ID: 1, Course ID: 1050
       Enrollment ID: 2, Course ID: 4022
       Enrollment ID: 3, Course ID: 4041

We recommend that you execute the above example in a step-by-step manner for better understanding.

    19 Lectures 
     5 hours 

 Trevoir Williams

    33 Lectures 
     3.5 hours 

 Nilay Mehta

    21 Lectures 
     2.5 hours 

 TELCOMA Global

    89 Lectures 
     7.5 hours 

 Mustafa Radaideh
 Print
 Add Notes
 Bookmark this page
How to Get the IP Address of a Docker Container? - GeeksforGeeks

28 Oct, 2020
If you want multiple Docker Containers to talk to each other, they can form a Bridge Network. Each Container Network has its own Subnet mask to distribute IP addresses. The default subnet for a Docker Network is 172.17.0.0/16
In this article, we are going to discuss the different ways you can use to know the IP address of a Docker Container.
Start the Bash of the Container.
sudo docker exec -it 6cb599fe30ea bash

Running the bash
Install iproute2 to use the ip command.
apt-get install iproute2

Use this command to get the IP address.
ip add | grep global

Method 1: Using the Bash
You can get the IP address of the Docker Container directly using this command. You need to have the Container ID to use this method.
sudo docker exec -it 6cb599fe30ea ip addr | grep global

Method 2:  Direct Command
You can also use the Docker Inspect command to return the IP address of the Docker Container. 
sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' 6cb599fe30ea

Method 3:  Using Docker Inspect
To conclude, in this article we discussed three different ways to find out the IP address of a Docker Container. Methods 2 and 3 require less effort and using a single line command, you can easily find out the IP address of the container if you have it’s Container ID.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
ML | Stochastic Gradient Descent (SGD)
Principal Component Analysis with Python
Fuzzy Logic | Introduction
How to create a REST API using Java Spring Boot
Classifying data using Support Vector Machines(SVMs) in Python
ML | Data Preprocessing in Python
Q-Learning in Python
Basics of API Testing Using Postman
Monolithic vs Microservices architecture
Pandas – DataFrame to CSV file using tab separator

27 Aug, 2021
Let’s see how to convert a DataFrame to a CSV file using the tab separator. We will be using the to_csv() method to save a DataFrame as a csv file. To save the DataFrame with tab separators, we have to pass “\t” as the sep parameter in the to_csv() method.
Approach : 
Import the Pandas and Numpy modules.Create a DataFrame using the DataFrame() method.Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\t”.Load the newly created CSV file using the read_csv() method as a DataFrame.Display the new DataFrame.
Import the Pandas and Numpy modules.
Create a DataFrame using the DataFrame() method.
Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\t”.
Load the newly created CSV file using the read_csv() method as a DataFrame.
Display the new DataFrame.
Python3
# importing the modulesimport pandas as pdimport numpy as np # creating a DataFramestudents = {'Student': ['Amit', 'Cody',                        'Darren', 'Drew'],            'RollNumber': [1, 5, 10, 15],            'Grade': ['A', 'C', 'F', 'B']}df = pd.DataFrame(students,                  columns =['Student', 'RollNumber',                            'Grade'])# displaying the original DataFrameprint("Original DataFrame")print(df) # saving as a CSV filedf.to_csv('Students.csv', sep ='\t') # loading the CSV filenew_df = pd.read_csv('Students.csv') # displaying the new DataFrameprint('Data from Students.csv:')print(new_df)
Output : 
 
The contents of the Students.csv file are : 
 
sooda367
anikakapoor
sagartomar9927
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a moving div using JavaScript ?

25 May, 2021
In this article, we will learn to create a moving HTML div using JavaScript. The div will move left to right using HTML, CSS, and JavaScript. 
Approach:
We have to create an HTML div and add some CSS to the div using a class ball. In CSS, we add some background-color to the body and give some height, width, and color to the div.Now we will add margin-left to the div using JavaScript. So it will move left to right.In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div.
We have to create an HTML div and add some CSS to the div using a class ball.
 In CSS, we add some background-color to the body and give some height, width, and color to the div.
Now we will add margin-left to the div using JavaScript. So it will move left to right.
In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div.
HTML code:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta http-equiv="X-UA-Compatible"           content="IE=edge" />    <meta name="viewport"           content="width=device-width, initial-scale=1.0" />      <style>      body {        background-color: aqua;        display: flex;        align-items: center;      }        .ball {        height: 12rem;        width: 12rem;        background-color: white;        border-radius: 50%;        margin-top: 20rem;      }    </style>  </head>  <body>    <div class="container">      <div class="ball" id="ballID"></div>    </div>    <script>      let ball = document.getElementById("ballID");        var myVar = setInterval(spostaDiv, 90);      var margin = 0;        let l = window.screen.width;      let w = 1300;        function spostaDiv() {        console.log(w);        if (margin == w) {          margin = 0 + "px";        } else {          ball.style.marginLeft = margin + "px";        }        margin += 10;      }    </script>  </body></html>
Output:
CSS-Properties
CSS-Questions
HTML-Attributes
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the last character of a string in PHP ? - GeeksforGeeks

21 May, 2021
In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.
Using array() method
Using substr() method
Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is “Akshit” Its length is 6, in zero-indexing, the value of (length-1) is 5 which is the character “t” The length can be found using the PHP strlen() method.
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)
Example:
PHP
<?php $txt = "Geeksforgeeks"; echo "Last Character of string is : "    .$txt[strlen($txt)-1];?>
Output:
Last Character of string is : s
Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string.
Syntax:
substr(string_name, start_position, string_length_to_cut)
Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”. There are 2 ways to reach “s”. From the beginning “s” is at the 25th position. We can find the length of the string, then display “length-1”. This means we want to display part of the string using substr() method where the starting point is “length-1”.
PHP
<?php$txt = "Akshit Loves GeeksForGeeks";echo "Last character of String is : "  .substr($txt, strlen($txt)-1);?>
Output: From the end, “s” is at 1st position. We can display string from (-1)
Last character of String is : s
From end: “s” is at 1st position
We can display string from “-1”
PHP
<?php$txt = "Akshit Loves GeeksForGeeks";echo "Last character of String is: ".substr($txt, -1);?>
Last character of String is: s
NOTE: If you’re using multibyte character encodings like UTF-8, use mb_substr() instead of substr .
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
numpy.fromiter() function – Python - GeeksforGeeks

18 Aug, 2020
numpy.fromiter() function create a new one-dimensional array from an iterable object.
Syntax : numpy.fromiter(iterable, dtype, count = -1)
Parameters :
iterable : [iterable object] An iterable object providing data for the array.
dtype : [data-type] Data-type of the returned array.
count : [int, optional] Number of items to read.
Returns : [ndarray] The output array.
Code #1 :
Python3
# Python program explaining# numpy.fromiter() function              # importing numpy as geek import numpy as geek  iterable = (x * x*x for x in range(4))  gfg = geek.fromiter(iterable, int)  print (gfg)
Output :
[ 0  1  8 27]
Code #2 :
Python3
# Python program explaining# numpy.fromiter() function              # importing numpy as geek import numpy as geek  iterable = (x * x for x in range(6))  gfg = geek.fromiter(iterable, float)  print (gfg)
Output :
[ 0.  1.  4.  9. 16. 25.]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
this pointer in C++ - GeeksQuiz

10 Jul, 2018
/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};
#include
using namespace std;
 
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test &setX(int a) { x = a; return *this; }
  Test &setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
 
int main()
{
  Test obj1(5, 5);
 
  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);
 
  obj1.print();
  return 0;
}

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
ReactJS useLayoutEffect Hook - GeeksforGeeks

22 Jan, 2021
The useLayoutEffect works similarly to useEffect but rather working asynchronously like useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the page loading, we should always use useEffect hook.
The useLayoutEffect hook works in the same phase as componentDidMount and componentDidUpdate methods. We should only use useLayoutEffect if useEffect isn’t outputting the expected result.
Syntax:
useLayoutEffect()
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a name changer application that changes the name of the state when the useLayoutEffect hook is called.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useLayoutEffect, useState } from 'react';  const App = () => {  const [value, setValue] = useState('GFG');      useLayoutEffect(() => {    if (value === 'GFG') {     // Changing the state       setValue('GeeksForGeeks');    }    console.log('UseLayoutEffect is called with the value of ', value);  }, [value]);    return <div>{value} is the greatest portal for geeks!</div>;};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
React-misc
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
How to Use Bootstrap with React?
How to check the version of ReactJS ?
Destructuring of Props in ReactJS
Python - Consecutive Alphabetic Occurrence - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Strings, we can have a problem in which we need to check whether we can find occurrence of characters consecutive and according to English alphabets. This kind of problem can occur in school programming and day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we extract the English alphabets using ascii_letters and check for consecution using zip().
# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()from string import ascii_letters  # initializing stringtest_str = 'geeksforgeeks is best fgr geeks'  # printing original stringprint("The original string is : " + str(test_str))  # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()res = []for i, j in zip(ascii_letters, ascii_letters[1:]) :    if i + j in test_str:        res.append((i, j))  # printing result print("The Consecutive matching letter pairs : " + str(res)) 
The original string is : geeksforgeeks is best fgr geeksThe Consecutive matching letter pairs : [(‘f’, ‘g’), (‘s’, ‘t’)]
 
Method #2 : Using list comprehension + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we perform similar way as above just in one-liner shortened way using list comprehension.
# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()from string import ascii_letters  # initializing stringtest_str = 'geeksforgeeks is best fgr geeks'  # printing original stringprint("The original string is : " + str(test_str))  # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()res = [(i, j) for i, j in zip(ascii_letters,       ascii_letters[1:]) if i + j in test_str]  # printing result print("The Consecutive matching letter pairs : " + str(res)) 
The original string is : geeksforgeeks is best fgr geeks
The Consecutive matching letter pairs : [('f', 'g'), ('s', 't')]

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sum() function in Python
Enumerate() in Python
Defaultdict in Python
Python Dictionary
Read a file line by line in Python
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
Perl unlink Function

This function deletes the files specified by LIST, or the file specified by $_ otherwise. Be careful while using this function because there is no recovering once a file gets deleted.
Following is the simple syntax for this function −
unlink LIST

unlink

This function returns the number of files deleted.
Following is the example code showing its basic usage, create two files t1.txt and t2.txt in /tmp directory and then use the following program to delete these two files −
#!/usr/bin/perl -w

unlink( "/tmp/t1.txt", "/tmp/t2.txt" );
When above code is executed, it produces the following result −
Both the files t1.txt and t2.txt will be deleted from /tmp.


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C# | Getting the value at the specified index of a SortedList object - GeeksforGeeks

01 Feb, 2019
SortedList.GetByIndex(Int32) Method is used to get the value at the specified index of a SortedList object.
Syntax:
public virtual object GetByIndex (int index);
Here index is the zero-based index of the value to get.
Return Value: It returns the value at the specified index of the SortedList object.
Exception: This method will throw ArgumentOutOfRangeException if the index is outside the range of valid indexes for the SortedList object.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating a SortedList of integers        SortedList mylist = new SortedList();          // Adding elements to SortedList        mylist.Add("1", "C++");        mylist.Add("2", "Java");        mylist.Add("3", "DSA");        mylist.Add("4", "Python");        mylist.Add("5", "C#");          // getting the indexing and        // store into a variable        int i = 4;          // getting the value at index 4        Console.WriteLine("Value at index {0} is {1}",                          i, mylist.GetByIndex(i));    }}
Output:
Value at index 4 is C#

Example 2:
// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating a SortedList of integers        SortedList mylist = new SortedList();          // Adding elements to SortedList        mylist.Add("First", "Ram");        mylist.Add("Second", "Shyam");        mylist.Add("Third", "Mohit");        mylist.Add("Fourth", "Rohit");        mylist.Add("Fifth", "Manish");          // getting the indexing and        // store into a variable        // it will give error as        // index is out of range        int i = 7;          // getting the value at index 7        Console.WriteLine("Value at index {0} is {1}",                          i, mylist.GetByIndex(i));    }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getbyindex?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#