code-rag-bench/online-tutorials huggingface dataset:
Rexx - do Loop

The do loop is used to execute a number of statements for a certain number of times. The number of times that the statement needs to be executed is determined by the value passed to the do loop.
The syntax of the do loop statement is as follows −
do count 
   statement #1 
   statement #2 
   ... 
End 

Statement#1 and Statement#2 are a series of a block of statements that get executed in the do loop. The count variable symbolizes the number of times the do loop needs to be executed.
The following diagram shows the diagrammatic explanation of this loop.
The key point to note about this loop is that the do loop will execute based on the value of the count variable.
The following program is an example of a do loop statement.
/* Main program */ 
do 5 
   say "hello" 
end 
The following key points need to be noted about the above program −
The count in the above case is 5. So the do loop will be run for 5 times.
The count in the above case is 5. So the do loop will be run for 5 times.
In the do loop, the phrase hello is displayed to the console.
In the do loop, the phrase hello is displayed to the console.
The output of the above program will be −
hello 
hello 
hello 
hello 
hello 

 Print
 Add Notes
 Bookmark this page
PHP | join() Function

08 Jan, 2018
The join() function is built-in function in PHP and is used to join an array of elements which are separated by a string.
Syntax
string join( $separator, $array)
Parameter: The join() function accepts two parameter out of which one is optional and one is mandatory.
$separator : This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the $separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string)
$array : The array whose value is to be joined to form a string.
Return Type: The return type of join() function is string. It will return the joined string formed from the elements of $array.
Examples:
Input : join(array('Geeks','for','Geeks')
Output : GeeksforGeeks

Input : join("-",array('Geeks','for','Geeks')
Output : Geeks-for-Geeks

Below program illustrates the working of join() function in PHP:
<?php    // PHP Code to implement join function          $InputArray = array('Geeks','for','Geeks');          // Join without separator    print_r(join($InputArray));          print_r("\n");          // Join with separator    print_r(join("-",$InputArray));?>
Output:
GeeksforGeeks
Geeks-for-Geeks

Functions
PHP-string
Web Technologies
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to create footer to stay at the bottom of a Web page?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
File uploading in React.js
Instagram-explore module in Python

20 Aug, 2020
instagram-explore module is an Instagram scrapping module.
Run the following pip command :
pip install instagram-explore

This module has 8 functions currently for exploring Instagram:
Getting user informationGetting tagGetting user imagesGetting locationsLocationLocation imagesMediaMedia images
Getting user information
Getting tag
Getting user images
Getting locations
Location
Location images
Media
Media images
Example 1 : To get information about a user we will use the user() method.
ie.user("username", max_id = None)

It will give html of page i.e. the homepage of the Instagram profile
Python3
# import the modulesimport instagram_explore as ieimport json  # search user nameresult = ie.user('timesofindia')  parsed_data= json.dumps(result, indent = 4,                        sort_keys = True)  # displaying the dataprint(parsed_data[15:400])
Output :
 “biography”: “The Times of India is India\u2019s most-read English newspaper and World\u2019s largest-selling English newspaper – A Times Internet Limited Product”,
       “blocked_by_viewer”: false,
       “business_category_name”: “Publishers”,
       “business_email”: “toisocialmedia@gmail.com”,
       “category_enum”: “BROADCASTING_MEDIA_PRODUCTION”,
       “connected_fb_p
Example 2 : Getting user images
If account is private – > Null is returned else links of images are returned sorted as latest.
Python3
# importing the modulesimport instagram_explore as ieimport json  res = ie.user_images('timesofindia')  parsed_data = json.dumps(res, indent = 4,                        sort_keys = True)  # displaying the dataprint(parsed_data)
Output :
Here only one link is being displayed.
https://scontent-del1-1.cdninstagram.com/v/t51.2885-15/fr/e15/s1080x1080/117758575_167564261503193_2290116502716246854_n.jpg?_nc_ht=scontent-del1-1.cdninstagram.com&_nc_cat=105&_nc_ohc=4Yds4Fv58wUAX-4Pgra&oh=eaa3b5b243433239e134e427f340049c&oe=5F666630
Example 3 : Searching Tags 
By the tag() function, we will get information about the searched tag 
variable = ie.tag("Name_of_tag", max_id = None)

Python3
# importing the modulesimport instagram_explore as ieimport json  # using the tag methodresult = ie.tag('Binod')  parsed_data = json.dumps(result, indent = 4,                          sort_keys = True)  # displaying the dataprint(parsed_data)
Output : 
Example 4 : Getting images by tag
Python3
# importing the modulesimport instagram_explore as ieimport json  # Search user nameresult = ie.tag_images('Binod')  parsed_data = json.dumps(result, indent = 4,                          sort_keys = True)  # displaying the dataprint(parsed_data)
Output :
.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to create a canvas ellipse using Fabric.js ?

08 Feb, 2022
In this article, we are going to see how to create a canvas ellipse using FabricJS. The canvas means ellipse is movable and can be stretched according to requirement. Further, the ellipse can be customized when it comes to initial stroke color, fill color, stroke width or radius.Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our ellipse. After this, we will initialize instances of Canvas and Ellipse provided by FabricJS and render the Ellipse on the Canvas as given in the example below.Syntax:  
 fabric.Ellipse({
            rx: number,
            ry: number,
            radius: number,
            fill: string,
            stroke: string,
            strokeWidth: int
        }); 
Parameters: This function accepts six parameters as mentioned above and described below:  
rx: It specifies the horizontal radius.
ry: It specifies the vertical radius.
radius: It specifies the radius.
fill: It specifies the fill colour.
stroke: It specifies the stroke colour.
strokeWidth: It specifies the width of stroke.
Program: This example uses FabricJS to create simple editable canvas-like ellipse as given below:  
html
<!DOCTYPE html><html> <head>    <title>        How to create a canvas-type        ellipse with JavaScript?    </title>     <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head> <body>    <canvas id="canvas"            width="600" height="200"            style="border:1px solid #000000">    </canvas>     <script>         // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");         // Initiate a Ellipse instance        var ellipse = new fabric.Ellipse({            rx: 80,            ry: 40,            fill: '',            stroke: 'green',            strokeWidth: 3        });         // Render the Ellipse in canvas        canvas.add(ellipse);    </script></body> </html>
Output:  
 
blalverma92
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
StringBuffer toString() method in Java with Examples

04 Dec, 2018
The toString() method of StringBuffer class is the inbuilt method used to returns a string representing the data contained by StringBuffer Object. A new String object is created and initialized to get the character sequence from this StringBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.
Syntax:
public abstract String toString()
Return Value: This method returns the String representing the data contained by StringBuffer Object.
Below programs illustrate the StringBuffer.toString() method:
Example 1:
// Java program to demonstrate// the toString() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuffer object        // with a String pass as parameter        StringBuffer str            = new StringBuffer("GeeksForGeeks");          // print string        System.out.println("String contains = "                           + str.toString());    }}
String contains = GeeksForGeeks

Example 2:
// Java program to demonstrate// the toString() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuffer object        // with a String pass as parameter        StringBuffer str            = new StringBuffer(                "Geeks for Geeks contribute");          // print string        System.out.println("String contains = "                           + str.toString());    }}
String contains = Geeks for Geeks contribute

References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#toString()
java-basics
Java-Functions
Java-lang package
java-StringBuffer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Introduction to Java
Constructors in Java
java.time.LocalDate.isBefore() Method Example

The java.time.LocalDate.isBefore(ChronoLocalDate other) method checks if this date is before the specified date.
Following is the declaration for java.time.LocalDate.isBefore(ChronoLocalDate other) method.
public boolean isBefore(ChronoLocalDate other)

other − the other date to compare to, not null.
true if this date is before the specified date.
The following example shows the usage of java.time.LocalDate.isBefore(ChronoLocalDate other) method.
package com.tutorialspoint;

import java.time.LocalDate;

public class LocalDateDemo {
   public static void main(String[] args) {
	  
      LocalDate date = LocalDate.parse("2017-02-03");
      LocalDate date1 = LocalDate.parse("2017-03-03");
      System.out.println(date1.isBefore(date));  
   }
}
Let us compile and run the above program, this will produce the following result −
Formatted Output in Java

String provides format() method can be used to print formatted output in java.
String provides format() method can be used to print formatted output in java.
System.out.printf() method can be used to print formatted output in java.
System.out.printf() method can be used to print formatted output in java.
Following example returns a formatted string value by using a specific locale, format and arguments in format() method
import java.util.*;

public class StringFormat {
   public static void main(String[] args) {

      double e = Math.E;
      System.out.format("%f%n", e);
      System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
   }
}
The above code sample will produce the following result.
2.718282
2,7183
The following is an another sample example of format strings.
public class HelloWorld {
   public static void main(String []args) {

      String name = "Hello World";
      String s1 = String.format("name %s", name);
      String s2 = String.format("value %f",32.33434);
      String s3 = String.format("value %32.12f",32.33434);
      System.out.print(s1);
      System.out.print("\n");
      System.out.print(s2);
      System.out.print("\n");
      System.out.print(s3);
      System.out.print("\n");
   }
}
The above code sample will produce the following result.
name Hello World
value 32.334340
value 32.334340000000
chgrp - Unix, Linux Command

chgrp - To change group ownership.
chgrp [Options]... {Group | --reference=File} File...
'chgrp' command changes the group ownership of each given File to Group (which can be either a group name or a numeric group id) or to match the same group as an existing reference file.
To Make oracleadmin the owner of the database directory
$ chgrp oracleadmin /usr/database


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Find a matrix or vector norm using NumPy - GeeksforGeeks

06 Jun, 2021
To find a matrix or vector norm we use function numpy.linalg.norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters. 
Syntax: numpy.linalg.norm(x, ord=None, axis=None)Parameters: x: input ord: order of norm axis: None, returns either a vector or a matrix norm and if it is an integer value, it specifies the axis of x along which the vector norm will be computed  
Example 1:  
Python3
# import libraryimport numpy as np # initialize vectorvec = np.arange(10) # compute norm of vectorvec_norm = np.linalg.norm(vec) print("Vector norm:")print(vec_norm)
Output: 
Vector norm:
16.881943016134134
The above code computes the vector norm of a vector of dimension (1, 10)Example 2:  
Python3
# import libraryimport numpy as np # initialize matrixmat = np.array([[ 1, 2, 3],               [4, 5, 6]]) # compute norm of matrixmat_norm = np.linalg.norm(mat) print("Matrix norm:")print(mat_norm)
Output: 
Matrix norm:
9.539392014169456
Here, we get the matrix norm for a matrix of dimension (2, 3)Example 3: To compute matrix norm along a particular axis –  
Python3
# import libraryimport numpy as np  mat = np.array([[ 1, 2, 3],               [4, 5, 6]]) # compute matrix num along axismat_norm = np.linalg.norm(mat, axis = 1) print("Matrix norm along particular axis :")print(mat_norm)
Output: 
Matrix norm along particular axis :
[3.74165739 8.77496439]
This code generates a matrix norm and the output is also a matrix of shape (1, 2)Example 4:  
Python3
# import libraryimport numpy as np # initialize vectorvec = np.arange(9) # convert vector into matrixmat = vec.reshape((3, 3)) # compute norm of vectorvec_norm = np.linalg.norm(vec) print("Vector norm:")print(vec_norm) # computer norm of matrixmat_norm = np.linalg.norm(mat) print("Matrix norm:")print(mat_norm)
Output: 
Vector norm:
14.2828568570857
Matrix norm:
14.2828568570857
From the above output, it is clear if we convert a vector into a matrix, or if both have same elements then their norm will be equal too. 
simmytarika5
Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
Python Tkinter – How do I change the text size in a label widget?

Tkinter Label Widgets are used to create labels in a window. We can style the widgets using the tkinter.ttk package. In order to resize the font-size, font-family and font-style of Label widgets, we can use the inbuilt property of font(‘font-family font style’, font-size).
In this example, we will create buttons that will modify the style of Label text such as font-size and font-style.
#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x250")

#Define all the functions
def size_1():
   text.config(font=('Helvatical bold',20))

def size_2():
   text.config(font=('Helvetica bold',40))

#Create a Demo Label to which the changes has to be done
text=Label(win, text="Hello World!")
text.pack()

#Create a frame
frame= Frame(win)

#Create a label
Label(frame, text="Select the Font-Size").pack()

#Create Buttons for styling the label
button1= Button(frame, text="20", command= size_1)
button1.pack(pady=10)

button2= Button(frame, text="40", command=size_2)
button2.pack(pady=10)

frame.pack()
win.mainloop()
Running the above code will display a window containing a text Label. The buttons can be used to change the font-size of the text label.
Now, select to change the font-size of the Text Label widget.
Java 8 Streams and its operations

Streams are sequences of objects from a source, which support aggregate operations. These were introduced in Java 8.
With Java 8, Collection interface has two methods to generate a Stream.
stream() − Returns a sequential stream considering collection as its source.
stream() − Returns a sequential stream considering collection as its source.
parallelStream() − Returns a parallel Stream considering collection as its source.
parallelStream() − Returns a parallel Stream considering collection as its source.
Some operations on streams are −
sorted − The sorted method is use to sort the stream lexicographically or in ascending order
List id = Arrays.asList("Objects","Classes","Interfaces");
List output = id.stream().sorted().collect(Collectors.toList());
map − The map method maps the elements in the collection to other objects according to the Predicate passed as a parameter
List list1= Arrays.asList(1,3,5,7);
List finalList = list1.stream().map(a -> a * a * a).collect(Collectors.toList());
filter − The filter method is used to select elements according to the Predicate parameter passed
List id = Arrays.asList(“Classes","Methods","Members");
List output = id.stream().filter(s -> s.startsWith("M")).collect(Collectors.toList());
The three operations above are intermediate operations. Now let us have a look at the terminal operations
collect − The collect method returns the outcome of the intermediate operations
List id = Arrays.asList(“Classes","Methods","Members");
List output = id.stream().filter(s -> s.startsWith("M")).collect(Collectors.toList());
forEach − This method iterates through every element in the stream
List list1 = Arrays.asList(1,3,5,7);
List finalList = list1.stream().map(a ->a * a * a).forEach(b->System.out.println(b));
Let us see an example which illustrates the use of Stream −
 Live Demo
import java.util.*;
import java.util.stream.*;
public class Example {
   public static void main(String args[]) {
      List<Integer> list1 = Arrays.asList(11,22,44,21); //creating an integer list
      List<String> id = Arrays.asList("Objects","Classes","Methods");
      //creating a String list
      // map method
      List<Integer> answer = list1.stream().map(x -> x*x).collect(Collectors.toList());
      System.out.println(answer);
      // filter method
      List<String> output = id.stream().filter(x->x.startsWith("M")).collect(Collectors.toList());
      System.out.println(output);
   }
}
[121, 484, 1936, 441]
[Methods]
casefold() string in Python

This function is helpful in converting the letters of a word into lowercase. When applied to two strings it can match their values irrespective of the type up of the case of the letters.
The below example we apply the casefold() function to a string and the result comes out in all lower case letters.
string = "BestTutorials"
# print lowercase string
print(" lowercase string: ", string.casefold())
Running the above code gives us the following result −
Lowercase String: besttutorials
We can compare two strings which have same letters but in different cases after applying the casefold() function. The result of the comparison gives a match of equality to the two words.
string1 = "Hello Tutorials"
string2 = "hello tutorials"
string3 = string1.casefold()
if string2==string3:
   print("String2 and String3 are equal")
elif string1 != string3:
   print("Strings are not equal")
Running the above code gives us the following result −
String2 and String3 are equal
Count Numbers with Unique Digits in C++

Suppose we have a non-negative integer n. We have to count all numbers with unique digits x, where x is in range 0 to 10^n. So if the number n is 2, then the result will be 91, as we want to find numbers from 0 to 100 without 11, 22, 33, 44, 55, 66, 77, 88, 99.
To solve this, we will follow these steps −
if n is 0, then return 1
if n is 0, then return 1
n := min of 10 and n
n := min of 10 and n
if n is 1, then return 10
if n is 1, then return 10
ans := 9 and ret := 10
ans := 9 and ret := 10
for i in range 2 to nans := ans * (9 – i + 2)ret := ret + ans
for i in range 2 to n
ans := ans * (9 – i + 2)
ans := ans * (9 – i + 2)
ret := ret + ans
ret := ret + ans
return ret
return ret
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int countNumbersWithUniqueDigits(int n) {
      if(n == 0)return 1;
      n = min(10, n);
      if(n == 1)return 10;
      int ans = 9;
      int ret = 10;
      for(int i = 2; i<= n; i++){
         ans *= (9 - i + 2);
         ret += ans;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.countNumbersWithUniqueDigits(3));
}
3
739
Sorting Operators in LINQ

A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         int[] num = { -20, 12, 6, 10, 0, -3, 1 };
			
         //create a query that obtain the values in sorted order
         var posNums = from n in num
                       orderby n
                       select n;
							  
         Console.Write("Values in ascending order: ");
     
         // Execute the query and display the results.
		 
         foreach (int i in posNums) 
            Console.Write(i + " \n");

            var posNumsDesc = from n in num
                              orderby n descending
                              select n;
										
            Console.Write("\nValues in descending order: ");

         // Execute the query and display the results.
		 
         foreach (int i in posNumsDesc) 
            Console.Write(i + " \n");

            Console.ReadLine();
      }
   }
}
Module Module1

   Sub Main()
   
      Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1};

      Dim posNums = From n In num
                    Order By n
                    Select n;
						  
      Console.Write("Values in ascending order: ");

      For Each n In posNums
         Console.WriteLine(n)
      Next
 
      Dim posNumsDesc = From n In num
                       Order By n Descending
                       Select n;
							  
         Console.Write("Values in descending order: ");

      For Each n In posNumsDesc
         Console.WriteLine(n)
		
      Next
         Console.ReadLine()
		
   End Sub
  
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
Values in ascending order: -20 
-3 
0 
1 
6 
10 
12
Values in descending order: 12 
10 
6 
1 
0 
-3 
-20

