code-rag-bench/online-tutorials huggingface dataset:
SQLite - CHECK Constraint

The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table.
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years −
CREATE TABLE COMPANY(
   ID   INT       PRIMARY KEY     ,
   NAME          TEXT     NOT NULL,
   AGE  INT              NOT NULL UNIQUE,
   ADDRESS  CHAR (25) ,
   SALARY   REAL  ,       
   
);
If COMPANY table has already been created, then to add a CHECK constraint to AGE column, you would write a statement similar to the following −
ALTER TABLE COMPANY
   MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );
You can also use following syntax, which supports naming the constraint and multiple columns as well −
ALTER TABLE COMPANY
   ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);
Python | Convert a list to dictionary

25 Sep, 2020
Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.Examples:  
Input : ['a', 1, 'b', 2, 'c', 3]
Output : {'a': 1, 'b': 2, 'c': 3}

Input : ['Delhi', 71, 'Mumbai', 42]
Output : {'Delhi': 71, 'Mumbai': 42}



  Method #1 : dict comprehensionTo convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.  
Python3
# Python3 program to Convert a# list to dictionary def Convert(lst):    res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}    return res_dct         # Driver codelst = ['a', 1, 'b', 2, 'c', 3]print(Convert(lst))
{'a': 1, 'b': 2, 'c': 3}


  Method #2 : Using zip() methodFirst create an iterator, and initialize it to variable ‘it’. Then use zip method, to zip keys and values together. Finally typecast it to dict type.  
Python3
# Python3 program to Convert a# list to dictionary def Convert(a):    it = iter(a)    res_dct = dict(zip(it, it))    return res_dct         # Driver codelst = ['a', 1, 'b', 2, 'c', 3]print(Convert(lst))
{'a': 1, 'b': 2, 'c': 3}


timothynewtoncma13
Python dictionary-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to convert 1-D arrays as columns into a 2-D array in Python?

13 Jan, 2021
Let’s see a program to convert 1-D arrays as columns into a 2-D array using NumPy library in Python. So, for solving this we are using numpy.column_stack() function of NumPy. This function takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array.
Syntax : numpy.column_stack(tuple)
Parameters :
tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same first dimension.
Return : [stacked 2-D array] The stacked 2-D array of the input arrays.
Now, let’s see an example:
 Example 1:
Python3
# import libraryimport numpy as np # create a 1d-arraya = np.array(("Geeks", "for",              "geeks")) # create a 1d-arrayb = np.array(("my", "name",              "sachin")) # convert 1d-arrays into# columns of 2d-arrayc = np.column_stack((a, b)) print(c)
  
Output:
 
[['Geeks' 'my']
 ['for' 'name']
 ['geeks' 'sachin']]
 
Example 2:
 
Python3
# import libraryimport numpy as np # create 1d-arraya = np.array((1,2,3,4)) # create 1d-arrayb = np.array((5,6,7,8)) # convert 1d-arrays into# columns of 2d-arrayc = np.column_stack((a, b))  print(c)
  
Output:
 
[[1 5]
[2 6]
[3 7]
[4 8]]
 
ysachin2314
Python numpy-arrayManipulation
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python | Get the real time currency exchange rate

14 Dec, 2018
Python is a very versatile programming language. Python is being used in almost each mainstream technology and one can develop literally any application with it.
Let’s see a Python program to the real-time currency exchange rate. To use this service, one must need the API key, which can be get form here. One can get the list of currency codes from here.
We will be using CURRENCY_EXCHANGE_RATE API ,which can return the realtime exchange rate for any pair of digital currency (e.g., Bitcoin) or physical currency (e.g., USD).
Modules Needed :
requests
json

