code-rag-bench/online-tutorials huggingface dataset:
Chef - ChefSpec

Test Driven Development (TDD) is a way to write unit test before writing any actual recipe code. The test should be real and should validate what a recipe does. It should actually fail as there was no recipe developed. Once the recipe is developed, the test should pass.
ChefSpec is built on the popular RSpec framework and offers a tailored syntax for testing Chef recipe.
Step 1 − Create a gem file containing the chefSpec gem.
vipin@laptop:~/chef-repo $ subl Gemfile 
source 'https://rubygems.org' 
gem 'chefspec' 

Step 2 − Install the gem.
vipin@laptop:~/chef-repo $ bundler install 
Fetching gem metadata from https://rubygems.org/ 
...TRUNCATED OUTPUT... 
Installing chefspec (1.3.1) 
Using bundler (1.3.5) 
Your bundle is complete! 

Step 3 − Create a spec directory.
vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec 

Step 4 − Create a Spec
vipin@laptop:~/chef-repo $ subl  
cookbooks/my_cookbook/spec/default_spec.rb  
require 'chefspec'  
describe 'my_cookbook::default' do  
   let(:chef_run) {  
      ChefSpec::ChefRunner.new(  
         platform:'ubuntu', version:'12.04'  
      ).converge(described_recipe)  
   }  

   it 'creates a greetings file, containing the platform  
   name' do  
      expect(chef_run).to  
      create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!')  
   end  
end 
Step 5 − Validate ChefSpec.
vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb 
F 
Failures: 
1) <CookBook Name> ::default creates a greetings file, containing the platform name 
Failure/Error: expect(chef_run.converge(described_recipe)).to 
create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') 
File content: 
does not match expected: 
Hello! ubuntu! 
# ./cookbooks/my_cookbook/spec/default_spec.rb:11:in `block 
(2 levels) in <top (required)>' 
Finished in 0.11152 seconds 
1 example, 1 failure  

Failed examples: 
rspec ./cookbooks/my_cookbook/spec/default_spec.rb:10 # my_ 
cookbook::default creates a greetings file, containing the 
platform name 

Step 6 − Edit Cookbooks default recipe.
vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb 
template '/tmp/greeting.txt' do 
   variables greeting: 'Hello!' 
end 
Step 7 − Create a template file.
vipin@laptop:~/chef-repo $ subl cookbooks/< Cookbook Name>/recipes/default.rb 
<%= @greeting %> <%= node['platform'] %>! 
Step 8 − Run the rspec again.
vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb 
. 
Finished in 0.10142 seconds 
1 example, 0 failures 

In order to make it work, we need to first set up the base infrastructure for using RSpec with Chef. Then we need to ChefSpec Ruby gem and the cookbook needs a directory called spec where all the tests will be saved.
 Print
 Add Notes
 Bookmark this page
How to splice duplicate item in array JavaScript

We have an array of Number / String literals that contain some duplicate values, we have to
remove these values from the array without creating a new array or storing the duplicate values
anywhere else.
We will use the Array.prototype.splice() method to remove entries inplace, and we will take help
of Array.prototype.indexOf() and Array.prototype.lastIndexOf() method to determine the
duplicacy of any element.
const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];
arr.forEach((el, ind, array) => {
   if(array.indexOf(el) !== array.lastIndexOf(el)){
      array.splice(ind, 1);
   }
});
console.log(arr);
The output in the console will be −
[
   4, 1, 5, 2,
   6, 8, 7
]
Ngx-Bootstrap - accordion