In Thenby and ThenbyDescending operators, same syntax can be applied and sorting order will depend on more than one columns. Priority will be the column which is maintained first.

    23 Lectures 
     1.5 hours 

 Anadi Sharma

    37 Lectures 
     13 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Input/Output Operators Overloading in C++

C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<.  The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object.
Following example explains how extraction operator >> and insertion operator <<.
#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      friend ostream &operator<<( ostream &output, const Distance &D ) { 
         output << "F : " << D.feet << " I : " << D.inches;
         return output;            
      }

      friend istream &operator>>( istream  &input, Distance &D ) { 
         input >> D.feet >> D.inches;
         return input;            
      }
};

int main() {
   Distance D1(11, 10), D2(5, 11), D3;

   cout << "Enter the value of object : " << endl;
   cin >> D3;
   cout << "First Distance : " << D1 << endl;
   cout << "Second Distance :" << D2 << endl;
   cout << "Third Distance :" << D3 << endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Git - Push Operation

Jerry modified his last commit by using the amend operation and he is ready to push the changes. The Push operation stores data permanently to the Git repository. After a successful push operation, other developers can see Jerry’s changes.
He executes the git log command to view the commit details.
[jerry@CentOS project]$ git log

The above command will produce the following result:
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530

Changed return type of my_strlen to size_t

Before push operation, he wants to review his changes, so he uses the git show command to review his changes.
[jerry@CentOS project]$ git show d1e19d316224cddc437e3ed34ec3c931ad803958

The above command will produce the following result:
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530

Changed return type of my_strlen to size_t

diff --git a/string.c b/string.c
new file mode 100644
index 0000000..7da2992
--- /dev/null
+++ b/string.c
@@ -0,0 +1,24 @@
+#include <stdio.h>
+
+size_t my_strlen(char *s)
+
{
   +
   char *p = s;
   +
   +
   while (*p)
   + ++p;
   + return (p -s );
   +
}
+
+int main(void)
+
{
   + int i;
   + char *s[] = 
   {
      + "Git tutorials",
      + "Tutorials Point"
      +
   };
   +
   +
   +
   for (i = 0; i < 2; ++i)
   printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i]));
   +
   +
   return 0;
   +
}

