code-rag-bench/online-tutorials huggingface dataset:
Python - Calculate the minimum of column values of a Pandas DataFrame

To get the minimum of column values, use the min() function. At first, import the required Pandas library −
import pandas as pd
Now, create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] }
)
Finding the minimum value of a single column “Units” using min() −
print"Minimum Units from DataFrame1 = ",dataFrame1['Units'].min()

In the same way, we have calculated the minimum value from the 2nd DataFrame.
Following is the complete code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] }
)

print"DataFrame1 ...\n",dataFrame1

# Finding minimum value of a single column "Units"
print"Minimum Units from DataFrame1 = ",dataFrame1['Units'].min()

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],"Price": [8000, 500, 3000, 1500, 3000, 4000]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# Finding minimum value of a single column "Price"
print"Minimum Price from DataFrame2 = ",dataFrame2['Price'].min()
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3    Tesla      80
4  Bentley     110
5   Jaguar      90
Minimum Units from DataFrame1 = 80

DataFrame2 ...
   Price    Product
0   8000         TV
1    500   PenDrive
2   3000  HeadPhone
3   1500   EarPhone
4   3000        HDD
5   4000        SSD
Minimum Price from DataFrame2 = 500
Explain project operation in relational algebra (DBMS)?

Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types −
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example − Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows −
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Select, project, rename comes under unary operation (operate on one table).
It displays the specific column of a table. It is denoted by pie (∏). It is a vertical subset of the original relation. It eliminates duplicate tuples.
The syntax is as follows −
∏regno(student)
Consider the student table:
To display regno column of student table, we can use the following command −
∏regno(student)
To display branch, section column of student table, use the following command −
∏branch,section(student)
The result is as follows −
To display regno, section of ECE students, use the following command −
∏regno,section(σbranch=ECE(student))
Note: Conditions can be written in select operation but not in projection operation.
Consider the employee table to know more about projection.
If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp).
If no condition is specified in the query then, Π empid, ename, salary, address, dno (emp).
If condition is specified then, the composition of the select and projection is as follows −
If condition is specified then, the composition of the select and projection is as follows −
∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp)
How to set the opacity level for an element with JavaScript?

Use the opacity property in JavaScript to set the opacity level. You can try to run the following code to set the opacity level for an element with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            width: 450px;
            background-color: gray;
         }
      </style>
   </head>
   <body>
      <p>Click below to set Opacity.</p>
      <button type="button" onclick="display()">Set Opacity</button>
      <div id="box">
         <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>
         <p>This is a div. This is a div. This is a div. This is a div. This is a div.</p>
      </div>
      <br>
      <script>
         function display() {
            document.getElementById("box").style.opacity = "0.5";
         }
      </script>
   </body>
</html>
How to get the square root of a number in JavaScript?

To get the square root, use the Math.sqrt() method. This method returns the square root of a number. If the value of a number is negative, sqrt returns NaN.
You can try to run the following code to get the square root of a number −
<html>
   <head>
      <title>JavaScript Math sqrt() Method</title>
   </head>
   <body>
      <script>
         var value = Math.sqrt( 0.5 );
         document.write("First Value : " + value );

         var value = Math.sqrt( 49 );
         document.write("<br />Second Value : " + value );
      </script>
   </body>
</html>
Concatenating Objects in R Programming – combine() Function

31 Aug, 2020
In R programming, coercion function c() and combine() function are similar to each other but are different in a way. combine() functions acts like c() and unlist() functions but uses consistent dplyr coercion rules. Moreover, combine() function is used to combine factors in R programming. In this article, we’ll see the implementation of combine() and c() function with same outputs and different outputs on the same operation.
Syntax: combine(x, y, ...)
Parameters:x, y, .... are vectors to combine
Example 1:
In this example, we’ll see the same output of both these functions on same operation.
# Package requiredinstall.packages("dplyr")  # Load the librarylibrary(dplyr)  x <- c(1, 2, 3)y <- c(4, 5, 6)  # Using c() functioncat("Using c() function:\n")c(x, y)  cat("\n")# Using combine() functioncat("Using combine() function:\n")combine(x, y)
Output:
Using c() function:
[1] 1 2 3 4 5 6