Accordion is a control to display collapsible panels and it is used to display information in limited space.
Displays collapsible content panels for presenting information in a limited amount of space.
accordion
accordion
closeOthers − boolean, if true expanding one item will close all others
closeOthers − boolean, if true expanding one item will close all others
isAnimated − boolean, turn on/off animation, default: false
isAnimated − boolean, turn on/off animation, default: false
Instead of using heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside of a group that will be used as group's header template.
accordion-group, accordion-panel
accordion-group, accordion-panel
heading − string, Clickable text in accordion's group header
heading − string, Clickable text in accordion's group header
isDisabled − boolean, enables/disables accordion group
isDisabled − boolean, enables/disables accordion group
isOpen − boolean, Is accordion group open or closed. This property supports two-way binding
isOpen − boolean, Is accordion group open or closed. This property supports two-way binding
panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...).
panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...).
isOpenChange − Emits when the opened state changes
isOpenChange − Emits when the opened state changes
Configuration service, provides default values for the AccordionComponent.
closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false
closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false
isAnimated − boolean, turn on/off animation
isAnimated − boolean, turn on/off animation
As we're going to use accordion, We've updated app.module.ts to use AccordionModule as in ngx-bootstrap Environment Setup chapter.
Update test.component.html to use the accordion.
test.component.html
<accordion>
   <accordion-group heading="Open By Default" [isOpen]="open">
      <p>Open By Default</p>
   </accordion-group>
   <accordion-group heading="Disabled" [isDisabled]="disabled">
      <p>Disabled</p>
   </accordion-group>
   <accordion-group heading="with isOpenChange" (isOpenChange)="log($event)">
      <p>Open Event</p>
   </accordion-group>
</accordion>
Update test.component.ts for corresponding variables and methods.
test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
   open: boolean = true;
   disabled: boolean = true;
   constructor() { }
   ngOnInit(): void {
   }
   log(isOpened: boolean){
      console.log(isOpened);
   }
}
Run the following command to start the angular server.
ng serve

Once server is up and running. Open http://localhost:4200 and verify the following output.
 Print
 Add Notes
 Bookmark this page
Number of distinct subsets of a set

07 Apr, 2021
Given an array of n distinct elements, count total number of subsets.Examples:  
Input : {1, 2, 3}
Output : 8
Explanation
the array contain total 3 element.its subset 
are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {3, 1}, {1, 2, 3}.
so the output is 8..
 
We know number of subsets of set of size n is 2n How does this formula work? For every element, we have two choices, we either pick it or do not pick it. So in total we have 2 * 2 * ... (n times) choices which is 2nAlternate explanation is : Number of subsets of size 0 = nC0 Number of subsets of size 1 = nC1 Number of subsets of size 2 = nC2 ....................Total number of subsets = nC0 + nC1 + nC2 + .... + nCn = 2nPlease refer Sum of Binomial Coefficients for details.  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count number of distinct// subsets in an array of distinct numbers#include <bits/stdc++.h>using namespace std; // Returns 2 ^ nint subsetCount(int arr[], int n){    return 1 << n;} /* Driver program to test above function */int main(){    int A[] = { 1, 2, 3 };    int n = sizeof(A) / sizeof(A[0]);     cout << subsetCount(A, n);    return 0;}
// Java program to count number of distinct// subsets in an array of distinct numbers class GFG {         // Returns 2 ^ n    static int subsetCount(int arr[], int n)    {        return 1 << n;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int A[] = { 1, 2, 3 };        int n = A.length;             System.out.println(subsetCount(A, n));    }} // This code is contributed by Prerna Saini.
# Python3 program to count number# of distinct subsets in an# array of distinct numbersimport math # Returns 2 ^ ndef subsetCount(arr, n):     return 1 << n     # driver codeA = [ 1, 2, 3 ]n = len(A)print(subsetCount(A, n)) # This code is contributed by Gitanjali.
// C# program to count number of distinct// subsets in an array of distinct numbersusing System; class GFG {         // Returns 2 ^ n    static int subsetCount(int []arr, int n)    {        return 1 << n;    }         // Driver program    public static void Main()    {        int []A = { 1, 2, 3 };        int n = A.Length;             Console.WriteLine(subsetCount(A, n));    }} // This code is contributed by vt_m.
<?php// PHP program to count// number of distinct// subsets in an array// of distinct numbers // Returns 2 ^ nfunction subsetCount($arr, $n){    return 1 << $n;} // Driver Code$A = array( 1, 2, 3 );$n = sizeof($A);echo(subsetCount($A, $n)); // This code is contributed by Ajit.?>
<script> // JavaScript  program to count number of distinct// subsets in an array of distinct numbers // Returns 2 ^ n    function subsetCount(arr, n)    {        return 1 << n;    }  // Driver code                let A = [ 1, 2, 3 ];        let n = A.length;               document.write(subsetCount(A, n)); </script>
8
 
jit_t
code_hunt
binomial coefficient
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS | border-inline-style Property