Below is the implementation :
# Python program to get the real-time# currency exchange rate  # Function to get real time currency exchange def RealTimeCurrencyExchangeRate(from_currency, to_currency, api_key) :      # importing required libraries    import requests, json      # base_url variable store base url     base_url = r"https://www.alphavantage.co/query?function = CURRENCY_EXCHANGE_RATE"      # main_url variable store complete url    main_url = base_url + "&from_currency =" + from_currency +                "&to_currency =" + to_currency + "&apikey =" + api_key      # get method of requests module     # return response object     req_ob = requests.get(main_url)      # json method return json format    # data into python dictionary data type.          # result contains list of nested dictionaries    result = req_ob.json()      print(" Result before parsing the json data :\n", result)            print("\n After parsing : \n Realtime Currency Exchange Rate for",          result["Realtime Currency Exchange Rate"]                ["2. From_Currency Name"], "TO",          result["Realtime Currency Exchange Rate"]                ["4. To_Currency Name"], "is",          result["Realtime Currency Exchange Rate"]                ['5. Exchange Rate'], to_currency)      # Driver codeif __name__ == "__main__" :      # currency code    from_currency = "USD"    to_currency = "INR"      # enter your api key here     api_key = "Your_Api_Key"      # function calling    RealTimeCurrencyExchangeRate(from_currency, to_currency, api_key)
Output :
Result before parsing the json data :{‘Realtime Currency Exchange Rate’: {‘1. From_Currency Code’: ‘USD’, ‘2. From_Currency Name’: ‘United States Dollar’, ‘3. To_Currency Code’: ‘INR’, ‘4. To_Currency Name’: ‘Indian Rupee’, ‘5. Exchange Rate’: ‘71.51500000’, ‘6. Last Refreshed’: ‘2018-12-13 17:40:36’, ‘7. Time Zone’: ‘UTC’}}
After parsing :Realtime Currency Exchange Rate for United States Dollar TO Indian Rupee is 71.51500000 INR
python-utility
Technical Scripter 2018
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Ways to increment a character in Python

13 May, 2021
In python there is no implicit concept of data types, though explicit conversion of data types is possible, but it not easy for us to instruct operator to work in a way and understand the data type of operand and manipulate according to that. For e.g Adding 1 to a character, if we require to increment the character, an error instructing type conflicts occur, hence other ways need to be formulated to increment the characters. 
Python
# python code to demonstrate error# due to incrementing a character # initializing a characters = 'M' # trying to get 'N'# produces errors = s + 1 print (s)
Output:  
Traceback (most recent call last):
  File "/home/fabc221bf999b96195c763bf3c03ddca.py", line 9, in 
    s = s + 1
TypeError: cannot concatenate 'str' and 'int' objects
 
 
Python3
# python code to demonstrate way to# increment character # initializing characterch = 'M' # Using chr()+ord()# prints Px = chr(ord(ch) + 3) print ("The incremented character value is : ",end="")print (x)
Output:  
The incremented character value is : P
Explanation : ord() returns the corresponding ASCII value of character and after adding integer to it, chr() again converts it into character. 
 
Python3
# python code to demonstrate way to# increment character # initializing byte characterch = 'M' # converting character to bytech = bytes(ch, 'utf-8') # adding 10 to Ms = bytes([ch[0] + 10]) # converting byte to strings = str(s) # printing the required valueprint ("The value of M after incrementing 10 places is : ",end="")print (s[2])
Output:  
The value of M after incrementing 10 places is : W
Explanation : The character is converted to byte string , incremented, and then again converted to string form with prefix “‘b”, hence 3rd value gives the correct output.This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
arorakashish0911
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Writing OS Independent Code in C/C++

03 Jun, 2022
A program that can interact with the operating system irrespective of the OS on which it runs. In simple words, we can say that a program, which can run on a computer without depending on the operating system.
How to write a utility program that lists all contents of the directory irrespective of the Operating System?
Most of the C/C++ compilers define macros that can be used to detect operating systems. For example, in GCC, the following are common macros. 
_WIN32 : Defined for both 32 bit and 64 bit windows OS.
_WIN64 : Defined for 64 bit windows OS.

unix, __unix, __unix__ : Defined in UNIX OS

__APPLE__, __MACH__ : Defined in Mac OS
In Windows, we use dir call to list all directories, and in most of the other Operating Systems “ls” is used. Below is a simple C++ implementation to list directories of folders irrespective of OS.
C++
C
// C++ program to list all directories.#include <bits/stdc++.h>using namespace std;int main(){#ifdef _WIN32    system("dir");#else    system("ls");#endif    return 0;}
// C program to list all directories.#include <stdio.h>  int main(){#ifdef _WIN32    system("dir");#else    system("ls");#endif    return 0;}
Output:
bin
boot
dev
etc
home
lib
lib64
media
mnt
opt
proc
run
sbin
srv
sys
tmp
usr
var
The above OS-independent code is totally different from Java’s platform independence. In Java, there is intermediate byte code that is a very clean way of handling platform dependencies. Here we have to remember compiler-specific macros and write code using clumsy #ifdef and #else, and the most important, we need to recompile the code for every OS.
This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. 
simmytarika5
SHUBHAMSINGH10
harsh_shokeen
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
How can I determine the position of a Toplevel in Tkinter?

