code-rag-bench/online-tutorials huggingface dataset:
Dart - Splitting of String - GeeksforGeeks

20 Jul, 2020
In Dart splitting of a string can be done with the help split string function in the dart. It is a built-in function use to split the string into substring across a common character.
Syntax:
string_name.split(pattern)

This function splits the string into substring across the given pattern and then store them to a list.
Example 1: Splitting a string across space.
Dart
// Main functionvoid main() {      // Creating a string  String gfg = "Geeks For Geeks !!";      // Splitting the string  // across spaces  print(gfg.split(" "));}
 
Output:
[Geeks, For, Geeks, !!]

 
Example 2: Splitting each character of the string.
 
Dart
// Main functionvoid main() {      // Creating a string  String gfg = "GeeksForGeeks";      // Splitting each  // character of the string  print(gfg.split(""));}
  
Output:
[G, e, e, k, s, F, o, r, G, e, e, k, s]

Apart from the above pattern, the pattern can also be a regex. It is useful when we have to split across a group of characters like numbers, special characters, etc.
 
Example 3: Splitting a string across any number present in it. (Using regex)
Dart
// Main functionvoid main() {  // Creating a string  String gfg = "Geeks1For2Geeks3is4the5best6computer7science8website.";      // Splitting each character  // of the string  print(gfg.split(new RegExp(r"[0-9]")));}
 
Output:
[Geeks, For, Geeks, is, the, best, computer, science, website.]

Dart-String
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Flutter - Row and Column Widgets
Dart Tutorial
Container class in Flutter
Flutter - Stack Widget
Dynamic Constructor in C++ with Examples - GeeksforGeeks

14 Dec, 2021
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. Example 1:  
CPP14
#include <iostream>using namespace std; class geeks {    const char* p; public:    // default constructor    geeks()    {         // allocating memory at run time        p = new char[6];        p = "geeks";    }     void display()    {        cout << p << endl;    }}; int main(){    geeks obj;    obj.display();}
Output:  
geeks
Explanation: In this we point data member of type char which is allocated memory dynamically by new operator and when we create dynamic memory within the constructor of class this is known as dynamic constructor.Example 2:  
CPP14
#include <iostream>using namespace std; class geeks {    int* p; public:    // default constructor    geeks()    {         // allocating memory at run time        // and initializing        p = new int[3]{ 1, 2, 3 };         for (int i = 0; i < 3; i++) {            cout << p[i] << " ";        }         cout << endl;    }}; int main(){     // five objects will be created    // for each object    // default constructor would be called    // and memory will be allocated    // to array dynamically    geeks* ptr = new geeks[5];}
1 2 3 
1 2 3 
1 2 3 
1 2 3 
1 2 3
 
dynamically .Explanation: In this program we have created array of object dynamically. The first object is ptr[0], second is ptr[1] and so on . For each object creation default constructor is called and for each object memory is allocated to pointer type variable by new operator.Example 3:  
CPP14
#include <iostream>using namespace std; class geeks {    int* p; public:    // default constructor    geeks()    {         // allocating memory at run time        p = new int;        *p = 0;    }     // parameterized constructor    geeks(int x)    {        p = new int;        *p = x;    }    void display()    {        cout << *p << endl;    }}; int main(){     // default constructor would be called    geeks obj1 = geeks();    obj1.display();     // parameterized constructor would be called    geeks obj2 = geeks(7);    obj2.display();}
0
7
 
Explanation: In this integer type pointer variable is declared in class which is assigned memory dynamically when the constructor is called. When we create object obj1, the default constructor is called and memory is assigned dynamically to pointer type variable and initialized with value 0. And similarly when obj2 is created parameterized constructor is called and memory is assigned dynamically. 
abhishekparekh007
cpp-constructor
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
HTML | <area> shape Attribute - GeeksforGeeks