18 Mar, 2020
The border-inline-style property is an inbuilt property in CSS which is used to set the individual logical block inline-border-style property values in a single place in the style sheet. It sets the inline border-style top(left), and bottom(right) of the defining border element.
Syntax:
border-inline-style: style;
Property values:
style: This property holds the style of the border dashed, border, dotted, etc.
Below examples illustrate the border-inline-style property in the CSS:Example 1:
<!DOCTYPE html><html>  <head>    <title>CSS | border-inline-style Property</title>    <style>        h1 {            color: green;        }                  div {            background-color: yellow;            width: 220px;            height: 40px;        }                  .one {            border: 5px solid cyan;            border-inline-style: dashed;            background-color: purple;        }    </style></head>  <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | border-inline-style Property</b>        <br><br>        <div class="one">A Computer Science Portal</div>    </center></body>  </html>                    
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <title>CSS | border-inline-style Property</title>    <style>        h1 {            color: green;        }                  div {            background-color: yellow;            width: 220px;            height: 40px;        }                  .one {            border: 5px dotted cyan;            border-inline-style: solid;            background-color: purple;        }    </style></head>  <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | border-inline-style Property</b>        <br><br>        <div class="one">A Computer Science Portal</div>    </center></body>  </html>                    
Output:
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-style#:~:text=The%20border%2Dinline%2Dstyle%20CSS,%2C%20directionality%2C%20and%20text%20orientation.
Supported Browsers: The browser supported by border-inline-style property are listed below:
Firefox
Opera
Edge
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap size() Method in Java

26 Nov, 2018
The java.util.HashMap.size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.
Syntax:
Hash_Map.size()
Parameters: The method does not take any parameters.
Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.
Below programs illustrates the working of java.util.HashMap.size():Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the size() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();          // Mapping string values to int keys        hash_map.put(10, "Geeks");        hash_map.put(15, "4");        hash_map.put(20, "Geeks");        hash_map.put(25, "Welcomes");        hash_map.put(30, "You");          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Displaying the size of the map        System.out.println("The size of the map is " + hash_map.size());    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The size of the map is 5

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the size() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("Initial Mappings are: " + hash_map);          // Displaying the size of the map        System.out.println("The size of the map is " + hash_map.size());    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The size of the map is 4

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Use enumerate() and zip() together in Python

28 Nov, 2021
In this article, we will discuss how to use enumerate() and zip() functions in python.
Python enumerate() is used to convert into a list of tuples using the list() method.
Syntax:
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is  to be started, by default it is 0
Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. 
Syntax:
zip(*iterators) 
Using Both, we can iterate two/more lists/objects by using enumerate and zip functions at a time.
Syntax:
enumerate(zip(list1,list2,.,list n))
We can iterate this in for loop.
Syntax:
for var1,var2,.,var n in enumerate(zip(list1,list2,..,list n))
where,
list1,list2 ,. are the input lists
var1 , var2,... are the iterators to iterate the lists
Example: Using enumerate() and zip() together in Python
Python3
# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']  # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata']  # create a list of marksmarks = [78, 100, 97, 89, 80]  # use enumerate() and zip() function# to iterate the listsfor i, (names, subjects, marks) in enumerate(zip(names, subjects, marks)):    print(i, names, subjects, marks)
Output:
0 sravan java 78
1 bobby python 100
2 ojaswi R 97
3 rohith cpp 89
4 gnanesh bigdata 80
We can also do this by using tuple(t)
Syntax:
for i, t in enumerate(zip(names, subjects,marks))
Its returns the data in the tuple format
Example: Using enumerate() and zip() together in Python
Python3
# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']  # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata']  # create a list of marksmarks = [78, 100, 97, 89, 80]  # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)):    print(i, t)
Output:
0 ('sravan', 'java', 78)
1 ('bobby', 'python', 100)
2 ('ojaswi', 'R', 97)
3 ('rohith', 'cpp', 89)
4 ('gnanesh', 'bigdata', 80)
we can also use t[index] in the above approach to get output
Example: Using enumerate() and zip() together in Python
Python3
# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh']  # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata']  # create a list of marksmarks = [78, 100, 97, 89, 80]  # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)):    print(i, t[0], t[1], t[2])
Output:
0 sravan java 78
1 bobby python 100
2 ojaswi R 97
3 rohith cpp 89
4 gnanesh bigdata 80
Picked
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Pandas – Display all the column names in a DataFrame

To display only the column names in a DataFrame, use dataframe.columns.
Import the required library with an alias −
import pandas as pd;
Following is the DataFrame −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
   }
)
Display the column names with dataframe.columns. Following is the complete code −
import pandas as pd;