Jerry is happy with his changes and he is ready to push his changes.
[jerry@CentOS project]$ git push origin master

The above command will produce the following result:
Counting objects: 4, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 517 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
19ae206..d1e19d3 master −> master

Jerry’s changes have been successfully pushed to the repository; now other developers can view his changes by performing clone or update operation.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    23 Lectures 
     2 hours 

 Asif Hussain

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    125 Lectures 
     9 hours 

 John Shea

    13 Lectures 
     2.5 hours 

 Raghu Pandey

    13 Lectures 
     3 hours 

 Sebastian Sulinski
 Print
 Add Notes
 Bookmark this page
Linear search in Java.

Following is the required program.
Live Demo
public class Tester {
   public static int linearSearch(int[] arr, int element) {
      for (int i = 0; i < arr.length; i++) {
         if (arr[i] == element) {
            return i;
         }
      }
      return -1;
   }
   public static void main(String a[]) {
      int[] array = { 10, 20, 30, 50, 70, 90 };
      int element = 50;
      int index = linearSearch(array, element);
      if (index != -1) {
         System.out.println(element + " present at index: " +index);
      } else {
         System.out.println(element + " is not present.");
      }
   }
}
50 present at index: 3
How can we parse a nested JSON object in Java?

The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. A JSONArray can parse text from a String to produce a vector-like object. We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index).getString() method and it returns a string value at the specified position.
String getString(int index)
import java.util.*;
import org.json.*;
public class NestedJSONObjectTest {
   public static void main(String args[]) {
      String jsonDataString = "{userInfo : [{username:abc123}, {username:xyz123},{username:pqr123},   {username:mno123},{username:jkl123}]}";
      JSONObject jsonObject = new JSONObject(jsonDataString);
      List<String> list = new ArrayList<String>();
      JSONArray jsonArray = jsonObject.getJSONArray("userInfo");
      for(int i = 0 ; i < jsonArray.length(); i++) {
         list.add(jsonArray.getJSONObject(i).getString("username"));
         System.out.println(jsonArray.getJSONObject(i).getString("username")); // display usernames
      }
   }
}
abc123
xyz123
pqr123
mno123
jkl123
Python | os.path.dirname() method

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.dirname() method in Python is used to get the directory name from the specified path.
Syntax: os.path.dirname(path)
Parameter:path: A path-like object representing a file system path.
Return Type: This method returns a string value which represents the directory name from the specified path.
Code: Use of os.path.dirname() method
# Python program to explain os.path.dirname() method     # importing os.path module import os.path  # Pathpath = '/home/User/Documents'  # Get the directory name  # from the specified pathdirname = os.path.dirname(path)  # Print the directory name  print(dirname)    # Pathpath = '/home/User/Documents/file.txt'  # Get the directory name  # from the specified pathdirname = os.path.dirname(path)  # Print the directory name  print(dirname)    # Pathpath = 'file.txt'  # Get the directory name  # from the specified pathdirname = os.path.dirname(path)  # Print the directory name  print(dirname)  # In the above specified path # does not contains any# directory so, # It will print Nothing  
/home/User
/home/User/Documents