Using combine() function:
[1] 1 2 3 4 5 6
Example 2:In this example, we’ll see the different outputs of both these functions on the same operation.
library(dplyr)  x <- factor(c("a", "a", "b", "c"))y <- factor(c("b", "a", "c", "b"))  # Using c() functioncat("Using c() function:\n")c(x, y)  # Using combine() functioncat("\n")cat("Using combine() function:\n")combine(x, y)
Output:
Using c() function:
[1] 1 1 2 3 2 1 3 2

Using combine() function:
[1] a a b c b a c b
Levels: a b c
Akanksha_Rai
R DataFrame-Function
R List-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Collect.js | count() Function

05 Jun, 2020
The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax: 
data.count()

Parameters: This function does not accept any parameterReturn Value:  Returns the count of the element in that collection. 
Below examples illustrate the count() function in collect.jsExample 1: 
Javascript
// It is used to import collect.js libraryconst collect = require('collect.js');  const num = [0 , 1 , 2 , 3 , 4, 5 , 6, 7, 8, 9]; const data = collect(num);const total = data.count();  console.log('Total number of elements are:', {total});
Output:
Total number of elements are: { total: 10 }

Example 2:
Javascript
// It is used to import collect.js libraryconst collect = require('collect.js');  const collection = collect([1, 2, 3, 4]);const x = collection.count();  console.log(`Total number of elements are : ${x}`);
Output:
Total number of elements are : 4
Reference: https://collect.js.org/api/count.html
Collect.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var and val in Kotlin

03 Jun, 2020
var and val are both used to declare variables in Kotlin language. However, there are some key differences between them:
It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime.Example:
fun main() {   var marks = 10   println("Previous marks is " + marks)   marks = 30   println("New marks " + marks) }
Output :
Previous marks is 10
New marks 30
The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only.
Example 1:
fun main(){    val marks = 10     println("Previous marks is " + marks)    marks = 30     println("new marks " + marks)}
Output:
Val cannot be reassigned

Example 2:
// Changing values of val objectfun main(){    val book = Book("Java", 1000)    println(book)    book.name = "Kotlin"     println(book)}data class Book(var name : String = "",                var price : Int = 0)
output:
Book(name=Java, price=1000)
Book(name=Kotlin, price=1000)

Articles
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
Difference Between Object And Class
SQL | DROP, TRUNCATE
Implementation of LinkedList in Javascript
Services in Android with Example
Bottom Navigation Bar in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Android RecyclerView in Kotlin
How to skip a particular test method in TestNG?

We can skip a particular test method in TestNG. To overlook a particular test method from execution in TestNG enabled helper attribute is used. This attribute has to be set to false to overlook a test method from execution. Code Implementation of Java class file.
@Test(enabled=false)
public void verifyRepay(){
   System.out.println("Repayment successful");
}
@Test
public void Login(){
   System.out.println("Login is successful ");
}
@Test
public verifyHistory(){
   System.out.println ("History verification is successful");
}
Here the verifyRepay() method shall be overlooked during execution.
Executing SQL Statements from a Text File on MySQL Client