To place objects in the middle of a frame, we can use the place method. Let's take an example and see how it's done.
Import the required libraries and create an instance of tkinter frame.
Import the required libraries and create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Set the size of the frame using win.geometry method.
Next, create a button and label it.
Next, create a button and label it.
Set the position of the buttons using the place method by supplying the x and y coordinate values.
Set the position of the buttons using the place method by supplying the x and y coordinate values.
Place the center of the widget at a relative x and y position of 0.5 of button widget (relx=0.5, rely=0.5). Set the anchor at the center by supplying "anchor=CENTER"
Place the center of the widget at a relative x and y position of 0.5 of button widget (relx=0.5, rely=0.5). Set the anchor at the center by supplying "anchor=CENTER"
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the Tkinter library
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter frame
win = Tk()

# Define the geometry
win.geometry("750x350")
win.title("Main Window")

def toplevel_position():
   print("The coordinates of Toplevel window are:", top.winfo_x(), top.winfo_y())

top = Toplevel(win, height=150, width=300)
top.title("This is the Toplevel Window")
top.attributes('-topmost', 'true')

button = ttk.Button(top, text="Get position", command=toplevel_position)

button.place(relx=0.5, rely=0.5, anchor=CENTER)

top.mainloop()
When you execute this code, it will show the following output window −
Now, click the "Get position" button and it will print the coordinates of the Toplevel window on the console.
The coordinates of Toplevel window are: 282 105
Powershell - Append content to File

Add-Content cmdlet can be used to append content of a any file.
In this example, we're adding content of test.txt.
In this example, we're set content in a new txt file named test.txt
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.txt 'Hello'
In this example, we're appending content to test.html.
Type the following command in PowerShell ISE Console
Add-Content D:\temp\test\test.txt 'World!'
In this example, we're reading content of test.html.
Get-Content D:\temp\test\test.txt

You can see following output in PowerShell console.
Hello
World!


    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
Difference between Array and Union in C - GeeksforGeeks

02 Mar, 2022
1. Array in C : An array is collection of similar data items accessed by a common name stored at continuous memory locations. The elements of an array can be accessed using indices. They can be used to store primitive data types such as int, float, double, char, etc. but all elements have to be of the same data type. Below is the picturesque representation of an array. 
 
Declaration of an array :  
datatype array_name[size]
2. Union in C : Union is a user defined datatype that allows storage of heterogeneous elements in the same memory location. Size of the union is the size of the largest element in the union. Below is the picturesque representation of a union. 
 
Declaration of a union :  
union name
{
  datatype element;
  datatype element;
};
Difference between Array and Union : 
 
Syntax :
datatype array_name[size]
Syntax : Union user defined name 
 
{
 
datatype Variable 1; datatype variable2;
 
};
 
 
rkbhola5
Arrays
C-Data Types
C-Structure & Union
C Language
Difference Between
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to dynamically allocate a 2D array in C?
fgets() and gets() in C language
Exception Handling in C++
void pointer in C / C++
sizeof operator in C
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
How to Calculate Quantiles by Group in Pandas? - GeeksforGeeks

19 Dec, 2021
In this article, how to calculate quantiles by group in Pandas using Python.
There are many methods to calculate the quantile, but pandas provide groupby.quantile() function to find it in a simple few lines of code. This is the Method to use when the desired quantile falls between two points.
Syntax: 
DataFrameGroupBy.quantile(self, q=0.5, interpolation=’linear’)
Parameters:  
q : float or array-like, default 0.5 (50% quantile) Values are given between 0 and 1 providing the quantiles to compute.
Interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
In this method, the values and interpolation are passed as parameters. By default, the q value will be 0.5 and interpolation will be Linear. This returns the series or Dataframe determined by the GroupBy object.
Dataframe in use:
dataframe
Example 1: Calculate quantiles by group
Python3
# Importing librariesimport pandas as pd  # Storing data in dictionarygame = {'Player': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',                        'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',                        'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'],        'wins': [2, 4, 4, 5, 6, 9, 13, 13, 15, 15, 14, 13,                 11, 9, 9, 8, 8, 16, 19, 21, 14, 20, 19, 18]        }# Creating data framedf = pd.DataFrame(game)  # calculating quantiledf.groupby('Player').quantile(0.5)
Output:
output
Example 2: Calculate quantiles by group
Python3
# Importing librariesimport pandas as pd  # Storing data in dictionarygame = {'Player': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',                        'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',                        'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'],        'wins': [2, 4, 4, 5, 6, 9, 13, 13, 15, 15, 14, 13,                 11, 9, 9, 8, 8, 16, 19, 21, 14, 20, 19, 18]        }# Creating data framedf = pd.DataFrame(game)  # calculating quantiledf.groupby('Player').quantile(0.9)
Output:
output
Picked
Python pandas-dataFrame
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to change the space between bars when drawing multiple barplots in Pandas? (Matplotlib)

To change the space between bars when drawing multiple barplots in Pandas within a group, we can use linewidth in plot() method.
Set the figure size and adjust the padding between and around the subplots.
Make a dictionary with two columns.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Plot the dataframe with plot() method, with linewidth that change the space between the bars.
Place a legend on the plot.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

d = {'Column 1': [i for i in range(10)],
      'Column 2': [i * i for i in range(10)]}

df = pd.DataFrame(d)
df.plot(kind='bar', edgecolor='white', linewidth=1)

plt.legend(loc="upper left")
plt.show()
C library function - labs()

The C library function long int labs(long int x) returns the absolute value of x.
Following is the declaration for labs() function.
long int labs(long int x)
x − This is the integral value.
x − This is the integral value.
This function returns the absolute value of x.
The following example shows the usage of labs() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   long int a,b;

   a = labs(65987L);
   printf("Value of a = %ld\n", a);

   b = labs(-1005090L);
   printf("Value of b = %ld\n", b);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Value of a = 65987
Value of b = 1005090


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Where is the MySQL table data stored in Windows?

In order to know the location of MySQL table data, you can use the below syntax −
select @@datadir;
You can also use SHOW VARIABLES command for this. Following is the syntax −
show variables where Variable_name ='datadir';
Let us implement the above syntaxes to know where MySQL table stores data −
mysql> select @@datadir;
This will produce the following output −
+---------------------------------------------+
| @@datadir                                   |
+---------------------------------------------+
| C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------------------------------------+
1 row in set (0.00 sec)
Here is the alternate query to know where MySQL table data stored −
mysql> show variables where Variable_name ='datadir';
This will produce the following output −
+---------------+---------------------------------------------+
| Variable_name | Value                                       |
+---------------+---------------------------------------------+
| datadir       | C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------+---------------------------------------------+
1 row in set (0.23 sec)
Now follow the above path to reach where MySQL table is stored. Following is the screenshot displaying the location for tables −
Cypress - Aliases

Cypress aliases are an important component that have multiple uses. These uses are listed below −
We have to use .as() to alias something that we have to share. To alias objects and primitives, Mocha context objects are used. The alias object can be accessed with this.*.
Mocha by default, shares context for all the hooks applicable for the test and the alias properties are flushed post the execution of a test.
describe('element', () => {
   beforeEach(() => {
      cy.wrap('eleone').as('x')
   })
   context('subelement', () => {
      beforeEach(() => {
         cy.wrap('eletwo').as('y')
      })
         it('aliases properties', function () {
            expect(this.x).to.eq(' eleone ')
            expect(this.y).to.eq(' eleone ')
         })
      })
   })
})
We can handle fixtures by sharing context. We can also use cy.get(), which is an asynchronous command, to access an alias with the help of @ symbol (instead of using this.*) This is a synchronous command.
beforeEach(() => {
   // alias fixtures
   cy.fixture('users.json').as('u')
})
it('scenario', function () {
   // '@' to handle aliases
   cy.get('@u').then((u) => {
      // access element argument
      const i = u[0]
      //verification
      cy.get('header').should('contain', u.name)
   })
})
Alias can be used with Document Object Model (DOM) elements and later be reused. Here in the below example, by default Cypress makes a reference to td collection obtained as the alias cols. To use the same cols, we have to use cy.get() command.
// alias td in tr
cy.get('tr').find('td').as('cols')
cy.get('@cols').first().click()
As we used @ in cy.get(), Cypress searches for the present alias (cols) and yields its reference.
Aliases can be utilised with routes. It makes sure that the application has made the requests. Then, it awaits a response from the server and accesses the request for verification.
cy.intercept('POST', '/users', { id: 54 }).as('u')
cy.get('#btn').click()
cy.wait('@u').then(({ request }) =>{
//assertion
   expect(request.body).to.have.property('name', 'User')
})
cy.contains('User added')
Aliases can be utilised with requests. We can alias a request and later use its properties.This can be done as follows −
cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
// other implementations if any
cy.get('@c').should((response) => {
   if (response.status === 404) {
      // assertion
         expect(response).to.have.property('duration')
      } else {
         // do something else
      }
   })
})

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
Ever wanted Progress Bars in Jupyter? | Towards Data Science