# create a DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
   }
)

print"DataFrame ...\n",dataFrame

# get all the column names
print"\n Display all the column names ...\n",dataFrame.columns
This will produce the following output −
DataFrame ...
       Car        Place  Units
0      BMW       Delhi    100
1     Audi   Bangalore    150
2      BMW   Hyderabad     50
3    Lexus  Chandigarh    110
4    Tesla        Pune     90
5    Lexus      Mumbai    120
6  Mustang      Jaipur     80

Display all the column names ...
Index([u'Car', u'Place', u'Units'], dtype='object')
POST method – Python requests

22 Sep, 2021
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make POST request to a specified URL using requests.post() method. Before checking out the POST method, let’s figure out what a POST request is –  
POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form.  
Python’s requests module provides in-built method called post() for making a POST request to a specified URI.Syntax – 
requests.post(url, params={key: value}, args)
Example – Let’s try making a request to httpbin’s APIs for example purposes.  
Python3
import requests # Making a POST requestr = requests.post('https://httpbin.org / post', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.json())
save this file as request.py and through terminal run,  
python request.py
Output –
 
It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST. 
Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query.
POST requests are never cached
POST requests do not remain in the browser history.
sooda367
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How to sort a Scala Map by key

13 Aug, 2019
Map is same as dictionary which holds key:value pairs. In this article, we will learn how to sort a Scala Map by key. We can sort the map by key, from low to high or high to low, using sortBy.Syntax :
mapName.toSeq.sortBy(_._1):_*
Let’s try to understand it with better example.Example #1:
// Scala program to sort given map by keyimport scala.collection.immutable.ListMap  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a map         val mapIm = Map("Zash" -> 30,                         "Jhavesh" -> 20,                         "Charlie" -> 50)                                   // Sort map by key        val res = ListMap(mapIm.toSeq.sortBy(_._1):_*)        println(res)    } } 
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)

Example #2:
// Scala program to sort given map by keyimport scala.collection.immutable.ListMap  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a map         val mapIm = Map("Zash" -> 30,                         "Jhavesh" -> 20,                         "Charlie" -> 50)                   // reverse map in ascending order        val res = ListMap(mapIm.toSeq.sortWith(_._1 < _._1):_*)        println(res)    } } 
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)

Example #3:
// Scala program to sort given map by keyimport scala.collection.immutable.ListMap  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a map         val mapIm = Map("Zash" -> 30,                         "Jhavesh" -> 20,                         "Charlie" -> 50)                   // reverse map in descending order        val res = ListMap(mapIm.toSeq.sortWith(_._1 > _._1):_*)        println(res)    } } 
Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Enumeration in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
Inheritance in Scala
R – Repeat loop

21 Apr, 2020
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found.
Repeat loop, unlike other loops, doesn’t use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true. An infinite loop in R can be created very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'.
Syntax:
repeat { 
   commands 
   if(condition) {
      break
   }
}
Flowchart:
Example 1:
# R program to illustrate repeat loop  result <- c("Hello World")i <- 1  # test expression repeat {     print(result)        # update expression    i <- i + 1        # Breaking condition   if(i >5) {      break   }}
Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
Example 2:
# R program to illustrate repeat loop  result <- 1i <- 1  # test expression repeat {     print(result)        # update expression    i <- i + 1   result = result + 1     # Breaking condition   if(i > 5) {      break   }}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to convert List of Integer to List of String

23 Jan, 2020
Given a List of Integers. The task is to convert them to List of Strings.
Examples:
Input: [1, 12, 15, 21, 131]
Output: ['1', '12', '15', '21', '131']

Input: [0, 1, 11, 15, 58]
Output: ['0', '1', '11', '15', '58']

Method 1: Using map()
# Python code to convert list of # string into sorted list of integer     # List initialization list_int = [1, 12, 15, 21, 131]    # mapping list_string = map(str, list_int)     # Printing sorted list of integers print(list(list_string))
Output:
['1', '12', '15', '21', '131']

Example 2: Using list comprehension
# Python code to convert list of  # string into sorted list of integer     # List initialization list_string = [1, 12, 15, 21, 131]    # Using list comprehension output = [str(x) for x in list_string]    # Printing output print(output)
Output:
['1', '12', '15', '21', '131']