Let us understand how SQL statements can be executed from a text file on the MySQL client. The mysql client is generally used in interactive way. Let us see an example of the same −
shell> mysql db_name
It is also possible to put the SQL statements in a file and then tell mysql to read the input from that specific file. To do this, a text file text_file is first created.
This text file would contain the statements that need to be executed. Let us take an example to understand the same −
shell> mysql db_name < text_file
If a USE db_name statement is placed as the first statement in the text file, it is unnecessary to specify the database name on the command line. Let us take an example to understand the same −
shell> mysql < text_file
If mysql is already running, an SQL script file can be executed using the source command or \. command. Let us take an example to understand the same −
mysql> source file_name
mysql> \. file_name
Sometimes the user may want the script to display progress information to them. For this insert statements like that given below can be used −
SELECT '<info_to_display>' AS ' ';
<info_to_display>
The mysql can also be invoked with the help of --verbose option. This causes every statement to be displayed before the result it produces.
The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files.
The mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files.
Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error.
Before this functionality, they were read and sent over to the server, thereby resulting in a syntax error.
The present of a BOM doesn’t cause mysql to change its default character set.
The present of a BOM doesn’t cause mysql to change its default character set.
To do this, mysql can be invoked with an option like --default-character-set=utf8.
To do this, mysql can be invoked with an option like --default-character-set=utf8.
Accessing Values of Lists in Python

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.
 Live Demo
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Convert Unicode to UTF-8 in Java

Before moving onto their conversions, let us learn about Unicode and UTF-8.
Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \u0000 and the highest value is \uFFFF.
UTF-8 is a variable width character encoding. UTF-8 has the ability to be as condensed as ASCII but can also contain any Unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4.
In order to convert Unicode to UTF-8 in Java, we use the getBytes() method. The getBytes() method encodes a String into a sequence of bytes and returns a byte array.
Declaration - The getBytes() method is declared as follows.
public byte[] getBytes(String charsetName)
where charsetName is the specific charset by which the String is encoded into an array of bytes.
Let us see a program to convert Unicode to UTF-8 in Java using the getBytes() method.
 Live Demo
public class Example {
   public static void main(String[] args) throws Exception {
      String str1 = "\u0000";
      String str2 = "\uFFFF";
      byte[] arr = str1.getBytes("UTF-8");
      byte[] brr = str2.getBytes("UTF-8");
      System.out.println("UTF-8 for \\u0000");
      for(byte a: arr) {
         System.out.print(a);
      }
      System.out.println("\nUTF-8 for \\uffff" );
      for(byte b: brr) {
         System.out.print(b);
      }
   }
}
UTF-8 for \u0000
0
UTF-8 for \uffff
-17-65-65
Let us understand the above program. We have created two Strings.
String str1 = "\u0000";
String str2 = "\uFFFF";
String str1 is assigned \u0000 which is the lowest value in Unicode. String str2 is assigned \uFFFF which is the highest value in Unicode.
To convert them into UTF-8, we use the getBytes(“UTF-8”) method. This gives us an array of bytes as follows −
byte[] arr = str1.getBytes("UTF-8");
byte[] brr = str2.getBytes("UTF-8");
Then to print the byte array, we use an enhanced for loop as follows −
for(byte a: arr) {
   System.out.print(a);
}
for(byte b: brr) {
   System.out.print(b);
}
How to set background color in HTML?

To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color. The bgcolor attribute deprecated in HTML5.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to set the background color in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Backgorund Color</title>
   </head>
   <body style="background-color:grey;">
      <h1>Products</h1>
      <p>We have developed more than 10 products till now.</p>
   </body>
</html>
How to pass a lambda expression as a method parameter in Java?

A lambda expression is an anonymous or unnamed method in Java. It doesn't execute on its own and used to implement methods that are declared in a functional interface. If we want to pass a lambda expression as a method parameter in java, the type of method parameter that receives must be of functional interface type.
interface Algebra {
   int operate(int a, int b);
}
enum Operation {
   ADD, SUB, MUL, DIV
}
public class LambdaMethodArgTest {
   public static void main(String[] args) {
      print((a, b) -> a + b, Operation.ADD);
      print((a, b) -> a - b, Operation.SUB);
      print((a, b) -> a * b, Operation.MUL);
      print((a, b) -> a / b, Operation.DIV);
   }
   static void print(Algebra alg, Operation op) {
      switch (op) {
         case ADD:
            System.out.println("The addition of a and b is: " + alg.operate(40, 20));
            break;
         case SUB:
            System.out.println("The subtraction of a and b is: " + alg.operate(40, 20));
            break;
         case MUL:
            System.out.println("The multiplication of a and b is: " + alg.operate(40, 20));
            break;
         case DIV:
            System.out.println("The division of a and b is: " + alg.operate(40, 20));
            break;
         default:
            throw new AssertionError();
      }
   }
}
The addition of a and b is: 60
The subtraction of a and b is: 20
The multiplication of a and b is: 800
The division of a and b is: 2
How do you click on an element which is hidden using Selenium WebDriver?