How you use loops tells a lot about your programming skills.
Loops can be deadly effective but sometimes take too long to run. Especially, as you work more with Big Data, you will have to deal with massive datasets and use loops to perform computations for each observation.
Loops are not at all fun when you have to watch for the asterisk in your Jupyter Notebook for many minutes and sometimes hours. The worst part is when the loop has thousands of iterations, you don’t know if the loop is working correctly or just stuck at some iteration because of some silly mistake in data.
The good news is you can create progress bars for Jupyter Notebooks with tqdm library. The library is incredibly easy to use and it also gives a certain styling to ugly black and white notebooks. Besides, while in progress, you can also make the bar show which iteration the loop is working on. Nice, right? Here, watch it in action:

          This isn't the page you were looking for. Double check the URL, or
          contact us at
          support@getcloudapp.com.
        

          If this is your link, the upload may have failed.
          
            See here how you can recover your content
Tcl - Arithmetic Operators

Following table shows all the arithmetic operators supported by Tcl language. Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then −
Try the following example to understand all the arithmetic operators available in Tcl language −
#!/usr/bin/tclsh

set a 21
set b 10
set c [expr $a + $b]
puts "Line 1 - Value of c is $c\n"
set c [expr $a - $b]
puts "Line 2 - Value of c is $c\n"
set c [expr $a * $b]
puts "Line 3 - Value of c is $c\n"
set c [expr $a / $b]
puts "Line 4 - Value of c is $c\n"
set c [expr $a % $b]
puts "Line 5 - Value of c is $c\n"
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31

Line 2 - Value of c is 11

Line 3 - Value of c is 210

Line 4 - Value of c is 2

Line 5 - Value of c is 1

 Print
 Add Notes
 Bookmark this page
How to get the absolute path of a file using tkFileDialog(Tkinter)?

Tkinter is a standard Python library that is used to create and develop functional and featured applications. It has a variety of inbuilt functions, modules, and packages that can be used for constructing the logic of the application.
The tkFileDialog is an inbuilt module available in the Tkinter library which is useful for interacting with the system files and directories. However, once we select a particular file in the read mode using tkFileDialog, potentially it can be used further to process the information available in the file.
If you want to access the absolute path of the file when it gets loaded in the application, you can use the available function of OS module, i.e., os.path.abspath(file.name) function. This function will return the absolute path of the file which can be stored in a variable to display in the window or screen.
# Import the required Libraries
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os

# Create an instance of tkinter frame
win = Tk()

# Set the geometry of tkinter frame
win.geometry("700x350")

def open_file():
   file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')])
   if file:
      filepath = os.path.abspath(file.name)
      Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()

# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)

# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

win.mainloop()
When we run the code, it will first display the following window −
Now, click the "Browse" button and select a Python file from the Explorer. It will show the absolute path of the file you selected.
How to find an element using the attribute “HTML tag name” in Selenium?

We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By.tagName method.
In the html code, a tagname is usually enclosed by <>, for example, an anchor tag <a> represents links on the page. An input tag represents text boxes, checkboxes or radio buttons. Let us look at the html code of an element and try to identify it with its tagname −
In the above image, the text – You are browsing the best resources for has the h4 tag.
WebElement e = driver. findElement(By.tagName("h4"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorTagName{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element with tag name
      WebElement n = driver.findElement(By.tagName("h4"));
      //obtain text on element
      String s = n.getText();
      System.out.println("Text on element is : " + s);
      driver.close();
   }
}
How to display XML in HTML in PHP?

If the string is pre-formatted, and a plain text representation of the same is needed, it can be wrapped in a HTML <pre/> tag and html entities can be used to escape the angle brackets. This has been shown below −
<?PHP echo '<pre>', htmlentities($string), '</pre>'; ?>
The string is assigned to a string type and the above is used to show XML in HTML −
 Live Demo
<?php
$string = "
<example>
   <example>
      <example_value>EXAMPLE</example_value>
   </example>
</example> ";
echo '<pre>', htmlentities($string), '</pre>';
?>
This will produce the following output −
<example>
   <example>
      <example_value>EXAMPLE</example_value>
   </example>
</example>
Find the first, second and third minimum elements in an array in C++

Suppose we have an array of n elements. We have to find the first, second and the third minimum elements in the array. First minimum is the minimum of the array, second min is minimum but larger than the first one, and similarly the third min is minimum but greater than second min.
Scan through each element, then check the element, and relate the condition for first, second and third min elements conditions to solve this problem.
#include<iostream>
using namespace std;
int getThreeMins(int arr[], int n) {
   int first = INT_MAX, sec = INT_MAX, third = INT_MAX;
      for (int i = 0; i < n; i++) {
         if (arr[i] < first) {
            third = sec;
            sec = first;
            first = arr[i];
         } else if (arr[i] < sec) {
            third = sec;
            sec = arr[i];
         } else if (arr[i] < third)
            third = arr[i];
   }
   cout << "First min = " << first << endl;
   cout << "Second min = " << sec << endl;
   cout << "Third min = " << third << endl;
}
int main() {
   int array[] = {4, 9, 18, 32, 12};
   int n = sizeof(array) / sizeof(array[0]);
   getThreeMins(array, n);
}
First min = 4
Second min = 9
Third min = 12
Data Structures Stack Primitive Operations 

Stack is Last In First Out data structure. The stack is used in different area for evaluating expressions, call and recursion strategy etc. The stack has some primitive operations. Here we will see those operations of stack, and see one example using the stack ADT.
The ADT (abstract datatype) is special kind of datatype, whose behavior is defined by a set of values and set of operations. The keyword “Abstract” is used as we can use these datatypes, we can perform different operations. But how those operations are working that is totally hidden from the user. The ADT is made of with primitive datatypes, but operation logics are hidden.
These are few operations or functions of the Stack ADT.
isFull(), This is used to check whether stack is full or not
isEmpry(), This is used to check whether stack is empty or not
push(x), This is used to push x into the stack
pop(), This is used to delete one element from top of the stack
peek(), This is used to get the top most element of the stack
size(), this function is used to get number of elements present into the stack
 Live Demo
#include<iostream>
#include<stack>
using namespace std;
main(){
   stack<int> stk;
   if(stk.empty()){
      cout << "Stack is empty" << endl;
   } else {
      cout << "Stack is not empty" << endl;
   }
   //insert elements into stack
   stk.push(10);
   stk.push(20);
   stk.push(30);
   stk.push(40);
   stk.push(50);
   cout << "Size of the stack: " << stk.size() << endl;
   //pop and dispay elements
   while(!stk.empty()) {
      int item = stk.top(); // same as peek operation
      stk.pop();
      cout << item << " ";
   }
}
Stack is empty
Size of the stack: 5
50 40 30 20 10
Date format validation using Java Regex

Following example demonstrates how to check whether the date is in a proper format or not using matches method of String class.
Live Demo
public class Main {
   public static void main(String[] argv) {
      boolean isDate = false;
      String date1 = "8-05-1988";
      String date2 = "08/04/1987";
      String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";

      isDate = date1.matches(datePattern);
      System.out.println("Date :"+ date1+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate);

      isDate = date2.matches(datePattern);
      System.out.println("Date :"+ date2+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate);
   }
}
The above code sample will produce the following result.
Date :8-05-1988: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:true
Date :08/04/1987: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:false
The following is an example to check whether date is in the proper format or not.
Live Demo
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) {
      List dates = new ArrayList();
      dates.add("25/12/1990");
      dates.add("25/12/1990");
      dates.add("12/12/90");
      dates.add("05/02/1990");
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      Pattern pattern = Pattern.compile(regex);

      for(Object date : dates) {          
         Matcher matcher = pattern.matcher((CharSequence) date);
         System.out.println(date +" : "+ matcher.matches());
      }
   }
}
The above code sample will produce the following result.
25/12/1990 : false
25/12/1990 : false
12/12/90 : false
05/02/1990 : true
Compare two character vectors in R - GeeksforGeeks

09 May, 2021
In this article, we will discuss how to compare two character vectors in R Programming Language.
This operator is used to find the elements present in one vector with respect to the second vector
Syntax: vector1 %in% vector2
Return type: It returns boolean values corresponding to the elements in a vector
It returns true, if corresponding element is present in vector 2
It returns false, if corresponding element is not present in vector 2.
Example:
R
# create a vector named names# of college 1names1 = c("mohan","sravya","navya")  # create a vector named names # of college 2names2 = c("mohan","sravan","deepika")   # check names1 is present in # names 2print(names1 %in% names2)
Output:
[1]  TRUE FALSE FALSE
intersect() function is used to return the common element present in two vectors. Thus, the two vectors are compared, and if a common element exists it is displayed.
Syntax:
intersect(vector1,vector2)
Example:
R
# create a vector named names # of college 1names1 = c("mohan","sravya","navya")  # create a vector named names # of college 2names2 = c("mohan","sravan","deepika")   # find the common elementsprint(intersect(names1,names2))
Output:
[1] "mohan"
This function returns the elements present in vector1 but not present in vector2 and vice versa. Thus, two vectors are first compared for similarity, and elements are displayed accordingly.
Syntax:
setdiff(vector1,vector2)
Example:
R
# create a vector named names # of college 1names1 = c("mohan","sravya","navya")  # create a vector named names # of college 2names2 = c("mohan","sravan","deepika")   # find the set difference in the  # elementsprint(setdiff(names1,names2))  # find the set difference in the  # elementsprint(setdiff(names2,names1))
Output:
[1] "sravya" "navya"
[1] "sravan" "deepika"
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
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?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Merge DataFrames by Column Names in R
C++ Library - <iostream>

It is used in standard Input / Output Streams Library.
Following is the declaration for iosstream function.
Including this header may automatically include other headers, such as <ios>,
   <streambuf>, <istream>, <ostream> and/or <iosfwd>.
Including <iostream> automatically includes also <ios>, <streambuf>, <istream>,
   <ostream> and <iosfwd>.
The objects of iosstream should be like this −
 Print
 Add Notes
 Bookmark this page
Is Python Dynamically Typed Language?

Yes, it is. Python is a dynamically typed language. What is dynamic? We don't have to declare the type of variable while assigning a value to a variable in Python. Other languages like C, C++, Java, etc.., there is a strict declaration of variables before assigning values to them.
Python don't have any problem even if we don't declare the type of variable. It states the kind of variable in the runtime of the program. So, Python is a dynamically typed language. Let's see one example.
 Live Demo
## assigning a value to a variable
x = [1, 2, 3]
## x is a list here
print(type(x))
## reassigning a value to the 'x'
x = True
## x is a bool here
print(type(x))
If you run the above program, it will generate the following results.
<class 'list'>
<class 'bool'>
PHP Class Abstraction

In object oriented programming, an abstract class is the one that can be instantiated, i.e. it is not possible to declare object of such class. PHP supports concept of abstarct class since version 5.0
A class defined with abstract keyword becomes an abstract class. Further, any class which contains at least one abstract method is also considered abstract.
<?php
class testclass{
   //
}
?>
If we try to create an object oof this class, PHP parser throws error as follows −
$a=new testclass();
PHP Fatal error: Uncaught Error: Cannot instantiate abstract class testclass
Abstract method only declares its signature i.e. its visibility, arguments and return type with type hints and donot have any functionality. A class that inherits such an abstract class must override (provide definition) all abstract methods. Corresponding method in child class must carry same signature as in parent class. If child class doesn't fulfil this condition, PHP parser throws exception. A class that extends an abstract class can now be instantiated, hence it is called concrete class
In following example, parent class has two abstract methods, only one of which is redefined in child class. This results in error as follows −
 Live Demo