Reference: https://docs.python.org/3/library/os.path.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Calculate standard deviation of a Matrix in Python

26 Nov, 2020
In this article we will learn how to calculate standard deviation of a Matrix using Python.
Standard deviation is used to measure the spread of values within the dataset. It indicates variations or dispersion of values in the dataset and also helps to determine the confidence in a model’s statistical conclusions. It is represented by the sigma (σ) and calculates by taking the square root of the variance. If the standard deviation is low it means most of the values are closer to the mean and if high, that means closer to the mean. In this article, we will learn what are the different ways to calculate SD in Python.
We can calculate the Standard Deviation using the following method : 
std() method in NumPy packagestdev() method in Statistics package
std() method in NumPy package
stdev() method in Statistics package
Method 1:std() method in NumPy package.
Python3
# import required packagesimport numpy as np  # Create matrixmatrix = np.array([[33, 55, 66, 74], [23, 45, 65, 27],                  [87, 96, 34, 54]])  print("Your matrix:\n", matrix)  # use std() methodsd = np.std(matrix)print("Standard Deviation :\n", sd)
Output :
Your matrix:
[[33 55 66 74]
[23 45 65 27]
[87 96 34 54]]
Standard Deviation :
22.584870796373593

Method 2: stdev() method in Statistics package.
Python3
import statistics    statistics.stdev([11, 43, 56, 77, 87, 45, 67, 33])
Output :
24.67466890789592

Python-Matrix
Technical Scripter 2020
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Left rotation of an array using vectors in C++

01 Jun, 2022
Given an array arr[] of integers and another integer D, the task is to perform D left rotations on the array and print the modified array.
Examples: 
Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 2
Output: 3 4 5 6 1 2

Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 12
Output: 1 2 3 4 5 6
Approach: Using vectors in C++, a rotation can be performed by removing the first element from the vector and then inserting it in the end of the same vector. Similarly, all the required rotations can be performed and then print the contents of the modified vector to get the required rotated array.
Below is the implementation of the above approach:
CPP
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to left rotate the array by d elements// here we are passing vector by reference to avoid copying// that just make our program slowvoid rotate(vector<int>& vec, int d){    // Base case    if (d == 0)        return;     // Push first d elements from the beginning    // to the end and remove those elements    // from the beginning    for (int i = 0; i < d; i++)    {        // adding first element at        // the end of vector        vec.push_back(vec[0]);               // removing first element        vec.erase(vec.begin());    }     // Print the rotated array    for (int i = 0; i < vec.size(); i++)    {        cout << vec[i] << " ";    }} // Driver codeint main(){    vector<int> vec = { 1, 2, 3, 4, 5, 6 };    int n = vec.size();    int d = 2;     // Function call    rotate(vec, d % n);     return 0;}
3 4 5 6 1 2 
Time Complexity: O(n)Auxiliary Space: O(1)
prerna_mehraa
sachinvinod1904
rotation
Arrays
C++ Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Difference between sums of odd and even digits