We can click on an element which is hidden with Selenium webdriver. The hidden elements are the ones which are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style="display:none;". In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden.
Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method.
First of all, the getElementById method can be used to identify the element. Next to enter text to the field, the value method is used to set value to the field.
executor.executeScript
("document.getElementById('txt').value='Selenium'");
Let’s take an example where there are two buttons Hide and Show. Also there is an edit box below the buttons. Once we click on the Hide button, the edit box disappears from the page.
Now let us enter some text inside the hidden text box.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ElementHidden{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://learn.letskodeit.com/p/practice");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element and click
      driver.findElement(By.id("hide-textbox")).click();
      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // identify element and set value
      j.executeScript ("document.getElementById('displayed-text').value='Selenium';");
      String s = (String) j.executeScript("return document.getElementById('displayed-text').value");
      System.out.print("Value entered in hidden field: " +s);
      driver.close()
   }
}
Python PIL | ImageDraw.Draw.pieslice()

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.pieslice() Same as arc, but also draws straight lines between the end points and the center of the bounding box.
Syntax: PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)
Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the fill.outline – Color to use for the outline.
Returns: An Image object in pieslice shape.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw   w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]   # creating new Image objectimg = Image.new("RGB", (w, h))   # create pieslice imageimg1 = ImageDraw.Draw(img)  img1.pieslice(shape, start = 50, end = 250, fill ="# ffff33", outline ="red")img.show()
Output:
Another Example: Here we use different colour for filling.
   # importing image object from PILimport mathfrom PIL import Image, ImageDraw   w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]   # creating new Image objectimg = Image.new("RGB", (w, h))   # create pieslice imageimg1 = ImageDraw.Draw(img)  img1.pieslice(shape, start = 50, end = 250, fill ="# 800080", outline ="white")img.show()
Output:
Python-pil
Python
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
Python hasattr() method

05 Jul, 2022
Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python.
Syntax : hasattr(obj, key)
Parameters : 
obj : The object whose which attribute has to be checked.
key : Attribute which needs to be checked.
Returns : Returns True, if attribute is present else returns False. 
Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code.
Python3
# declaring classclass GfG:    name = "GeeksforGeeks"    age = 24  # initializing objectobj = GfG() # using hasattr() to check nameprint("Does name exist ? " + str(hasattr(obj, 'name'))) # using hasattr() to check mottoprint("Does motto exist ? " + str(hasattr(obj, 'motto')))
Output: 
Does name exist ? True
Does motto exist ? False
This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement.
Python3
import time # declaring classclass GfG:    name = "GeeksforGeeks"    age = 24 # initializing objectobj = GfG() # use of hasattr to check mottostart_hasattr = time.time()if(hasattr(obj, 'motto')):    print("Motto is there")else:    print("No Motto") print("Time to execute hasattr : " + str(time.time() - start_hasattr)) # use of try/except to check mottostart_try = time.time()try:    print(obj.motto)    print("Motto is there")except AttributeError:    print("No Motto")print("Time to execute try : " + str(time.time() - start_try))
Output: 
No Motto
Time to execute hasattr : 5.245208740234375e-06
No Motto
Time to execute try : 2.6226043701171875e-06
Result: Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice.
Applications: This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if the other is not present.
kumar_satyam
prachisoda1234
surajkumarguptaintern
Python-Built-in-functions
python-object
Python-OOP
Python
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
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
numpy.random.chisquare() in Python