07 Jun, 2021
The HTML area shape Attribute is used with the coords attribute to describe the size, shape, and placement of a <area> element.
Syntax: 
<area shape="default | rect | circle | poly">
Attribute Values: 
default: It is used to specify the entire region.
rect: It is used to specify the rectangular region.
circle: It is used to specify a circular region.
poly: It is used to specify the polygonal region.
Example: 
html
<!DOCTYPE html><html> <head>    <title>        HTML area shape Attribute    </title></head> <body style="text-align:center;">    <h1>        GeeksForGeeks    </h1>    <h2>          HTML <area> shape Attribute    </h2>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png"         alt="alt_attribute"         width="300"         height="119"         class="aligncenter"         usemap="#shapemap" />     <map name="shapemap">         <!-- area tag contained image. -->        <area shape="poly"              coords="59, 31, 28, 83, 91, 83"              href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png"              alt="Triangle">         <area shape="circle"              coords="155, 56, 26"              href="https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png"              alt="Circle">         <area shape="rect"              coords="224, 30, 276, 82"              href="https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png"              alt="Square">    </map></body> </html>
Output : 
Before click on specific area:  
After click on specific area: 
Supported Browsers: The browsers supported by HTML area shape Attribute are listed below: 
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
HTML | <img> align Attribute
Form validation using HTML and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Difference between Type Casting and Type Conversion - GeeksforGeeks

08 Jun, 2020
1. Type Casting:In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;


(): is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x;  //Line 5 
In Line 5: you can see that, we are converting float(source) data type into byte(target) data type.
2. Type conversion :In type conversion, a data type is automatically converted into another data type by a compiler at the compiler time. In type conversion, the destination data type cannot be smaller than the source data type, that’s why it is also called widening conversion. One more important thing is that it can only be applied to compatible data types.
Type Conversion example –
int x=30;
float y;
y=x;  // y==30.000000. 
Let’s see the difference between Type casting and Type conversion which are given below:
pp_pankaj
C Language
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
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
Differences between IPv4 and IPv6
Java Program to Find GCD or HCF of Two Numbers - GeeksforGeeks

28 Mar, 2021
GCD (i.e. Greatest Common Divisor) or HCF (i.e. Highest Common Factor) is the largest number that can divide both the given numbers.
Example:
HCF of 10 and 20 is 10, and HCF of 9 and 21 is 3.
Therefore, firstly find all the prime factors of both the stated numbers, then find the intersection of all those factors that are present in both the given numbers. And at last, return the product of elements that are in the intersection.
Note: GCD of the two stated numbers doesn’t alter if the smaller number is subtracted from the bigger number.
Example 1:
Java
// Java program to find GCD of two numbersclass GFG {    // Gcd of x and y using recursive function    static int GCD(int x, int y)    {        // Everything is divisible by 0        if (x == 0)            return y;        if (y == 0)            return x;          // Both the numbers are equal        if (x == y)            return x;          // x is greater        if (x > y)            return GCD(x - y, y);        return GCD(x, y - x);    }      // The Driver method    public static void main(String[] args)    {        int x = 100, y = 88;        System.out.println("GCD of " + x + " and " + y                           + " is " + GCD(x, y));    }}
GCD of 100 and 88 is 4

Similarly, you can find the GCD or HCF of any two given numbers.
An efficient solution is to utilize a modulo operator in the Euclidean algorithm which is the foremost algorithm applied for this topic.
Example 2:
Java
// Java program to find GCD of two // numbers using Euclidean algorithmclass geeksforgeeks {    // Function to return gcd of x and y    // recursively    static int GCD(int x, int y)    {        if (y == 0)            return x;        return GCD(y, x % y);    }      // The Driver code    public static void main(String[] args)    {        int x = 47, y = 91;        System.out.println("The GCD of " + x + " and " + y                           + " is: " + GCD(x, y));    }}
The GCD of 47 and 91 is: 1

Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file 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?
Program to print ASCII Value of a character
How to Install Fabric in Python on Windows? - GeeksforGeeks

22 Sep, 2021
Fabric is a Python library used to execute shell commands remotely over SSH, yielding useful Python objects in return.. In this article, we will look into the process of installing the Fabric Library on Windows.
The only thing that you need for installing the Scrapy module on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:
conda install -c anaconda fabric
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if Fabric Library has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list fabric
You’ll get the below message if the installation is complete:
If you want the installation to be done through PIP,  open up the command Prompt and use the below command:
pip install fabric
You will get a similar message once the installation is complete:
To verify if the Fabric Library has been successfully installed in your system run the below command in Command Prompt:
python -m pip show fabric
You’ll get the below message if the installation is complete:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Lodash _.uniq() Method - GeeksforGeeks

