code-rag-bench/online-tutorials huggingface dataset:
Python 3 - os.chdir() Method

The method chdir() changes the current working directory to the given path.It returns None in all the cases.
Following is the syntax for chdir() method −
os.chdir(path)

path − This is complete path of the directory to be changed to a new location.
This method does not return any value. It throws FileNotFoundError if specified path is not found
The following example shows the usage of chdir() method.
#!/usr/bin/python3
import os

path = "d:\\python3" #change path for linux

# Now change the directory
os.chdir( path )

# Check current working directory.
retval = os.getcwd()

print ("Directory changed successfully %s" % retval)
When we run the above program, it produces the following result −
Directory changed successfully d:\python3


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Calculate the Cumulative Minima of a Vector in R Programming - cummin() Function - GeeksforGeeks

15 Jun, 2020
cummin() function in R Language is used to calculate the cumulative minima of the values of vector passed as arguments.
Syntax: cummin(x)
Parameters:x: numeric object
Example 1:
# R program to cumulative minima  # Calling cummin() functioncummin(2:6)cummin(-2:-6)cummin(1.8:4.2)
Output:
[1] 2 2 2 2 2
[1] -2 -3 -4 -5 -6
[1] 1.8 1.8 1.8

Example 2:
# R program to cumulative minima  # Creating vectorsx1 <- c(3, 6, 4, 2, 6, 7)x2 <- c(-4, 6, 3)  # Calling cummin() functioncummin(x1)cummin(x2)
Output:
[1] 3 3 3 2 2 2
[1] -4 -4 -4

Since, the minima is calculated for the values in increasing order and hence the above code shows two cumulative values for first vector.
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
PyQt5 – Block signals of push button - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can block the signals of the button, blocking signals means stopping the button to do his assigned task. It is used to make a button deactive.
In order to do this we will use blockSignals method which belongs to QObject class.
Syntax : button.blockSignals(True)
Argument : It takes bool as argument.
Action performed: It blocks the signal of button.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 30)          # adding action to a button        button.clicked.connect(self.clickme)          # blocking signals of the button        button.blockSignals(True)                # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :When this button will be clicked nothing will happen.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Selecting rows in pandas DataFrame based on conditions
Algorithms | Analysis of Algorithms | Question 1 - GeeksforGeeks

28 Jun, 2021
What is time complexity of fun()?
int fun(int n){  int count = 0;  for (int i = n; i > 0; i /= 2)     for (int j = 0; j < i; j++)        count += 1;  return count;}
(A) O(n^2)(B) O(nLogn)(C) O(n)(D) O(nLognLogn)Answer: (C)Explanation: For a input integer n, the innermost statement of fun() is executed following times.
n + n/2 + n/4 + ... 1
So time complexity T(n) can be written as
T(n) = O(n + n/2 + n/4 + ... 1) = O(n)
The value of count is also n + n/2 + n/4 + .. + 1
Quiz of this Question
Algorithms-Analysis of Algorithms
Analysis of Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Sorting | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Bit Algorithms | Question 3
Algorithms | Sorting | Question 5
Algorithms | Bit Algorithms | Question 2
Algorithms | Sorting | Question 6
Data Structures and Algorithms | Set 38
Algorithms | Bit Algorithms | Question 1
Generating Random id's using UUID in Python

UUID is having the full form Universal Unique Identifier, it is a python library which supports 128 bits ids for generating random objects.
As discussed, we can use it to generate unique random id for random objects.
For cryptography and hashing applications, this id can be used.
For generating random documents and also addresses etc. this id can be used.
Method1
Example code
import uuid
print ("Random id using uuid1() is : ",end="")
print (uuid.uuid1())
Output
Random id using uuid1() is : 4adeede2-e5d8-11e8-bd27-185e0fd4f8b3