Method 3: Using iteration
# Python code to convert list of # string into sorted list of integer     # List initialization list_string = [1, 12, 15, 21, 131]        list_int = []# using iteration and sorted() for i in list_string:    list_int.append(i)    # printing output print(list_int) 
Output:
['1', '12', '15', '21', '131']

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Getting frequency counts of a columns in Pandas DataFrame

28 Dec, 2018
Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways:
Method #1: Using Series.value_counts()
This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequency counts of values in one column.
# importing pandas as pdimport pandas as pd  # sample dataframedf = pd.DataFrame({'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g',                         'bar', 'bar', 'foo', 'bar'],                  'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] })  # frequency count of column Acount = df['A'].value_counts()print(count)
Output: Method #2: Using GroupBy.count()
This method can be used to count frequencies of objects over single columns. After grouping a DataFrame object on one column, we can apply count() method on the resulting groupby object to get a DataFrame object containing frequency count.
# importing pandas as pdimport pandas as pd  # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g',                                'bar', 'bar', 'foo', 'bar'],                   'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] })  # Multi-column frequency countcount = df.groupby(['A']).count()print(count)
Output: Method #3: Using GroupBy.size()
This method can be used to count frequencies of objects over single or multiple columns. After grouping a DataFrame object on one or more columns, we can apply size() method on the resulting groupby object to get a Series object containing frequency count.
# importing pandas as pdimport pandas as pd  # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g',                                 'bar', 'bar', 'foo', 'bar'],                   'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] })  # Multi-column frequency countcount = df.groupby(['A', 'B']).size()print(count)
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Find All Roots of a Quadratic Equation

A quadratic equation is in the form ax2 + bx + c. The roots of the quadratic equation are given by the following formula −
There are three cases −
b2 < 4*a*c - The roots are not real i.e. they are complex
b2 = 4*a*c - The roots are real and both roots are the same.
b2 > 4*a*c - The roots are real and both roots are different
The program to find the roots of a quadratic equation is given as follows.
#include<iostream>
#include<cmath>
using namespace std;
int main() {
   int a = 1, b = 2, c = 1;
   float discriminant, realPart, imaginaryPart, x1, x2;
   if (a == 0) {
      cout << "This is not a quadratic equation";
   }else {
      discriminant = b*b - 4*a*c;
      if (discriminant > 0) {
         x1 = (-b + sqrt(discriminant)) / (2*a);
         x2 = (-b - sqrt(discriminant)) / (2*a);
         cout << "Roots are real and different." << endl;
         cout << "Root 1 = " << x1 << endl;
         cout << "Root 2 = " << x2 << endl;
      } else if (discriminant == 0) {
         cout << "Roots are real and same." << endl;
         x1 = (-b + sqrt(discriminant)) / (2*a);
         cout << "Root 1 = Root 2 =" << x1 << endl;
      }else {
         realPart = (float) -b/(2*a);
         imaginaryPart =sqrt(-discriminant)/(2*a);
         cout << "Roots are complex and different." << endl;
         cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<end;
         cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<end;
      }
   }
   return 0;
}
Roots are real and same.
Root 1 = Root 2 =-1
In the above program, first the discriminant is calculated. If it is greater than 0, then both the roots are real and different.
This is demonstrated by the following code snippet.
if (discriminant > 0) {
   x1 = (-b + sqrt(discriminant)) / (2*a);
   x2 = (-b - sqrt(discriminant)) / (2*a);
   cout << "Roots are real and different." << endl;
   cout << "Root 1 = " << x1 << endl;
   cout << "Root 2 = " << x2 << endl;
}
If the discriminant is equal to 0, then both the roots are real and same. This is demonstrated by the following code snippet.
else if (discriminant == 0) {
   cout << "Roots are real and same." << endl;
   x1 = (-b + sqrt(discriminant)) / (2*a);
   cout << "Root 1 = Root 2 =" << x1 << endl;
}
If the discriminant is less than 0, then both the roots are complex and different. This is demonstrated by the following code snippet.
else {
   realPart = (float) -b/(2*a);
   imaginaryPart =sqrt(-discriminant)/(2*a);
   cout << "Roots are complex and different." << endl;
   cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
   cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}
How to Read Text File Into List in Python? - GeeksforGeeks