19 Aug, 2020
The _.uniq method is used to create an array of unique values in order, from all given arrays using SameValueZero for equality comparisons.
Syntax:
_.union(array)

Parameters: This method accepts a single parameter as mentioned above and described below:
array: This parameter holds array to inspect.
Return Value: This method is used to return the new array of combined values.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = ([1, 2, 2, 3, 4, 3, 8, 6]);      // Use of _.uniq() // method  let gfg = _.uniq(y);      // Printing the output console.log(gfg);
Output:
[ 1, 2, 3, 4, 8, 6 ]

Example 2:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = (['a', 'b', 'c', 'e', 'd', 'd', 'g', 'i', 'i']);      // Use of _.uniq() // method  let gfg = _.uniq(y);      // Printing the output console.log(gfg);
Output:
[ 'a', 'b', 'c', 'e', 'd', 'g', 'i' ]

Example 3:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array let y = (['apple', 'banana', 'banana', 'chikoo',          'Elderberry', 'Damson   Date', 'guava', 'Damson Date']);      // Use of _.uniq() // method  let gfg = _.uniq(y);      // Printing the output console.log(gfg);
Output:
['apple', 'banana', 'chikoo', 'Elderberry', 'Damson Date', 'guava']

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to update data in a Collection using Python? - GeeksforGeeks

17 May, 2020
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
We can update data in a collection using update_one() method and update_many() method. 
Update_one() method updated first occurrence if query is found. 
Syntax :update_one(query, newvalues)
Parameters:Query: It is the query object. newvalues: It is the new values of the document. 
Example:
Sample Database:
Python3
import pymongo    client = pymongo.MongoClient("mongodb://localhost:27017/")  # Database namedb = client["GFG"]  # Collection namecol = db["gfg"]  # Query to be updatedquery = { "coursename": "SYSTEM DESIGN" }  # New valuenewvalue = { "$set": { "coursename": "Computer network" } }  # Update the valuecol.update_one(query, newvalue)
Output : 
update_many() method update all the query values.  
Syntax: update_many(query, newvalues)
Parameters:Query: It is the query object. newvalues: It is the new values of the document.
Example: 
Python3
import pymongo    client = pymongo.MongoClient("mongodb://localhost:27017/")  # Database namedb = client["GFG"]  # Collection namecol = db["gfg"]  # Query to be updatedquery = { "coursename": "SYSTEM DESIGN" }  # New valuenewvalue = { "$set": { "coursename": "Computer network" } }  # Update the valuecol.update_many(query, newvalue)
Output:
Python-mongoDB
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()
Node.js date-and-time Date.transform() Method - GeeksforGeeks

25 Mar, 2021
The date-and-time.Date.transform() method is used to transform date and time from the existing string format to new string format.
Required Module: Install the module by npm or used it locally.
By using npm:
npm install date-and-time --save
By using CDN link:
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
const transform(dateString, arg1, arg2[, utc])
Parameters: This API takes the following arguments as parameters.
dateString: String object of the date.
arg1: Existing string format.
arg2: New string format.
Return Value: This method returns a formatter string.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.transform() method  // Importing http moduleconst date = require('date-and-time')  // Creating object of current date and time // by using Datw() const now  =  new Date(07-03-2021);  // Changing the format of date and time// by using date.transform() apiconst value = date.transform(    now.toLocaleDateString(),    'D/M/YYYY', 'YYYY/M/D');  // Display the resultconsole.log("transformed date and time :- "     + value)
Output:
transformed date and time :- 1970/1/1
Example 2:
index.js
// Node.js program to demonstrate the  // Date.transform() method  // Importing http moduleconst date = require('date-and-time')  // Changing the format of date and time// by using date.transform() apiconst value = date.transform(    '23:14:05 GMT+0900',    'HH:mm:ss [GMT]Z', 'YYYY/M/D');  // Display the resultconsole.log("transformed date and time :- "      + value)
Output:
transformed date and time :- 1970/1/1
Reference: https://github.com/knowledgecode/date-and-time#transformdatestring-arg1-arg2-utc
Node.js-Methods
NodeJS date-time
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Drawing multiple legends on the same axes in Matplotlib

To draw multiple legends on the same axes in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots
Plot lines using two lists with different labels, linewidth and linestyle.
Place the first legend at the upper-right location.
Add artist, i.e., first legend on the current axis.
Place the second legend on the current axis at the lower-right location.
To display the figure, use show() method.
from matplotlib import pyplot as plt

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