<?php
abstract class testclass{
   abstract function test1();
   abstract function hello();
}
class myclass extends testclass{
   function test1(){
      echo "Overrides parent test method";
   }
}
$a=new myclass();
?>
Following is the error message
PHP Fatal error: Class myclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testclass::hello)
When abstract method is defined with arguments, it must be overridden in child class with same number of arguments
In following example, abstract method in parent class has two arguments. Child class also defines same function with two arguments
 Live Demo
<?php
abstract class testclass{
   abstract function hello($name, $age);
}
class myclass extends testclass{
   function hello($name, $age){
      echo "My name is $name and my age is $age";
   }
}
$a=new myclass();
$a->hello("Ravi",20);
?>
This will produce following output −
My name is Ravi and my age is 20
How to Create a File in the Linux/Unix system using terminal?

In the Linux/Unix operating system there are two ways available to creating files.
Using the touch command
Using the cat command
The touch command is used to create file/files without any content and update the access date or modification date of a file or directory in the Linux system. This is the simplest way to create a file in Linux/Unix using a terminal.
The general syntax of the touch command is as follow −
$ touch [option] ... FILE...
Brief description of option available in the touch command.
Here, using the touch command we can create a file in the Linux system. Before executing touch command, we will check how many files are available in our current directory using the below command.
$ ls -l
After using below command a new file created newfile.txt in the current directory.
$ touch newfile.txt
To ensure that file is created or not we will again execute ls command to list the directory contents.
To change the access time of a file in the Linux system using -a option with touch command as shown in below.
$ touch -a newfile.txt
The cat (concatenate) command is used to create, view, concatenate files in the Linux operating system. The touch command is also used to create files in the Linux system without content whereas the cat creates files with some content. The cat command reads the content of a file and prompts it.
The general syntax of the cat command is as follows −
$ cat [option]... FILE...
Brief description of option available in the cat command.
To create a file with some content, we use the cat command and file name after that write some content and press CTRL + C when writing is complete as shown in below.
$ cat >file.txt
Hey, write some contents here...
^C
The cat command is also used to view the contents of the file. After using cat command along with file name contents of the file will be prompt as shown in below.
$ cat file.txt
Hey, here your contents...
UnitTest Framework - Test Discovery

The TestLoader class has a discover() function. Python testing framework uses this for simple test discovery. In order to be compatible, modules and packages containing tests must be importable from top level directory.
The following is the basic command line usage of test discovery −
Python –m unittest discover

Interpreter tries to load all modules containing test from current directory and inner directories recursively. Other command line options are −
-v, --verbose
Verbose output
-s, --start-directory
directory Directory to start discovery (. default)
-p, --pattern
pattern Pattern to match test files (test*.py default)
-t, --top-level-directory
directory Top level directory of project (defaults to start directory)
For example, in order to discover the tests in modules whose names start with 'assert' in 'tests' directory, the following command line is used −
C:\python27>python –m unittest –v –s "c:\test" –p "assert*.py"

Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify, it turns the paths into package names to import.
If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.
 Print
 Add Notes
 Bookmark this page
When should we create a user-defined exception class in Java?

We should create our own exceptions in Java. Keep the following points in mind when writing our own exception classes
All exceptions must be a child of Throwable.
If we want to write a checked exception that is automatically enforced by the Handle or Declare Rule, we need to extend the Exception class.
If we want to write a runtime exception, we need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception {
}
We just need to extend the Exception class to create our own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception.
Live Demo
// File Name InsufficientFundsException.java
import java.io.*;
class InsufficientFundsException extends Exception {
   private double amount;
   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }
   public double getAmount() {
      return amount;
   }
}

// File Name CheckingAccount.java
class CheckingAccount {
   private double balance;
   private int number;
   public CheckingAccount(int number) {
      this.number = number;
   }
   public void deposit(double amount) {
      balance += amount;
   }
   public void withdraw(double amount) throws InsufficientFundsException {
      if(amount <= balance) {
         balance -= amount;
      }
      else {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance() {
      return balance;
   }
   public int getNumber() {
      return number;
   }
}
// File Name BankDemo.java
public class BankDemo {
   public static void main(String [] args) {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      } catch(InsufficientFundsException e) {
         System.out.println("Sorry, but you are short $" + e.getAmount());
         e.printStackTrace();
      }
   }
}

Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(BankDemo.java:32)
at BankDemo.main(BankDemo.java:53)