19 Dec, 2021
In this article, we are going to see how to read text files into lists in Python.
File for demonstration:
We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line(‘/n’) with ‘ ‘ and split the text further when ‘.’ is seen using the split() and replace() functions. 
read(): The read bytes are returned as a string. Reads n bytes, or the full file if no n is given.
Syntax: fileobject.read(size)
split(): The split() method creates a list from a string. The separator can be specified; the default separator is any whitespace.
Syntax: string.split(separator, maxsplit)
replace(): The replace() method substitutes one phrase for another.
Syntax: string.replace(previous_value, value_to_be_replaced_with, count)
Code:
Python3
# opening the file in read modemy_file = open("file1.txt", "r")  # reading the filedata = my_file.read()  # replacing end of line('/n') with ' ' and# splitting the text it further when '.' is seen.data_into_list = data.replace('\n', ' ').split(".")  # printing the dataprint(data_into_list)my_file.close()
Output:
['Hello geeks Welcome to geeksforgeeks']
The same process as before but we don’t replace any string here.
Python3
# opening the file in read modemy_file = open("file1.txt", "r")  # reading the filedata = my_file.read()  # replacing end splitting the text # when newline ('\n') is seen.data_into_list = data.split("\n")print(data_into_list)my_file.close()
Output:
['Hello geeks', 'Welcome to geeksforgeeks']
Picked
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Shuffle or Randomize a list in Java

To shuffle a list in Java, the code is as follows −
 Live Demo
import java.util.*;
public class Demo{
   public static void main(String[] args){
      ArrayList<String> my_list = new ArrayList<String>();
      my_list.add("Hello");
      my_list.add(",");
      my_list.add("this");
      my_list.add("is");
      my_list.add("a");
      my_list.add("sample");
      System.out.println("The original list is : \n" + my_list);
      Collections.shuffle(my_list);
      System.out.println("\n The shuffled list is : \n" + my_list);
   }
}
The original list is :
[Hello, ,, this, is, a, sample]
The shuffled list is :
[a, is, ,, Hello, this, sample]
A class named Demo contains the main function. Here, an array list is defined and elements are
added to the array list with the help of the ‘add’ function. The original list is printed, and then the
‘shuffle’ function is called on this array list. This way, the elements in the list will be shuffled and
then printed on the screen.
How to create an empty DataFrame in R ? - GeeksforGeeks

07 Apr, 2021
In this article, we are going to see how to create an empty DataFrame in R Programming Language. An empty data frame corresponds to the tabular structure where the axes are of length 0, that is it does not contain any data items.
Method 1: We first create a matrix with both rows and columns and then convert it to a data frame
A data frame and matrix are easily inter-convertible to each other, we first create a matrix with both rows and columns equivalent to 0 and then convert it to a data frame. The dimensions of the equivalent data frame are 0. Time complexity incurred in the creation of an empty data frame is O(1), since a constant time is required. 
R
# creating a matrix with 0 rows # and columns mat = matrix(ncol = 0, nrow = 0)  # converting the matrix to data # framedf=data.frame(mat)print ("Data Frame")print (df)  # check for the dimensions of data # frameprint("Dimensions of data frame")dim(df)
Output
[1] "Data Frame"
data frame with 0 columns and 0 rows
[1] "Dimensions of data frame"
[1] 0 0
The data frame can also be created using this method, without specifying the column types. Naming the columns of a data frame is also optional. An empty vector can be passed as an argument in the data.frame method. 
R
# declaring an empty data frame with 5# columns and null entriesdf = data.frame(matrix(  vector(), 0, 5, dimnames=list(c(), c("C1","C2","C3","C4","C5"))),                stringsAsFactors=F)  # printing the empty data frameprint ("Empty dataframe")print (df)
Output
[1] "Empty dataframe"
[1] C1 C2 C3 C4 C5
<0 rows> (or 0-length row.names)
Method 2: Assign the column with the empty vectors
An empty data frame can also be created with or without specifying the column names and column types to the data values contained within it. data.frame() method can be used to create a data frame, and we can assign the column with the empty vectors. Column type checking with zero rows is supported by the data frames, where in we define the data type of each column prior to its creation. 
R
# declaring an empty data framedf <- data.frame(Col1 = double(),                 Col2 = integer(),                 Col3 = character(),                 stringsAsFactors = FALSE)  # print the data framestr(df)
Output
'data.frame': 0 obs. of  3 variables:
$ Col1: num
$ Col2: int
$ Col3: chr 
Column 1 of the data frame can support numeric values, Column 2 can support integer values, and Column 3 as character variable values.
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to concatenate column values and create a new column in an R data frame?