line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)

first_legend = plt.legend(handles=[line1], loc='upper right')

plt.gca().add_artist(first_legend)
plt.legend(handles=[line2], loc='lower right')

plt.show()
time.Time.String() Function in Golang With Examples

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.String() function in Go language is used to yield the time which is formatted with the help of the format string. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) String() string

Here, “t” is the stated time.
Note: It the stated time has a clock reading that is monotonic then the string that is returned as an output includes a final field i.e, “m=±value”. Where value is the unvaried clock reading that is arranged as a decimal number of seconds.
Return Value: It returns the time which is formatted with the help of format string.
Example 1:
// Golang program to illustrate the usage of// Time.String() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining the time for String method    Time := time.Date(2020, 11, 14, 10, 45, 16, 0, time.UTC)      // Calling String method    t := Time.String()      // Prints output    fmt.Printf("The time without nanoseconds is: %v\n", t)}
Output:
The time without nanoseconds is: 2020-11-14 10:45:16 +0000 UTC

Example 2:
// Golang program to illustrate the usage of// Time.String() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining the time for String method    Time := time.Date(2020, 11, 14, 36, 45, 16, 36, time.UTC)      // Calling String method    t := Time.String()      // Prints output    fmt.Printf("The time with nanoseconds is: %v\n", t)}
Output:
The time with nanoseconds is: 2020-11-15 12:45:16.000000036 +0000 UTC

Here, the hour stated in the above code is out of usual range but it is normalized, while conversion and nanoseconds are also included in the time, stated above.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
Why import star in Python is a bad idea

08 Jan, 2020
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from which library does a particular function came from. The risk of overriding the variables/functions etc always persist with the import * practice.
Below are some points about why import * should not be used:
Code Readability
It is always remains a mystery what is imported and cannot be found easily from which module a certain thing was imported that result in low code readability.
Polluting the namespace, import * imports all the functions and classes in your own namespace that may clash with the function and classes you define or function and classes of other libraries that you may import.
Concrete possibility of hiding bugs
Tools like pyflakes can’t be used to statically detect errors in the source code.
All of this does not mean that using import * is always bad, if i had told you that there is nothing like import * thing on this universe you would have been craving for it. The only thing you should remember while using import * is that you should always use this carefully and with discipline maintained.
Now lets dive into an example to see the problem in a more practical and easy to understand way.
consider a package a that contains a function sum (a, b)
# import the module a using import * from a import *  # define a function sumdef sum (x, y):    return x + y  print (sum (2, 6))
the error with this code is that the sum function that we define overrides the sum function from the module ‘a’ that we imported and we don’t even have any idea about it. also it becomes very difficult to identify which function is actually being called in case of large programs.
Correct method:
# import the module a as limport a as l  def sum (x, y):    return x + y  # calls the self-defined sum functionprint (sum (2, 6))  # calls the sum function defined in the module aprint (l.sum(2, 6))
Coding this way increases code readability as well as it becomes easy to debug and there are almost zero chances that any conflict will occur.
ShivamShahi
Picked
python-basics
python-modules
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
MoviePy – Getting Cut Out of Video File Clip

27 Dec, 2021
In this article we will see how we can get the cut out of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Cut out video is the trimmed video or we can say it as some few seconds get cut from the original video, it is used to skip some part of the video. Cut out means to get the video from original video with skip of some time in between the video.
In order to do this we will use cutout method with the VideoFileClip objectSyntax : clip.cutout(ts, te)Argument : It takes two integer as argument (start and end time to skip)Return : It returns VideoFileClip 
Below is the implementation  
Python3
# Import everything needed to edit video clips from moviepy.editor import *     # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4")       # getting only first 5 seconds clip = clip.subclip(0, 15)    # cutting out some part from the clipclip = clip.cutout(3, 10)   # showing  clip clip.ipython_display(width = 360)
Output : 
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example 
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import *   # loading video gfgclip = VideoFileClip("geeks.mp4")   # getting only first 5 secondsclip = clip.subclip(0, 5)     # getting only first 5 seconds clip = clip.subclip(0, 10)    # cutting out some part from the clipclip = clip.cutout(3, 7)   # showing  clip clip.ipython_display(width = 360)
Output : 
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4 
 
germanshephered48
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
8086 program to print a String - GeeksforGeeks

10 Dec, 2021
Problem: Write an assembly level program to print a given string .
Examples:
Input String: "This is a sample string" 
Output: This is a sample string


Input String: "Geeks for Geeks" 
Output: Geeks for Geeks 
Explanation:
Create a stringLoad the effective address of the string in dx using LEA commandPrint the string by calling the interrupt with 9H in AHThe string must be terminated by ‘$’ sign
Create a string
Load the effective address of the string in dx using LEA command
Print the string by calling the interrupt with 9H in AH
The string must be terminated by ‘$’ sign
Program
.MODEL SMALL .STACK 100H .DATA   ;The string to be printed STRING DB 'This is a sample string', '$'  .CODE MAIN PROC FAR  MOV AX,@DATA  MOV DS,AX    ; load address of the string  LEA DX,STRING    ;output the string ;loaded in dx  MOV AH,09H INT 21H    ;interrupt to exit MOV AH,4CH INT 21H   MAIN ENDP END MAIN 
Output:
This is a sample string 
Note:The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program.
andrew1234
meetgor
Computer Organization and Architecture
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Computer Organization | Von Neumann architecture
Interrupts
Difference between Von Neumann and Harvard Architecture
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Computer Organization | Booth's Algorithm
Groovy - collect()

The method collect iterates through a collection, converting each element into a new value using the closure as the transformer.
List collect(Closure closure)

The Closure expression.
The modified list collection.
Following is an example of the usage of this method of the every method −
class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      def newlst = [];
      newlst = lst.collect {element -> return element * element}
      println(newlst);
   } 
}
When we run the above program, we will get the following result −
[1, 4, 9, 16]
Python | Pandas Index.drop()

16 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.drop() function make new Index with passed list of labels deleted. The function is similar to the Index.delete() except in this function we pass the label names rather than the position values.
Syntax: Index.drop(labels, errors=’raise’)
Parameters :labels : array-likeerrors : {‘ignore’, ‘raise’}, default ‘raise’If ‘ignore’, suppress error and existing labels are dropped.
Returns : dropped : IndexRaises : KeyError. If not all of the labels are found in the selected axis
Example #1: Use Index.drop() function to drop the passed labels from the Index.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])  # Print the Indexidx
Output :
Let’s drop the month of ‘Jan’ and ‘Dec’ from the Index.
# Passing a list containing the labels# to be dropped from the Indexidx.drop(['Jan', 'Dec'])
Output :
As we can see in the output, the function has returned an object which does not contain the labels that we passed to the Index.drop() function. Example #2: Use Index.drop() function to drop a list of labels in the Index containing datetime data.
# importing pandas as pdimport pandas as pd  # Creating the first Indexidx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',                '2016-02-08', '2017-05-05', '2014-02-11'])  # Print the Indexidx
Output :
Now, let’s drop some dates from the Index.
# Passing the values to be dropped from the Indexidx.drop(['2015-12-02', '2016-02-08'])
Output :As we can see in the output, the Index.drop() function has dropped the passed values from the Index.
Python pandas-indexing
Python-pandas
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
Python OOPs Concepts
Iterate over a list in Python
Ternary Operator in Java

A ternary operator uses 3 operands and it can be used to replace the if else statement. This can be done to make the code simpler and more compact.
The syntax of the ternary operator is given as follows −
Expression ? Statement 1 : Statement 2
In the above syntax, the expression is a conditional expression that results in true or false. If the value of the expression is true, then statement 1 is executed otherwise statement 2 is executed.
A program that demonstrates the ternary operator in Java is given as follows.
 Live Demo
public class Example {
   public static void main(String[] args) {
      Double num = -10.2;
      String str;
      str = (num > 0.0) ? "positive" : "negative or zero";
      System.out.println("The number " + num + " is " + str);
      }
}
The number -10.2 is negative or zero
Now let us understand the above program.
The number num is defined. Then the ternary operator is used. If num is greater than 0, str stores “positive”, otherwise it stores "negative or zero". Then this is displayed for the specified number. The code snippet that demonstrates this is given as follows.
Double num = -10.2;
String str;
str = (num > 0.0) ? "positive" : "negative or zero";
System.out.println("The number " + num + " is " + str);
numpy.greater() in Python

28 Mar, 2022
The numpy.greater() checks whether x1 is greater than x2 or not. Syntax : 
numpy.greater(x1, x2[, out]) 
Parameters : 
x1, x2 : [array_like]Input arrays. If x1.shape != x2.shape, they must be 
             broadcastable to a common shape 
out    : [ndarray, boolean]Array of bools, or a single bool if x1 and x2 are scalars.
Return : 
Boolean array indicating results, whether x1 is greater than x2 or not.
Code 1 : 
Python
# Python Program illustrating# numpy.greater() method  import numpy as geek a  = geek.greater([8., 2.], [5., 3.])print("Not equal : \n", a, "\n") b = geek.greater([2, 2], [[1, 3],[1, 4]])print("Not equal : \n", b, "\n") a = geek.array([4,2])b = geek.array([6,2]) print("Is a greater than b : ", a > b)
Output : 
Not equal : 
 [ True False] 

Not equal : 
 [[ True False]
 [ True False]] 

Is a greater than b :  [False False]
Code 2 : 
Python
# Python Program illustrating# numpy.greater() method   import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2])  # indicating 1.1 is greater than 1print("Comparing float with int : ", a < b) # indicating 1.1 is greater than 1d  = geek.greater(a, b)print("\n Comparing float with int using  .greater() : ", d)
Output : 
Comparing float with int :  [False  True]

 Comparing float with int using  .greater() :  [ True False]
Code 3 : 
Python
# Python Program illustrating# numpy.greater() method   import numpy as geek # Here we will compare Complex values with inta = geek.array([1j,2])b = geek.array([1,2])  # indicating 1j is greater than 1print("Comparing complex with int : ", a < b) # indicating 1j is greater than 1d  = geek.greater(a, b)print("\nComparing complex with int using .greater() : ", d)
Output : 
Comparing complex with int :  [ True False]

Comparing complex with int using .greater() :  [False False]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.greater.html#numpy.greater Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
vinayedula
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Problem solving on scatter matrix

03 Feb, 2022
Prerequisite : Scatter Plot Matrix
We calculate Sw  ( within class scatter matrix ) and SB ( between class scatter matrix )  for the available data points.
SW : To minimize variability within a class, inner class scatter.SB :  To increase between class variability, between class scatter.
scatter plot of the points
X1 = (y1, y2) ={ (2,2), (1,2), (1,2), (1,2), (2,2) }
X2 = (y1,y2) ={ (9, 10), (6,8), (9,5), (8,7), (10,8) }
Within class scatter matrix :
Si is the class specific covariance matrix.
mi is the mean of individual class
Mean computation :
We calculate the mean for each of the points present in the class. Here mean is the total sum of observations divided by the number of observations, we require this mean for calculating the covariance of the matrix.
Covariance matrix computation :We subtract the mean value from each of the observation and then we calculate the average after performing the matrix multiplication with the transpose of the matrix.
Class specific covariance for the first class :
Averaging values from 1,2,3,4 and 5.We calculate the sum of all the values for each element in the matrix for S1 and divide by the number of the observation which in the present computation is 5.
Therefore S1 is :
Class specific covariance for the second class :
Averaging values from 1,2,3,4 and 5we calculate the sum of all the values for each element in the matrix for S2 and divide by the number of the observation which in the present computation is 5.
Therefore S2 is :
Within class scatter matrix Sw :
SW = S1 + S2
Between class scatter matrix SB  :
Total scatter matrix :
ST = SB + SW
Therefore we have calculated between class scatter matrix and within class scatter matrix for the available data points.
We make use of these computations in feature extraction , where the main goal is to increase the distance between the class in the projection of points and decrease the distance between  the points within the class in the projection. Here we aim at generating data projection at the required dimension. 
sumitgumber28
data-science
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Activation Functions
Logic Notations in LaTeX
Mathematics | Introduction of Set theory
Modular Arithmetic
Introduction of Statistics and its Types
Difference between Spline, B-Spline and Bezier Curves
Mathematics | Set Operations (Set theory)
Brackets in Latex
Proof that vertex cover is NP complete
Python | Calculate difference between adjacent elements in given list