15 Jul, 2020
With the help of chisquare() method, we can get chi-square distribution by using this method. Mainly we can use this distribution in hypothesis testing.
chi-square distribution
Syntax : numpy.random.chisquare(df, size=None)
Parameters : 
1) df – number of degree of freedom and must be >0.
2) size – Output shape of scalar array.
Return : Return the scalar numpy array.
Example #1 :
In this example we can see that by using chisquare() method, we are able to get the chi-square distribution and return the scalar numpy array by using this method.
Python3
# import chisquareimport numpy as npimport matplotlib.pyplot as plt  # Using chisquare() methodgfg = np.random.chisquare(3, 1000)  count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import chisquareimport numpy as npimport matplotlib.pyplot as plt  # Using chisquare() methodgfg = np.random.chisquare(5, 10000)gfg1 = np.random.chisquare(gfg, 10000)  count, bins, ignored = plt.hist(gfg1, 30, density = True)plt.show()
Output :
Python numpy-Random
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Create a directory in Python
How to remove partial string after a special character in R?

Sometimes we don’t require the whole string to proceed with the analysis, especially when it complicates the analysis or making no sense. In such type of situations, the part of string which we feel that is not necessary can be removed from the complete string. For example, suppose we have a string ID:00001-1 but we don’t want -1 in this string then we can remove it and this can be done with the help of gsub function.
> x1<-c("ID:00001-1","ID:00100-1","ID:00201-4","ID:014700-3","ID:12045-5","ID:00012-2","ID:10078-3")
> gsub("\\-.*","",x1)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x2<-c("ID:00001/1","ID:00100/1","ID:00201/4","ID:014700/3","ID:12045/5","ID:00012/2","ID:10078/3")
> gsub("\\/.*","",x2)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x3<-c("ID:00001_1","ID:00100_1","ID:00201_4","ID:014700_3","ID:12045_5","ID:00012_2","ID:10078_3")
> gsub("\\_.*","",x3)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x4<-c("ID:00001@1","ID:00100@1","ID:00201@4","ID:014700@3","ID:12045@5","ID:00012@2","ID:10078@3")
> gsub("\\@.*","",x4)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x5<-c("ID:00001*1","ID:00100*1","ID:00201*4","ID:014700*3","ID:12045*5","ID:00012*2","ID:10078*3")
> gsub("\\*.*","",x5)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x6<-c("ID:00001#1","ID:00100#1","ID:00201#4","ID:014700#3","ID:12045#5","ID:00012#2","ID:10078#3")
> gsub("\\#.*","",x6)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x7<-c("ID:00001()1","ID:00100()1","ID:00201()4","ID:014700()3","ID:12045()5","ID:00012()2","ID:10078()3")
> gsub("\\().*","",x7)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x8<-c("ID:00001<>1","ID:00100<>1","ID:00201<>4","ID:014700<>3","ID:12045<>5","ID:00012<>2","ID:10078<>3")
> gsub("\\<>.*","",x8)
[1] "ID:00001<>1" "ID:00100<>1" "ID:00201<>4" "ID:014700<>3" "ID:12045<>5" "ID:00012<>2" "ID:10078<>3"
> x9<-c("ID:00001&1","ID:00100&1","ID:00201&4","ID:014700&3","ID:12045&5","ID:00012&2","ID:10078&3")
> gsub("\\&.*","",x9)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
> x10<-c("ID:00001;1","ID:00100;1","ID:00201;4","ID:014700;3","ID:12045;5","ID:00012;2","ID:10078;3")
> gsub("\\;.*","",x10)
[1] "ID:00001" "ID:00100" "ID:00201" "ID:014700" "ID:12045" "ID:00012" "ID:10078"
What is OpenMP?