bytes − It returns id in the format of 16 byte string.
int − It returns id in format of 128-bit integer.
hex − As 32 character hexadecimal string, it returns random id.
version − version number of UUID.
variant − It determines the internal layout of UUID.
time_low −Indicates the first 32 bits of id.
time_mid −Indicates the next 16 bits of id.
time_hi_version − Indicates the next 16 bits of id.
clock_seq_hi_variant − Indicates next 8 bits of id.
clock_seq_low − Indicates next 8 bits of id.
node − Indicates last 48 bits of id.
time − Indicates time component field of id.
clock_seq − Indicates 14 bit sequence number.
import uuid
id = uuid.uuid1()
# Representations of uuid1()
print ("Different Representations of uuid1() are : ")
print ("Representation in byte : ",end="")
print (repr(id.bytes))
print ("Representation in int : ",end="")
print (id.int)
print ("Representation in hex : ",end="")
print (id.hex)
print("\n")
# Components of uuid1()
print ("Different Components of uuid1() are : ")
print ("UUID Version : ",end="")
print (id.version)
print ("UUID Variant : ",end="")
print (id.variant)
print("\n")
# Fields of uuid1()
print ("Fields of uuid1() are : ")
print ("UUID Fields : ",end="")
print (id.fields)
print("\n")
# uuid1() Time Component
print ("uuid1() time Component is : ")
print ("Time component : ",end="")
print (id.node)
Different Representations of uuid1() are :
Representation in byte : b'\x1a\xd2\xa7F\xe5\xe4\x11\xe8\xbd\x9c\x18^\x0f\xd4\xf8\xb3'
Representation in int : 35653703010223099234452630771665795251
Representation in hex : 1ad2a746e5e411e8bd9c185e0fd4f8b3

Different Components of uuid1() are :
UUID Version : 1
UUID Variant : specified in RFC 4122

Fields of uuid1() are :
UUID Fields : (450012998, 58852, 4584, 189, 156, 26792271607987)

uuid1() time Component is :
Time component : 26792271607987

Method2
Example code
import uuid
id = uuid.uuid4()
# Id generated using uuid4()
print ("The id generated using uuid4() : ",end="")
print (id)
Output
The id generated using uuid4() : 21764219-e3d9-4bd3-a768-0bbc6e376bc0
Auto-HMM in Python. Automatic Model selection, training... | by MANIE TADAYON | Towards Data Science

During my Ph.D. at UCLA, I developed various models for sequential and time-series data. The hidden Markov model (HMM) was one of the earliest models I used, which worked quite well. I could not find any tutorial or any working codes on the HMM in Python/MATLAB/R. I am releasing the Auto-HMM, which is a python package to perform automatic model selection using AIC/BIC for supervised and unsupervised HMM.
This package uses hmmlearn for hidden Markov model training and decoding and it includes a model selection for the optimal number of parameters (number of mixture components, number of hidden states, etc). I implemented a similar package in MATLAB and R.
Please comment under this post if you would like to see the R and MATLAB implementation of the same model.
The training in HMM is done through the Baum-Welch, which is the special case of the EM algorithm. The decoding is done through the Viterbi algorithm. I guess the hmmlearn package supports the MAP decoder besides the ML (Viterbi) decoder.
The model selection is done through AIC and BIC, which operate by penalizing the likelihood functions. This is done automatically here by specifying the maximum number of hidden states you like and the algorithm finds the optimal number of hidden states for the discrete HMM, and optimal number mixture component, and an optimal number of hidden states for the continuous HMM.
To access the code please visit my GitHub at
github.com
Please go over the examples in DHMM_Testing and HMM_Testing Python files. They require you to have provided your CSV file address, number of iteration for HMM model, training size, number of features (dimension of time series).
As an example, the following code performs the discrete HMM for 2000 observations with 50 points in time for a maximum of 3 hidden states. The training size is set to 0.8 (0.8 * 2000 = 1600). The Feat determines the dimensionality of the time series (1 means a univariate time series). The flag determines if you would like to sort your hidden states in descending or ascending order.
from Hidden_Markov_Model import *from Hidden_Markov_Model.DHMM import *Train_ratio=0.8Max_state=3Iter=1000Feat=1N=2000T=50flag=0N_symb=3Path= 'Path to CSV file'Data=pd.read_csv(Path)Data=Data.astype(int)First_DHMM=Supervised_DHMM(Train_ratio,Max_state,Iter,Feat,N,T,Data,N_symb)First_DHMM.Best_States()
For more information about my recent activity and any questions, please visit my YouTube page. I have also written tsBNgen, the Python package for generating synthetic time-series data, which can be used as the input to the Auto-HMM model. To learn more about tsBNgen, please visit my YouTube page below.
www.youtube.com
If you have any questions or concerns you can visit my personal page at
manietadayon.com
To learn more about the HMM modeling and implementation please refer to the following video:
Keras - Reshape Layers

Reshape is used to change the shape of the input. For example, if reshape with argument (2,3) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3)
Reshape has one argument as follows −
keras.layers.v(target_shape)

A simple example to use Reshape layers is as follows −
>>> from keras.models import Sequential 
>>> from keras.layers import Activation, Dense, Reshape 
>>> 
>>> 
>>> model = Sequential() 
>>> layer_1 = Dense(16, input_shape = (8,8)) 
>>> model.add(layer_1) 
>>> layer_2 = Reshape((16, 8)) 
>>> model.add(layer_2) 
>>> layer_2.input_shape (None, 8, 16) 
>>> layer_2.output_shape (None, 16, 8)
>>>
where, (16, 8) is set as target shape.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    68 Lectures 
     2 hours 

 Mike West
 Print
 Add Notes
 Bookmark this page
Count zero, NULL and distinct values except zero and NULL with a single MySQL query

Let us first create a table −
mysql> create table DemoTable(
   Value int
);
Query OK, 0 rows affected (1.35 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.59 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.70 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 10    |
| NULL  |
| 10    |
| 0     |
| 20    |
| 10    |
| 0     |
| NULL  |
+-------+
8 rows in set (0.00 sec)
Following is the query to group by on all values except null and 0 −
mysql> select sum(Value is null) as NumberOfNull,
   sum(Value=0) as NumberOfZero,
   count(distinct Value > 0) as ValueExceptZeroAndNull
from DemoTable;
This will produce the following output −
+--------------+--------------+------------------------+
| NumberOfNull | NumberOfZero | ValueExceptZeroAndNull |
+--------------+--------------+------------------------+
| 2            | 2            | 2                      |
+--------------+--------------+------------------------+
1 row in set (0.00 sec)
Draw a car using Turtle in Python - GeeksforGeeks

12 Jan, 2022
Prerequisite: Turtle module, Drawing Shapes
There are many modules in python which depict graphical illustrations, one of them is a turtle, it is an in-built module in Python, which lets the user control a pen(turtle) to draw on the screen(drawing board). It is mostly used to illustrate figures, shapes, designs, etc.  In this article, we will learn how to draw a Car using the turtle module. 
To draw a car in Python using the Turtle module:
We are going to create different shapes using the turtle module in order to illustrate a car.Tyres can be drawn using the circle() function.The upper body can be thought of as a rectangle.The roof and windows are similar to a trapezoid.Overlapping all the above shapes in particular positions will illustrate a car.
We are going to create different shapes using the turtle module in order to illustrate a car.
Tyres can be drawn using the circle() function.
The upper body can be thought of as a rectangle.
The roof and windows are similar to a trapezoid.
Overlapping all the above shapes in particular positions will illustrate a car.
 Let’s try to understand it better with the help of the below program:
Python3
#Python program to draw car in turtle programming # Import required libraryimport turtle     car = turtle.Turtle()  # Below code for drawing rectangular upper bodycar.color('#008000')car.fillcolor('#008000')car.penup()car.goto(0,0)car.pendown()car.begin_fill()car.forward(370)car.left(90)car.forward(50)car.left(90)car.forward(370)car.left(90)car.forward(50)car.end_fill()     # Below code for drawing window and roofcar.penup()car.goto(100, 50)car.pendown()car.setheading(45)car.forward(70)car.setheading(0)car.forward(100)car.setheading(-45)car.forward(70)car.setheading(90)car.penup()car.goto(200, 50)car.pendown()car.forward(49.50)     # Below code for drawing two tyrescar.penup()car.goto(100, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill()car.penup()car.goto(300, -10)car.pendown()car.color('#000000')car.fillcolor('#000000')car.begin_fill()car.circle(20)car.end_fill()     car.hideturtle()
Output: 
 
chhabradhanvi
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
C# Program to Read a String and Find the Sum of all Digits - GeeksforGeeks

19 Oct, 2021
Given a string, our task is to first read this string from the user then find the sum of all the digits present in the given string.
Examples
Input : abc23d4
Output: 9

Input : 2a3hd5j
Output: 10
Approach:
To reada String and find the sum of all digits present in the string follow the following steps:
First of all we read the string from the user using Console.ReadLine() method.
Initialize a integer sum with value 0.
Now iterate the string till the end.
If the character value is greater than or equal to ‘0’ and less than or equal to ‘9’ (i.e. ascii value between 48 to 57) then perform character – ‘0’  (this gives value of character) and add the value to the sum.
Now the sum contains the value of sum of all the digits in the strings.
Example:
C#
// C# program to read the string from the user and// then find the sum of all digits in the stringusing System;  class GFG{      public static void Main(){    string str;    Console.WriteLine("Enter a string ");        // Reading the string from user.    str = Console.ReadLine();    int count, sum = 0;    int n = str.Length;          for(count = 0; count < n; count++)    {                  // Checking if the string contains digits or not        // If yes then add the numbers to find their sum         if ((str[count] >= '0') && (str[count] <= '9'))        {            sum += (str[count] - '0');        }    }    Console.WriteLine("Sum = " + sum);}}
Enter a string
abc23d4
Sum = 9
Output 2:
Enter a string
2a3hd5j
Sum = 10
Explanation: In the above example, first we read the string and we will iterate each character and check if the character is an integer or not by comparing the ASCII value of the character. If the character is an integer then add the value to the sum. At the end of the iteration, the sum variable will have the total sum of digits in the string.
CSharp-programs
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
Python | Create simple animation for console-based application - GeeksforGeeks

17 Apr, 2019
As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility.
We will try to replicate the loading animation as shown below:
We will be using following modules –
sys module
os module
time module

 Below is the Python implementation:
# importing the necessary packagesimport timeimport sysimport os  # Function for implementing the loading animationdef load_animation():      # String to be displayed when the application is loading    load_str = "starting your console application..."    ls_len = len(load_str)        # String for creating the rotating line    animation = "|/-\\"    anicount = 0          # used to keep the track of    # the duration of animation    counttime = 0                  # pointer for travelling the loading string    i = 0                           while (counttime != 100):                  # used to change the animation speed        # smaller the value, faster will be the animation        time.sleep(0.075)                                       # converting the string to list        # as string is immutable        load_str_list = list(load_str)                   # x->obtaining the ASCII code        x = ord(load_str_list[i])                  # y->for storing altered ASCII code        y = 0                                       # if the character is "." or " ", keep it unaltered        # switch uppercase to lowercase and vice-versa         if x != 32 and x != 46:                         if x>90:                y = x-32            else:                y = x + 32            load_str_list[i]= chr(y)                  # for storing the resultant string        res =''                     for j in range(ls_len):            res = res + load_str_list[j]                      # displaying the resultant string        sys.stdout.write("\r"+res + animation[anicount])        sys.stdout.flush()          # Assigning loading string        # to the resultant string        load_str = res                    anicount = (anicount + 1)% 4        i =(i + 1)% ls_len        counttime = counttime + 1          # for windows OS    if os.name =="nt":        os.system("cls")              # for linux / Mac OS    else:        os.system("clear")  # Driver programif __name__ == '__main__':     load_animation()      # Your desired code continues from here     # s = input("Enter your name: ")    s ="David"    sys.stdout.write("Hello "+str(s)+"\n")
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Execute main() multiple times without using any other function or condition or recursion in Java - GeeksforGeeks

01 Apr, 2019
Given task is to execute main() multiple times without using any other function and without recursion() and without error. Given condition is that if executing main() n times then you can only call him (n-1) times.
Solution:
class Test {      // static block    static    {        main(new String[] { "Hello" });    }    public static void main(String[] args)    {        System.out.println("Hii");    }}
Hii
Hii

Explanation: Static block is executed even before the main() executed. Here first, main() get called by static block and then JVM(Java Virtual Machine) call the main(). So, main() is executed two times by calling only one time.
java-basics
main
Interview Experiences
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Zoho Interview | Set 3 (Off-Campus)
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
numpy.negative() in Python - GeeksforGeeks

28 Nov, 2018
numpy.negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar.
Syntax : numpy.negative(arr, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘negative’)
Parameters :arr : [array_like or scalar] Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray or scalar] Returned array or scalar = -(input arr or scalar )
Code #1 : Working
# Python program explaining# numpy.negative() function  import numpy as geekin_num = 10  print ("Input  number : ", in_num)    out_num = geek.negative(in_num) print ("negative of input number : ", out_num) 
Output :
Input  number :  10
negative of input number :  -10

 Code #2 :
# Python program explaining# numpy.negative function  import numpy as geek  in_arr = geek.array([[2, -7, 5], [-6, 2, 0]])   print ("Input array : ", in_arr)     out_arr = geek.negative(in_arr) print ("negative of array elements: ", out_arr) 
Output :
Input array :  [[  2.   2.   2.]
 [  2.   2.  nan]]
product of array elements:  32.0Input array :  [[ 2 -7  5]
 [-6  2  0]]
negative of array elements:  [[-2  7 -5]
 [ 6 -2  0]]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
fdisk command in Linux with examples - GeeksforGeeks

20 Jan, 2021
fdisk also known as format disk is a dialog-driven command in Linux used for creating and manipulating disk partition table. It is used for the view, create, delete, change, resize, copy and move partitions on a hard drive using the dialog-driven interface. fdisk allows you to create a maximum of four primary partitions and the number of logical partition depends on the size of the hard disk you are using. It allows the user: 
To Create space for new partitions.
Organizing space for new drives.
Re-organizing old drives.
Copying or Moving data to new disks(partitions).
Synopsis:  
fdisk [options] device

or

fdisk -l [device...]
1. View All Disk Partitions:The first thing to do before doing any thing with the disks and partition is to view basic details about all available partition in the system. The below command is used to list the partitions on your system and see their /dev names. For example /dev/sda, /dev/sdb or /dev/sdc. 
$ sudo fdisk -l
2. View Partition on a Specific Disk: Below command is used to view all disk partitions on device /dev/sda.  
$ sudo fdisk -l /dev/sda
3. View all fdisk Commands: To see all the command which are available under fdisk command you can use /dev/sda partition with fdisk command.  
$ sudo fdisk /dev/sda
Note: This will prompt for a command. Type m for seeing all the operations which can perform on /dev/sda. After pressing m you will get:  
4. Create a Hard Disk Partition: For this go inside the hard drive partition that is the /dev/sda partition, and use the following command:  
$ sudo fdisk /dev/sda
Now you have to type n to create new partition and then type p for making a primary partition and e for making an extended or logical partition depending on the type of partition to make.  
Run w command to write the changes and reboot your system. 
5. Delete a Hard Disk Partition: To delete a partition for the hard disk and free up space occupied by that partition for example /dev/sdb. Go to the command menu using following:  
$ sudo fdisk /dev/sda
and then type d to go to the delete partition menu. It will prompt the partition number you want to delete(type the number).  
Run w command to write the changes and reboot the system. 
6. How to view the size of your Partition:  
$ sudo fdisk -s /dev/sda
Note:  
To check for the manual page of fdisk command, use the following command:
$ man fdisk
To see the help message and listing of all options, use the following command option:
$ sudo fdisk -h
 
Akanksha_Rai
Vishwajith.K
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
How to use Thread in Tkinter Python - GeeksforGeeks

17 Dec, 2020
Prerequisite: 
Python GUI – tkinter
multithreading
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
While Creating a GUI there will be a need to do multiple work/operation at backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During execution of one operation the GUI window will also not move and this is why we need threading. Both implementation is given below which obviously will help understand their differences better.
Working without threads, makes the process delayed. Also, the window will not move until full execution takes place.
Approach
Create Normal Tkinter Window
Add Button with command 
Execute Tkinter
Program:
Python3
# Import Modulefrom tkinter import *import timefrom threading import *  # Create Objectroot = Tk()  # Set geometryroot.geometry("400x400")    def work():      print("sleep time start")      for i in range(10):        print(i)        time.sleep(1)      print("sleep time stop")    # Create ButtonButton(root, text="Click Me", command=work).pack()  # Execute Tkinterroot.mainloop()
Output:
Approach
Create Normal Tkinter Window
Add Button with command for threading 
Execute Tkinter
Program:
Python3
# Import Modulefrom tkinter import *import timefrom threading import *  # Create Objectroot = Tk()  # Set geometryroot.geometry("400x400")  # use threading  def threading():    # Call work function    t1=Thread(target=work)    t1.start()  # work functiondef work():      print("sleep time start")      for i in range(10):        print(i)        time.sleep(1)      print("sleep time stop")  # Create ButtonButton(root,text="Click Me",command = threading).pack()  # Execute Tkinterroot.mainloop()
Output:
Python-threading
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to use conditional operator in jQuery a template? - GeeksforGeeks

23 Apr, 2021
In this article, we will learn to use ternary or conditional operator in jQuery.
The Ternary or Conditional operator takes three operands, a condition followed by question mark followed by two expressions to execute with a semicolon (:) in between the two expressions.
Syntax:
condition ? expression1 : expression2
Example: Now let us try an example to find how a conditional operator is used in the jQuery template.
HTML
<!DOCTYPE HTML><html><head>    <script src="https://code.jquery.com/jquery-3.5.0.js"></script></head> <body style="text-align:center;">   <h2 style="color:green">GeeksforGeeks</h2>   <div style="background-color:red">        <p>Click the button to change the background color .</p>        <button>Click me!</button>   </div>   <script>    function toggleColor(){      tag = $('div');      // Ternary Operator (add/remove background color)      // If tag color is green convert it to red otherwise convert to green.     tag.css('background') == 'green' ? tag.css({'background':'red'}) : tag.css({'background':'green'});   }     $('button').on('click', function(){      toggleColor();    });    </script></body></html>
Output:
ternary operator
Picked
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
jQuery | attr() Method
Difference Between JavaScript and jQuery
jQuery | parent() & parents() with Examples
How to submit a form using ajax in jQuery ?
jQuery | focus() with Examples
Batch Script - CD

This batch command helps in making changes to a different directory, or displays the current directory.
cd

The following example shows how the cd command can be used in a variety of ways.
@echo off
Rem The cd without any parameters is used to display the current working directory
cd
Rem Changing the path to Program Files
cd\Program Files
cd
Rem Changing the path to Program Files
cd %USERPROFILE%
cd
Rem Changing to the parent directory
cd..
cd
Rem Changing to the parent directory two levels up
cd..\..
cd
The above command will display the following output after changing to the various folder locations.
C:\Users\Administrator
C:\Program Files
C:\Users\Administrator
C:\Users
C:\

 Print
 Add Notes
 Bookmark this page
Why do we use question mark literal in Python regular expression?

The question mark literal is used in different ways in Python Regular Expressions
As a special character '?' causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’
The question mark literal '?' is used following ways as per Python docs.
*?, +?, ??
The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only '<a>'.
puts() vs printf() for printing a string in C language

The function puts() and printf() are declared in stdio.h header file and are used to send the text to the output stream. Both have different usages and syntax.
The function puts() is used to print the string on the output stream with the additional new line character ‘\n’. It moves the cursor to the next line. Implementation of puts() is easier than printf().
Here is the syntax of puts() in C language,
puts(“string”);
If you do not want the cursor to be moved to the new line, use the following syntax.
fputs(string, stdout)
Here is an example of puts() in C language,
 Live Demo
#include<stdio.h>
int main() {
   puts("This is a demo.");
   fputs("No new Line.", stdout);
   puts(" Welcome!");
   getchar();
   return 0;
}
This is a demo.
No new Line. Welcome!
The function printf() is used to print the text long with the values of variables. The implementation of printf() is complex, that is why it is expensive than puts().
Here is the syntax of printf() in C language,
printf(“string”);
Here is an example of printf() in C language,
 Live Demo
#include<stdio.h>
int main() {
   int a = 10;
   printf("Hello world! \n");
   printf("The value of a : %d",a);
   getchar();
   return 0;
}
Hello world!
The value of a : 10
Matplotlib - Axes Class

Axes object is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects. The Axes class and its member functions are the primary entry point to working with the OO interface.
Axes object is added to figure by calling the add_axes() method. It returns the axes object and adds an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height.
Following is the parameter for the Axes class −
rect − A 4-length sequence of [left, bottom, width, height] quantities.
rect − A 4-length sequence of [left, bottom, width, height] quantities.
ax=fig.add_axes([0,0,1,1])
The following member functions of axes class add different elements to plot −
The legend() method of axes class adds a legend to the plot figure. It takes three parameters −
ax.legend(handles, labels, loc)
Where labels is a sequence of strings and handles a sequence of Line2D or Patch instances. loc can be a string or an integer specifying the legend location.
This is the basic method of axes class that plots values of one array versus another as lines or markers. The plot() method can have an optional format string argument to specify color, style and size of line and marker.
Following example shows the advertisement expenses and sales figures of TV and smartphone in the form of line plots. Line representing TV is a solid line with yellow colour and square markers whereas smartphone line is a dashed line with green colour and circle marker.
import matplotlib.pyplot as plt
y = [1, 4, 9, 16, 25,36,49, 64]
x1 = [1, 16, 30, 42,55, 68, 77,88]
x2 = [1,6,12,18,28, 40, 52, 65]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
l1 = ax.plot(x1,y,'ys-') # solid line with yellow colour and square marker
l2 = ax.plot(x2,y,'go--') # dash line with green colour and circle marker
ax.legend(labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')
plt.show()
When the above line of code is executed, it produces the following plot −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to use Cookies in CGI in Perl?

HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after transactions which spans through many pages. But how to maintain user's session information across all the web pages?
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name = Value − Cookies are set and retrviewed in the form of key and value pairs.
It is very easy to send cookies to browser. These cookies will be sent along with the HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows −
#!/usr/bin/perl
print "Set-Cookie:UserID = XYZ;\n";
print "Set-Cookie:Password = XYZ123;\n";
print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\n";
print "Set-Cookie:Domain = www.tutorialspoint.com;\n";
print "Set-Cookie:Path = /perl;\n";
print "Content-type:text/html\r\n\r\n";
...........Rest of the HTML Content goes here....
Here we used Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is important to note that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.
key1 = value1;key2 = value2;key3 = value3....
Here is an example of how to retrieve cookies.
#!/usr/bin/perl
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie ( @cookies ) {
   ($key, $val) = split(/=/, $cookie); # splits on the first =.
   $key =~ s/^\s+//;
   $val =~ s/^\s+//;
   $key =~ s/\s+$//;
   $val =~ s/\s+$//;
   if( $key eq "UserID" ) {
      $user_id = $val;
   } elsif($key eq "Password") {
      $password = $val;
   }
}
print "User ID = $user_id\n";
print "Password = $password\n";
This will produce the following result, provided above cookies have been set before calling retrieval cookies script.
User ID = XYZ
Password = XYZ123
Convert Long Values into Byte Using Explicit Casting in Java - GeeksforGeeks

29 Oct, 2020
In Java, a byte can contain only values from -128 to 127, if we try to cast a long value above or below the limits of the byte then there will be a precision loss.
1. byte: The byte data type is an 8-bit signed two’s complement integer.
Syntax:
byte varName; // Default value 0

Values:
1 byte (8 bits) : 
-128 to 127

2. long: The long data type is a 64-bit two’s complement integer. 
Syntax:
long varName; // Default value 0

Values:
8 byte (64 bits):
-9223372036854775808 to 9223372036854775807

Example 1: In limits
Java
// Java Program to Convert Long (under Byte limit)// Values into Byte using explicit castingimport java.io.*;  class GFG {        public static void main(String[] args)    {        long firstLong = 45;        long secondLong = -90;                // explicit type conversion from long to byte        byte firstByte = (byte)firstLong;        byte secondByte = (byte)secondLong;                // printing typecasted value        System.out.println(firstByte);        System.out.println(secondByte);    }}
45
-90


Example 2: Out of limits
Java
// Java Program to Convert Long (out of the// limits of Byte) Values into Byte using // explicit casting  import java.io.*;  class GFG {    public static void main(String[] args)    {        long firstLong = 150;        long secondLong = -130;                // explicit type conversion from long to byte        byte firstByte = (byte)firstLong;        byte secondByte = (byte)secondLong;                // printing typecasted value        System.out.println(firstByte);        System.out.println(secondByte);    }}
-106
126


Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Tryit Editor v3.7

Tryit: HTML article element
How to print a formatted text using printf() method in Java?


The printf() method allows us to format output to a java.io.PrintStream or java.io.PrintWriter. These classes also contain a method called format() which can produce the same results, so whatever we read here for the printf() method can also be applied to the format() method.
System.out.printf(“format-string” [, arg1, arg2, ... ]);
import java.io.PrintStream;
public class PrintfTest1 {
   public static void main(String[] args) {
      int i = 1234;
      System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x"\n, i);
      String str = "Tutorials Point";
      System.out.printf("%15s", str);
   }
}
Decimal: 1,234 Octal: 2322 Hex: 4d2
Tutorials Point
public class PrintfTest2 {
   public static void main(String[] args) {
      String name = "Adithya";
      int age= 30;
      System.out.format("%-10s - %4d\n", name, age);
   }
}
Adithya    -   30
C library function - sin()

The C library function double sin(double x) returns the sine of a radian angle x.
Following is the declaration for sin() function.
double sin(double x)
x − This is the floating point value representing an angle expressed in radians.
x − This is the floating point value representing an angle expressed in radians.
This function returns sine of x.
The following example shows the usage of sin() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main () {
   double x, ret, val;

   x = 45.0;
   val = PI / 180;
   ret = sin(x*val);
   printf("The sine of %lf is %lf degrees", x, ret);
   
   return(0);
}
Let us compile and run the above program to produce the following result −
The sine of 45.000000 degrees is 0.707107


    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
Assembly - Recursion

A recursive procedure is one that calls itself. There are two kind of recursion: direct and indirect. In direct recursion, the procedure calls itself and in indirect recursion, the first procedure calls a second procedure, which in turn calls the first procedure.
Recursion could be observed in numerous mathematical algorithms. For example, consider the case of calculating the factorial of a number. Factorial of a number is given by the equation −
Fact (n) = n * fact (n-1) for n > 0
For example: factorial of 5 is 1 x 2 x 3 x 4 x 5 = 5 x factorial of 4 and this can be a good example of showing a recursive procedure. Every recursive algorithm must have an ending condition, i.e., the recursive calling of the program should be stopped when a condition is fulfilled. In the case of factorial algorithm, the end condition is reached when n is 0.
The following program shows how factorial n is implemented in assembly language. To keep the program simple, we will calculate factorial 3.
section	.text
   global _start         ;must be declared for using gcc
	
_start:                  ;tell linker entry point

   mov bx, 3             ;for calculating factorial 3
   call  proc_fact
   add   ax, 30h
   mov  [fact], ax
    
   mov	  edx,len        ;message length
   mov	  ecx,msg        ;message to write
   mov	  ebx,1          ;file descriptor (stdout)
   mov	  eax,4          ;system call number (sys_write)
   int	  0x80           ;call kernel

   mov   edx,1            ;message length
   mov	  ecx,fact       ;message to write
   mov	  ebx,1          ;file descriptor (stdout)
   mov	  eax,4          ;system call number (sys_write)
   int	  0x80           ;call kernel
    
   mov	  eax,1          ;system call number (sys_exit)
   int	  0x80           ;call kernel
	
proc_fact:
   cmp   bl, 1
   jg    do_calculation
   mov   ax, 1
   ret
	
do_calculation:
   dec   bl
   call  proc_fact
   inc   bl
   mul   bl        ;ax = al * bl
   ret

section	.data
msg db 'Factorial 3 is:',0xa	
len equ $ - msg			

section .bss
fact resb 1
When the above code is compiled and executed, it produces the following result −
Factorial 3 is:
6


    46 Lectures 
     2 hours 

 Frahaan Hussain

    23 Lectures 
     12 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page