09 Jun, 2022
Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for the leftmost digit).
Examples:
Input : 1212112
Output : Yes
Explanation:-
the odd position element is 2+2+1=5
the even position element is 1+1+1+2=5
the difference is 5-5=0.so print yes.
Input :12345
Output : No
Explanation:-
the odd position element is 1+3+5=9
the even position element is 2+4=6
the difference is 9-6=3 not  equal
to zero. So print no.
Method 1: One by one traverse digits and find the two sums. If the difference between two sums is 0, print yes, else no.
Python3
# Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not # Reading Inputnum = int(input())string1 = str(num)evensum = 0oddsum = 0  # Driver Codefor i in range(0, len(string1)):    if(i % 2 == 0):        evensum += int(string1[i])    else:        oddsum += int(string1[i])  # Conditionif(oddsum-evensum == 0):    print("Yes")else:    print("No")
Yes

Method 2: This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not. 
Example
Python
# Python program to check if difference between sum of# odd digits and sum of even digits is 0 or not  def isDiff(n):    return (n % 11 == 0)  # Driver coden = 1243if (isDiff(n)):    print("Yes")else:    print("No")
Yes

Please refer complete article on Difference between sums of odd and even digits for more details!
kogantibhavya
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Swing Examples - Show a Modal Dialog

Following example showcase how to create a modal dialog in swing based application.
We are using the following APIs.
JDialog − To create a standard dialog box.
JDialog − To create a standard dialog box.
JDialog.getContentPane() − To get the content panel of the dialog box.
JDialog.getContentPane() − To get the content panel of the dialog box.
Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box.
Dialog.ModalityType.DOCUMENT_MODAL − To show a dialog box as a modal dialog box.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JDialog modelDialog = createDialog(frame);
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            modelDialog.setVisible(true);
         }
      });

      panel.add(button);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }   

   private static JDialog createDialog(final JFrame frame){
      final JDialog modelDialog = new JDialog(frame, "Swing Tester", 
         Dialog.ModalityType.DOCUMENT_MODAL);
      modelDialog.setBounds(132, 132, 300, 200);
      Container dialogContainer = modelDialog.getContentPane();
      dialogContainer.setLayout(new BorderLayout());
      dialogContainer.add(new JLabel("                         Welcome to Swing!")
      , BorderLayout.CENTER);    
      JPanel panel1 = new JPanel();
      panel1.setLayout(new FlowLayout());
      JButton okButton = new JButton("Ok");
      okButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
Working with Images – Python .docx Module

03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add an image in a word document we use add_picture() method. This method is used to add an image in your Word document whenever called.
Syntax: doc.add_picture(image_path, width=None, height=None)
Parameters:
image_path: It is a string containing the path of the image to be added.
width: It sets the width of the image to be added in the document.
height: It sets the height of the image to be added in the document.
In the function given above, height and width are not specified then the image appears in its native size.
Pip command to install this module is:
pip install python-docx
Import module
Create docx object
Declare add_picture() method where ever image is required to be inserted, along with the path to that image and dimensions(optional).
Save document.
Example 1: Adding an image in native size in a word document.
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)  # Image in its native sizedoc.add_heading('Image in Native Size:', 3)doc.add_picture('logo.png')  # Now save the document to a locationdoc.save('gfg.docx')
Output:
gfg.docx
Example 2: Adding an image in a defined size in a word document.
Python3
# Import docx NOT python-docximport docxfrom docx.shared import Inches  # Create an instance of a word documentdoc = docx.Document()  # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0)    # Image with defined sizedoc.add_heading('Image with Defined Size:', 3)doc.add_picture('logo.png', width=Inches(2), height=Inches(2))  # Now save the document to a locationdoc.save('gfg.docx')
Output:
gfg.docx
Technical Scripter 2020
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 | Get unique values from a list
Python | datetime.timedelta() function
Python – Create window button in GTK+ 3

30 Jun, 2021
GTK+ 3 is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License. Along with Qt, it is one of the most popular toolkits for the Wayland and X11 windowing systems. Let’s see how to create a window and a button using GTK+ 3.Follow the below steps:  
import GTK+ 3 moduleCreate the main window.Create Button.
import GTK+ 3 module
Create the main window.
Create Button.
We have to import the Gtk module to be able to access GTK+’s classes and functions.Note: In IDEs like Pycharm we can install a package named PyGObject in order to use GTK+ 3.Code #1: Create an empty 200 x 200-pixel window.  
Python3
import gi # Since a system can have multiple versions# of GTK + installed, we want to make# sure that we are importing GTK + 3.gi.require_version("Gtk", "3.0") from gi.repository import Gtk # Creates an empty window.window = Gtk.Window() # Connecting to the window’s delete event# to ensure that the application is terminated# whenever we click close button window.connect("destroy", Gtk.main_quit)# Display the window.window.show_all() Gtk.main()
Output:  
Code #2: Create a button  
Python3
import gi gi.require_version("Gtk", "3.0")from gi.repository import Gtk # Define our own newWindow class.class newWindow(Gtk.Window):    def __init__(self):         # Call the constructor of the super class.        # Set the value of the property title to Geeks for Geeks.        Gtk.Window.__init__(self, title ="Geeks for Geeks")         # Create a button widget, connect to its clicked signal        # and add it as child to the top-level window.        self.button = Gtk.Button(label ="Click Here")        self.button.connect("clicked", self.on_button_clicked)        self.add(self.button)     # When we click on the button this method    # will be called    def on_button_clicked(self, widget):        print("Geeks for Geeks")  win = newWindow()win.connect("destroy", Gtk.main_quit)win.show_all()Gtk.main()
Output:  
 
amateurcoderrrrrrr
Python-GTK
Python-gui
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LocalDate getMonthValue() method in Java with Examples

29 Nov, 2018
The getMonthValue() method of LocalDate class in Java gets the month-of-year field from 1 to 12.
Syntax:
public int getMonthValue()

Parameter: This method does not accepts any parameter.
Return Value: The function returns the month of the year from 1-12 in numbers.
Below programs illustrate the getMonthValue() method of LocalDate in Java:Program 1:
// Program to illustrate the getMonthValue() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-11-27");          // Prints the day number        System.out.println(dt.getMonthValue());    }}
11

Program 2:
// Program to illustrate the getMonthValue() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-01-02");          // Prints the day number        System.out.println(dt.getMonthValue());    }}
1

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getMonthValue()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.