OpenMP is a set of compiler directives as well as an API for programs written in C, C++, or FORTRAN that provides support for parallel programming in shared-memory environments. OpenMP identifies parallel regions as blocks of code that may run in parallel. Application developers insert compiler directives into their code at parallel regions, and these directives instruct the OpenMP run-time library to execute the region in parallel. The following C program illustrates a compiler directive above the parallel region containing the printf() statement −
#include <omp.h>
#include <stdio.h>
int main(int argc, char *argv[]){
   /* sequential code */
   #pragma omp parallel{
      printf("I am a parallel region.");
   }
   /* sequential code */
   return 0;
}
When OpenMP encounters the directive
#pragma omp parallel
It creates as many threads which are processing cores in the system. Thus, for a dual-core system, two threads are created, for a quad-core system, four are created; and so forth. Then all the threads simultaneously execute the parallel region. When each thread exits the parallel region, it is terminated. OpenMP provides several additional directives for running code regions in parallel, including parallelizing loops.
In addition to providing directives for parallelization, OpenMP allows developers to choose among several levels of parallelism. E.g., they can set the number of threads manually. It also allows developers to identify whether data are shared between threads or are private to a thread. OpenMP is available on several open-source and commercial compilers for Linux, Windows, and Mac OS X systems.
Nagios - Checks and States

Once the host and services are configured on Nagios, checks are used to see if the hosts and services are working as they are supposed to or not. Let us see an example to perform checks on host −
Consider that you have put your host definitions inside host1.cfg file in /usr/local/nagios/etc/objects directory.
cd /usr/local/nagios/etc/objects
gedit host1.cfg

This is how your host definitions look currently −
define host {
   host_name host1
   address 10.0.0.1
}

Now let us add check_interval directive. This directive is used to perform scheduled checks of the hosts for the number you set; by default it is in minutes. Using the definition below, checks on the host will be performed after every 3 minutes.
define host {
   host_name host1
   address 10.0.0.1
   check_interval 3
}

In Nagios, 2 types of checks are performed on hosts and services −
Active Checks
Passive Checks
Active checks are initiated by Nagios process and then run on a regular scheduled basis. The check logic inside Nagios process starts the Active check. To monitor hosts and services running on remote machines, Nagios executes plugins and tells what information to collect. Plugin then gets executed on the remote machine where is collects the required information and sends then back to Nagios daemon. Depending on the status received on hosts and services, appropriate action is taken.
The figure shown below shows an active check −
These are executed on regular intervals, as defined by check_interval and retry_interval.
Passive checks are performed by external processes and the results are given back to Nagios for processing.
Passive checks work as explained here −
An external application checks the status on hosts/services and writes the result to External Command File. When Nagios daemon reads external command file, it reads and sends all the passive checks in the queue to process them later. Periodically when these checks are processed, notifications or alerts are sent depending on the information in check result.
The figure shown below shows a passive check −
Thus, the difference between active and passive check is that active checks are run by Nagios and passive checks are run by external applications.
These checks are useful when you cannot monitor hosts/services on a regular basis.
Nagios stores the status of the hosts and services it is monitoring to determine if they are working properly or not. There would be many cases when the failures will happen randomly and they are temporary; hence Nagios uses states to check the current status of a host or service.
There are two types of states −
Soft state
Hard state
When a host or service is down for a very short duration of time and its status is not known or different from previous one, then soft states are used. The host or the services will be tested again and again till the time the status is permanent.
When max_check_attempts is executed and status of the host or service is still not OK, then hard state is used. Nagios executes event handlers to handle hard states.
The following figure shows soft states and hard states.
 Print
 Add Notes
 Bookmark this page
C - strtok function

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <stdio.h>