28 Feb, 2019
Given a list, the task is to create a new list containing difference of adjacent elements in the given list.
Method #1: Using zip()
# Python code to demonstrate# to calculate difference# between adjacent elements in list    # initialising _listini_list = [5, 4, 89, 12, 32, 45]  # printing iniial_listprint("intial_list", str(ini_list))  # Calculating difference listdiff_list = []for x, y in zip(ini_list[0::], ini_list[1::]):    diff_list.append(y-x)      # printing difference listprint ("difference list: ", str(diff_list))        
intial_list [5, 4, 89, 12, 32, 45]
difference list:  [-1, 85, -77, 20, 13]

 Method #2: Using Naive approach
# Python code to demonstrate# to calculate difference# between adjacent elements in list    # initialising _listini_list = [5, 4, 89, 12, 32, 45]  # printing iniial_listprint("intial_list", str(ini_list))  # Calculating difference listdiff_list = []  for i in range(1, len(ini_list)):    diff_list.append(ini_list[i] - ini_list[i-1])  # printing difference listprint ("difference list: ", str(diff_list))
intial_list [5, 4, 89, 12, 32, 45]
difference list:  [-1, 85, -77, 20, 13]

 Method #3: Using numpy
# Python code to demonstrate# to calculate difference# between adjacent elements in list  import numpy as np# initialising _listini_list = np.array([5, 4, 89, 12, 32, 45])  # printing iniial_listprint("intial_list", str(ini_list))  # Calculating difference listdiff_list = np.diff(ini_list)  # printing difference listprint ("difference list: ", str(diff_list))
intial_list [ 5  4 89 12 32 45]
difference list:  [ -1  85 -77  20  13]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Number of values greater than K in list

One of the basic problems for many complex problems is finding numbers greater than certain number in list in python, is commonly encountered.
 Live Demo
# find number of elements > k using for loop
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using for loop to get numbers > k
count = 0
for i in test_list :
   if i > k :
      count = count + 1
# printing the intersection
print ("The numbers greater than 4 : " + str(count))    
# find number of elements > k using list comprehension
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using list comprehension to get numbers > k
count = len([i for i in test_list if i > k])
# printing the intersection
print ("The numbers greater than 4 : " + str(count))
# find number of elements > k using sum()
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using sum() to get numbers > k
count = sum(i > k for i in test_list)
# printing the intersection
print ("The numbers greater than 4 : " + str(count))
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
Accessing variables of two interfaces, which are same from an implementing class in java?

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
You can implement multiple interfaces using a single class in Java. Whenever both interfaces have same name, since all the fields of an interface are static by default, you can access them using the name of the interface as −
interface MyInterface1{
   public static int num = 100;
   public void display();
}
interface MyInterface2{
   public static int num = 1000;
   public void show();
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public static int num = 10000;
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      System.out.println("num field of the interface MyInterface1"+MyInterface1.num);
      System.out.println("num field of the interface MyInterface2"+MyInterface2.num);
      System.out.println("num field of the class InterfaceExample "+obj.num);
   }
}
num field of the interface MyInterface1 100
num field of the interface MyInterface2 1000
num field of the class InterfaceExample 10000
JUnit - Exceptions Test

JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.
Create a java class to be tested, say, MessageUtil.java in C:\> JUNIT_WORKSPACE.
Add an error condition inside the printMessage() method.
/*
* This class prints the given message on console.
*/

public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message; 
   }

   // prints the message
   public void printMessage(){
      System.out.println(message);
      int a = 0;
      int b = 1/a;
   }   

   // add "Hi!" to the message
   public String salutationMessage(){
      message = "Hi!" + message;
      System.out.println(message);
      return message;
   }   
}  	
Create a java test class called TestJunit.java. Add an expected exception ArithmeticException to the testPrintMessage() test case.
Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit {

   String message = "Robert";	
   MessageUtil messageUtil = new MessageUtil(message);
   
   @Test(expected = ArithmeticException.class)
   public void testPrintMessage() {	
      System.out.println("Inside testPrintMessage()");     
      messageUtil.printMessage();     
   }

   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Robert";
      assertEquals(message,messageUtil.salutationMessage());
   }
}
Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
		
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
}  	
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java

Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner

Verify the output. testPrintMessage() test case will be passed.
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
true


    24 Lectures 
     2.5 hours 

 Nishita Bhatt

    56 Lectures 
     7.5 hours 

 Dinesh Varyani
 Print
 Add Notes
 Bookmark this page