Sometimes we want to combine column values of two columns to create a new column. This is mostly used when we have a unique column that maybe combined with a numerical or any other type of column. Also, we can do this by separating the column values that is going to be created with difference characters. And it can be done with the help of apply function.
Consider the below data frame −
 Live Demo
> ID<-1:20
> Country<-
sample(c("Russia","USA","China","Canada","UK","India","Nepal"),20,replace=TRUE)
> df1<-data.frame(ID,Country)
> df1
 ID Country
1 1 UK
2 2 UK
3 3 India
4 4 USA
5 5 USA
6 6 UK
7 7 Nepal
8 8 Russia
9 9 Nepal
10 10 China
11 11 UK
12 12 Nepal
13 13 Canada
14 14 USA
15 15 Russia
16 16 UK
17 17 China
18 18 USA
19 19 China
20 20 Russia
Creating a new column of ID and Country −
> df1$ID_with_Country<-apply(df1,1,paste,collapse="")
> df1
 ID Country ID_with_Country
1 1    UK       1UK
2 2    UK       2UK
3 3   India    3India
4 4    USA     4USA
5 5   USA       5USA
6 6    UK       6UK
7 7    Nepal  7Nepal
8 8   Russia  8Russia
9 9   Nepal    9Nepal
10 10 China    10China
11 11  UK       11UK
12 12 Nepal    12Nepal
13 13 Canada 13Canada
14 14  USA    14USA
15 15 Russia    15Russia
16 16  UK       16UK
17 17 China    17China
18 18 USA       18USA
19 19 China    19China
20 20 Russia    20Russia
Let’s have a look at another example −
 Live Demo
> Class<-LETTERS[1:20]
> Rank<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(Class,Rank)
> df2
 Class Rank
1 A    2
2 B    4
3 C    4
4 D    6
5 E    7
6 F    10
7 G    10
8 H    5
9 I    9
10 J   6
11 K   1
12 L    8
13 M    10
14 N    7
15 O    5
16 P    7
17 Q    6
18 R    1
19 S    10
20 T    3
> df2$Class_Rank<-apply(df2,1,paste,collapse="_")
> df2
 Class Rank Class_Rank
1    A 2       A_ 2
2    B 4       B_ 4
3    C 4       C_ 4
4    D 6       D_ 6
5    E 7       E_ 7
6    F 10      F_10
7    G 10       G_10
8    H 5       H_ 5
9    I 9       I_ 9
10    J 6       J_ 6
11    K 1       K_ 1
12    L 8       L_ 8
13    M 10       M_10
14    N 7       N_ 7
15    O 5       O_ 5
16    P 7       P_ 7
17    Q 6       Q_ 6
18    R 1       R_ 1
19    S 10       S_10
20    T 3       T_ 3
Java Program to get Milli seconds from Instant

Create an Instant and get an Instant using milliseconds passed as parameter from the epoch of 1970-01-
01T00:00:00Z. This is done using ofEpochMilli():
Instant instant = Instant.ofEpochMilli(342627282920l);
Now, get the Epoch milliseconds from Instant:
instant. toEpochMilli();
import java.time.Instant;
public class Demo {
   public static void main(String[] args) {
      Instant instant = Instant.ofEpochMilli(1262347200000l);
      long res = instant.toEpochMilli();
      System.out.println(res);
   }
}
1262347200000
Tryit Editor v3.7

Tryit: Bad background image for page
Powershell - Rename File

Rename-Item cmdlet is used to rename a File by passing the path of the file to be renamed and target name.
In this example, we'll rename a folder D:\Temp\Test\test.txt to test1.txt
Type the following command in PowerShell ISE Console
Rename-Item D:\temp\Test\test.txt test1.txt
You can see the test.txt renamed to test1.txt in Windows explorer.

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
How to change the color of gridlines of a ggplot2 graph in R?

To change the color of gridlines of a ggplot2 graph in R, we can use theme function with
panel.grid.major and panel.grid.minor arguments where we can set the minor and major
gridlines color of the plot panel to desired color.
To understand how it can be done, check out the below Example.
Following snippet creates a sample data frame −
x<-sample(0:9,20,replace=TRUE)
y<-sample(0:9,20,replace=TRUE)
df<-data.frame(x,y)
df
The following dataframe is created
  x y
1  5 7
2  7 5
3  1 5
4  5 9
5  6 4
6  2 5
7  4 2
8  7 7
9  6 7
10 7 2
11 1 3
12 2 9
13 7 0
14 6 9
15 5 7
16 6 6
17 5 9
18 5 7
19 4 5
20 4 4
To load ggplot2 package and create scatterplot between x and y on the above created
data frame, add the following code to the above snippet −
x<-sample(0:9,20,replace=TRUE)
y<-sample(0:9,20,replace=TRUE)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
If you execute all the above given snippets as a single program, it generates the following Output −
To create scatterplot between x and y with red color gridlines on the above created data
frame, add the following code to the above snippet −
x<-sample(0:9,20,replace=TRUE)
y<-sample(0:9,20,replace=TRUE)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+theme(panel.grid.major=element_line(colour="re
d"),panel.grid.minor=element_line(colour="red"))
If you execute all the above given snippets as a single program, it generates the following Output −
Apply a Function over a List of elements in R Programming - lapply() Function - GeeksforGeeks

16 Dec, 2021
lapply() function in R Programming Language is used to apply a function over a list of elements. 
Syntax: lapply(list, func)
Parameters: 
list: list of elements
func: operation to be applied
R
# R program to illustrate# lapply() function   # Creating a matrixA = matrix(1:9, 3, 3)   # Creating another matrixB = matrix(10:18, 3, 3)    # Creating a listmyList = list(A, B)   # applying lapply()determinant = lapply(myList, det)print(determinant)
Output: 
[[1]]
[1] 0

[[2]]
[1] 5.329071e-15
R
# R program to illustrate# lapply() function   # Creating a matrixA = matrix(1:9, 3, 3)   # Creating another matrixB = matrix(10:18, 3, 3)    # Creating a listmyList = list(A, B)   # applying lapply()sum = lapply(myList, sum)print(sum)
Output: 
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1]  28  80 162
[1]   6 120 504
kumar_satyam
R List-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
Java Program to create DefaultTableModel from two dimensional array

The DefaultTableModel is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. At first create a two dimensional array for rows and columns −
DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
   { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" },
   { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" },
   { "Germany", "Europe" }, { "France", "Europe" }
 },
new Object[] { "Country", "Continent" });
Above, “Country” and “Continent” are the columns. Now, set the above set of rows and columns to JTable −
JTable table = new JTable(tableModel);
The following is an example to create DefaultTableModel from two dimensional array −
package my;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
         { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" },
         { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" },
         { "Germany", "Europe" }, { "France", "Europe" }
      },
      new Object[] { "Country", "Continent" });
      JTable table = new JTable(tableModel);
      Font font = new Font("Verdana", Font.PLAIN, 12);
      table.setFont(font);
      table.setRowHeight(30);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}
How do you test if a value is equal to NaN in Javascript?

The global NaN property in javascript is a value representing Not-A-Number. It is the returned value
When Math functions fail (Math.sqrt(-500))
When a function trying to parse a number fails (parseFloat("test"))
NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value.
To test if a value is NaN, we must use Number.isNaN method.
let a = Math.sqrt(-500);
console.log(Number.isNaN(a))
true
Note − isNaN() and Number.isNaN(): the former returns true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number, while the latter will return true only if the value is currently NaN.
isNaN('hello world');
Number.isNaN('hello world');
true
false
\cal - Tex Command

\cal - turns on calligraphic mode;  only affects uppercase letters and digits.
{ \cal ... }
\cal command turns on calligraphic mode; only affects uppercase letters and digits.

\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ

ABCDEFGHIJKLMNOPQRSTUVWXYZ


\cal 0123456789

0123456789


\cal abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


{\cal AB}AB

ABAB


\cal AB \rm AB

ABAB


\cal{AB}CD

ABCD



\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ

ABCDEFGHIJKLMNOPQRSTUVWXYZ


\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ
\cal 0123456789

0123456789


\cal 0123456789
\cal abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


\cal abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


abcdefghijklmnopqrstuvwxyz
{\cal AB}AB

ABAB


{\cal AB}AB
\cal AB \rm AB

ABAB


\cal AB \rm AB
\cal{AB}CD

ABCD


\cal{AB}CD

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page