char *strtok(char *s, const char *delim) ;

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters spearated by any of the characters that are part of delimiters.
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in separator (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in separator, which becomes the end of the token.
This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
A pointer to the last token found in string.
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
A null pointer is returned if there are no tokens left to retrieve.
#include <stdio.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

It will proiduce following result:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
Tokens in C

Tokens are the smallest elements of a program, which are meaningful to the compiler.
The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc.
Let us begin with Keywords.
Keywords are predefined, reserved words in C and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers.
There are total 32 keywords in C.
Each program element in C programming is known as an identifier. They are used for naming of variables, functions, array etc. These are user-defined names which consist of alphabets, number, underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords are not used as identifiers.
Rules for naming C identifiers −
It must begin with alphabets or underscore.
It must begin with alphabets or underscore.
Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed.
Only alphabets, numbers, underscore can be used, no other special characters, punctuations are allowed.
It must not contain white-space.
It must not contain white-space.
It should not be a keyword.
It should not be a keyword.
It should be up to 31 characters long.
It should be up to 31 characters long.
A string is an array of characters ended with a null character(\0). This null character indicates that string has ended. Strings are always enclosed with double quotes(“ “).
Let us see how to declare String in C language −
char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\0’};
char string[20] = “demo”;
char string [] = “demo”;
Here is an example of tokens in C language,
 Live Demo
#include >stdio.h>
int main() {
   // using keyword char
   char a1 = 'H';
   int b = 8;
   float d = 5.6;
   // declaration of string
   char string[200] = "demodotcom";
   if(b<10)
   printf("Character Value : %c\n",a1);
   else
   printf("Float value : %f\n",d);
   printf("String Value : %s\n", string);
   return 0;
}
Character Value : H
String Value : demodotcom
Code indentation in Lua Programming

Lua codes are not like Python when it comes to indentation. So, most of the code you will write will work even if it falls on another line, and you don’t necessarily need to have the nested code to be intended by a certain tab size.
The code indentation in lua is more about making the code look much better and more readable. If your entire code is on one line or worse, if it is like multiple lines then I am afraid that your code isn’t very readable.
While we can use the code editor’s indentation packages to do the indentation for us, it is still a good idea to use the indentation that Lua provides.
Lua provides us with a script which we can make use of when we want to improve the indentation of our file, and running that script includes several steps and you must be aware of the parameters that you require that will help you increase the code indentation in your file.
Let’s explore why we need the script. Consider the points listed below about the script −
Reduces the Inconsistency of tab sizes.
Handles added tabs done by automatic indentation.
Makes the code look more like a homogeneous appearance.
Removes tab indents and replaces them with spaces.
Standardized indentation at 2 spaces per indent.
Checks that line lengths don't exceed 80 characters.
lua -f codeformat.lua --file myfile.lua --ts 4 --in 4
In the above usage example, the codeformat.lua is the Lua script file that will do all the work for the code indentation for you, the myfile.lua is the file whose indentation you want to improve, the 4 after the --ts flag tells Lua how much tab size you want to keep, and the last 4 tell Lua about the indentation space you want for your file.
Why and how are Python functions hashable?

An object is said to be hashable if it has a hash value that remains the same during its lifetime. It has a __hash__() method and it can be compared to other objects. For this, it needs the __eq__() or __cmp__()method. If hashable objects are equal when compared, then they have same hash value.
Being hashable renders an object usable as a dictionary key and a set member as these data structures use hash values internally.
All immutable built-in objects in python are hashable. Mutable containers like lists and dictionaries are not hashable while immutable container tuple is hashable
Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().
The hash is apparently not necessarily the ID of the function: Consider given lambda function.
m = lambda x: 1
print hash(m)
print id(m)
print m.__hash__()
1265925722
3074942372
1265925722
This shows that lambda functions are hashable
Now let us consider given function f() as follows
def f():pass
print type(f)
print f.__hash__()
print hash(f)
<type 'function'>
1265925978
1265925978
This shows that any function is hashable as it has a hash value that remains same over its lifetime.
How to write a program to copy characters from one file to another in Java?

To copy the contents of one file to other character by character
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFiles {
   public static void main(String[] args) throws IOException {
      //Creating a File object to hold the source file
      File source = new File("D:\\ExampleDirectory\\SampleFile.txt");
      //Creating a File object to hold the destination file
      File destination = new File("D:\\ExampleDirectory\\outputFile.txt");
      //Creating an FileInputStream object
      FileInputStream inputStream = new FileInputStream(source);
      //Creating an FileOutputStream object
      FileOutputStream outputStream = new FileOutputStream(destination);
      //Creating a buffer to hold the data
      int length = (int) source.length();
      byte[] buffer = new byte[length];
      while ((length = inputStream.read(buffer)) > 0) {
         outputStream.write(buffer, 0, length);
      }
      inputStream.close();
      outputStream.close();
      System.out.println("File copied successfully.......");
   }
}
File copied successfully.......
PySpark - Create DataFrame from List - GeeksforGeeks

30 May, 2021
In this article, we are going to discuss how to create a Pyspark dataframe from a list. 
To do this first create a list of data and a list of column names. Then pass this zipped data to spark.createDataFrame() method. This method is used to create DataFrame. The data attribute will be the list of data and the columns attribute will be the list of names.
dataframe = spark.createDataFrame(data, columns)
Example1: Python code to create Pyspark student dataframe from two lists.
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of college data with two listsdata = [["java", "dbms", "python"],         ["OOPS", "SQL", "Machine Learning"]]  # giving column names of dataframecolumns = ["Subject 1", "Subject 2", "Subject 3"]  # creating a dataframedataframe = spark.createDataFrame(data, columns)  # show data framedataframe.show()
Output:
Example 2: Create a dataframe from 4 lists
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of college data with two listsdata = [["node.js", "dbms", "integration"],        ["jsp", "SQL", "trigonometry"],        ["php", "oracle", "statistics"],        [".net", "db2", "Machine Learning"]]  # giving column names of dataframecolumns = ["Web Technologies", "Data bases", "Maths"]  # creating a dataframedataframe = spark.createDataFrame(data, columns)  # show data framedataframe.show()
Output:
Picked
Python-Pyspark
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
time.Round() Function in Golang With Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration ‘d’ to the closest multiple of ‘m’ duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Round(m Duration) Duration

Here, d is the duration of time that will be rounded and m is the closest multiple.
Return value: It returns maximum (or minimum) duration if the outcome surpasses the maximum (or minimum) value that could be stored in a duration. But if m is less than or equal to 0 then it returns unaltered ‘d’.
Example 1:
// Golang program to illustrate the usage of// Round() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration     // of Round method    d, _ := time.ParseDuration("5m7s")      // Prints rounded d    fmt.Printf("Rounded d is : %s",             d.Round(6*time.Second))}
Output:
Rounded d is : 5m6s

Here, ‘d’ is rounded to the closest multiple of m.
Example 2:
// Golang program to illustrate the usage of// Round() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration of Round method    d, _ := time.ParseDuration("3m73.671s")      // Array of m    R := []time.Duration{        time.Microsecond,        time.Second,        3 * time.Second,        9 * time.Minute,    }      // Using for loop and range to    // iterate over an array    for _, m := range R {          // Prints rounded d of all         // the items in an array        fmt.Printf("Rounded(%s) is : %s\n",                              m, d.Round(m))    }}
Output:
Rounded(1μs) is : 4m13.671s
Rounded(1s) is : 4m14s
Rounded(3s) is : 4m15s
Rounded(9m0s) is : 0s

Here, an array of ‘d’ is formed first then a range is used in order to iterate over all the values of d. And at last Round() method is used to print all the rounded values of d.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Formatting in Golang
fmt.Sprintf() Function in Golang With Examples
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Slices in Golang
Arrays in Go
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang