code-rag-bench/online-tutorials huggingface dataset:
numpy.load() in Python - GeeksforGeeks

29 Nov, 2018
numpy.load() function return the input array from a disk file with npy extension(.npy).
Syntax : numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding=’ASCII’)
Parameters:file : : file-like object, string, or pathlib.Path.The file to read. File-like objects must support the seek() and read() methods.mmap_mode : If not None, then memory-map the file, using the given mode (see numpy.memmap for a detaileddescription of the modes).allow_pickle : Allow loading pickled object arrays stored in npy files.fix_imports : Only useful when loading Python 2 generated pickled files on Python 3,which includes npy/npz files containing object arrays.encoding : Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays.
Returns : Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors.
Code #1 : Working
# Python program explaining # load() function   import numpy as geek  a = geek.array(([i + j for i in range(3)                        for j in range(3)]))# a is printed.print("a is:")print(a)  geek.save('geekfile', a)print("the array is saved in the file geekfile.npy")  # the array is saved in the file geekfile.npy b = geek.load('geekfile.npy')  # the array is loaded into bprint("b is:")print(b)  # b is printed from geekfile.npyprint("b is printed from geekfile.npy")
Output :
a is:
[0, 1, 2, 1, 2, 3, 2, 3, 4]
the array is saved in the file geekfile.npy
b is:
[0, 1, 2, 1, 2, 3, 2, 3, 4]
b is printed from geekfile.npy

 Code #2:
# Python program explaining # load() function   import numpy as geek  # a and b are numpy arrays.a = geek.array(([i + j for i in range(3)                        for j in range(3)]))b = geek.array([i + 1 for i in range(3)])  # a and b are printed.print("a is:")print(a)print("b is:")print(b)  # a and b are stored in geekfile.npzgeek.savez('geekfile.npz', a = a, b = b)  print("a and b are stored in geekfile.npz")  # compressed file is loadedc = geek.load('geekfile.npz')  print("after loading...")print("a is:", c['a'])print("b is:", c['b'])
Output :
a is:
[0 1 2 1 2 3 2 3 4]
b is:
[1 2 3]
a and b are stored in geekfile.npz
after loading...
a is: [0 1 2 1 2 3 2 3 4]
b is: [1 2 3]

Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
Python | sympy.Function() method - GeeksforGeeks

19 Jul, 2019
With the help of sympy.Function() method, we can find the various functions in the whole mathematical expression like f(x), sin(x), log(x), etc by using sympy.Function() method.
Syntax : sympy.Function()Return : Return the list of functions in mathematical operation.
Example #1 :In this example we can see that by using sympy.Function() method, we are able to find the function in the mathematical operation.
# import sympyfrom sympy import *   x, y = symbols('x y')f = Function('f')  # Use sympy.Function() methodgfg = (f(x) + 2 * tan(y + I * pi) + log(2 * x)).atoms(Function)    print(gfg)
Output :
{f(x), tan(y + I*pi), log(2*x)}
Example #2 :
# import sympyfrom sympy import *   x, y = symbols('x y')f = Function('f')  # Use sympy.Function() methodgfg = (2 + 3 * cos(y) + 5 * log(2 * x)).atoms(Function)    print(gfg)
Output :
{cos(y), log(2*x)}
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to Install MongoDB on AWS EC2 Instance? - GeeksforGeeks

02 Jan, 2022
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer
In this article, we will learn how to install MongoDB on AWS EC2.
AWS account.EC2 Instance.User with privileges to create Instance.
AWS account.
EC2 Instance.
User with privileges to create Instance.
Follow the steps below to install MongoDB on AWS EC2 :
Step 1: Create an AWS Elastic Cloud Compute Instance.
Step 2: Start the EC2 instance that you have created in Step 1.
Step 3: Connect to your EC2 Instance by clicking on Connect Button.
Step 4: A prompt will pop up after connecting.
Step 5: At first check, if MongoDB is already installed or not.
mongod --version
Step 6: If MongoDB is not installed on your virtual machine then at first Install the public key using the following command.
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
Step 7: Add sources.
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
Step 8: Reload the local package database using the following command.
sudo apt update
Step 9: Now install the MongoDB packages using the command.
sudo apt install -y mongodb-org
Step 10: Wait for the process to end.
Step 11: We have successfully installed MongoDB on our EC2  instance, to check if MongoDB is installed or not, verify using the following command.
mongod --version
To Start MongoDB:
 sudo systemctl start mongod
To Verify that MongoDB has started successfully:
sudo systemctl status mongod
To Stop MongoDB:
sudo systemctl stop mongod
To restart MongoDB:
sudo systemctl restart mongod
MongoDB Commands
In this way, we can install MongoDB on our EC2 instance using EC2 Instance Connect. And if you also use a free tier account, make sure you delete all the resources you have used before logging out. 
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 create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
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?
C# Program to Find Greatest Numbers in an Array using WHERE Clause LINQ - GeeksforGeeks

18 Oct, 2021
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to find the greatest numbers in an array using WHERE Clause LINQ. Here, we will get the numbers that are greater than a particular number in the given array.
Example:
Input: Array of Integers: 100,200,300,450,324,56,77,890
Value: 500
Output: Numbers greater than 500 are: 890
      
Input: Array of Integers: 34,56,78,100,200,300,450,324,56,77,890
Value: 100
Output: Numbers greater than 100 are: 200,300,450,324,890
Approach:
To display the greatest numbers in an array using WHERE Clause LINQ follow the following approach:
Store integer(input) in an array.The sum of the elements is calculated using the for loop.The numbers which are greater than particular value is checked using where function.By using the LINQ query we will store the numbers in an iterator.Now the iterator is iterated and the integers are printed.
Store integer(input) in an array.
The sum of the elements is calculated using the for loop.
The numbers which are greater than particular value is checked using where function.
By using the LINQ query we will store the numbers in an iterator.
Now the iterator is iterated and the integers are printed.
Example:
C#
// C# program to print the greatest numbers in an array// using WHERE Clause LINQusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;   class GFG{  static void Main(){          // Array of numbers    int[] array1 = { 34, 56, 78, 100, 200, 300,                     450, 324, 56, 77, 890 };          // Now get the numbers greater than 100 and     // store in big variable using where clause    var big = from value in array1 where value > 100 select value;    Console.WriteLine("Numbers that are greater than 100 are  :");          // Get the greater numbers    foreach (var s in big)    {        Console.Write(s.ToString() + " ");    }    Console.Read();}}
Output:
Numbers that are greater than 100 are  :
200 300 450 324 890 
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C#
Implementing K-Nearest Neighbors in scikit-learn | by Chaim Gluck | Towards Data Science

We’ll be using the iris data set, available here from the UCI Machine Learning. It’s a small data set with easily distinguishable clusters that’s very useful for demonstrations like this one. It contains 150 observations of iris plants of three species: setosa, versicolor, and virginica. The task is to identify the species of each plant based on their nearest neighbors.
K-Nearest Neighbors is a method that simply looks at the observation that are nearest to the one it’s trying to predict, and classifies the point of interest based on the majority of those around it.
I used the following code to load the data into a pandas DataFrame:
## load the iris data into a DataFrameimport pandas as pdurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' ## Specifying column names.col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']iris = pd.read_csv(url, header=None, names=col_names)
Here’s a look at the data:
Below, I’ve plotted the petal length and width divided by class so you can see how separable the classes are.
Now, in order to model the data I ran through a couple of preprocessing steps. First, I mapped the species names to a number, so I can run my Classifier against it. The code for that is as follows:
## map each iris species to a number with a dictionary and list comprehension.iris_class = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}iris['species_num'] = [iris_class[i] for i in iris.species]
Split the data into our modeling and target variables, our X and y:
## Create an 'X' matrix by dropping the irrelevant columns.X = iris.drop(['species', 'species_num'], axis=1)y = iris.species_num
Train-test split:
from sklearn.model_selection import train_test_split## Split data into training and testing sets.X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
And we’re ready for the model. In the code below, we’ll import the Classifier, instantiate the model, fit it on the training data, and score it on the test data. Note that you can change the number of nearest neighbors it uses to classify each point.
## Import the Classifier.from sklearn.neighbors import KNeighborsClassifier## Instantiate the model with 5 neighbors. knn = KNeighborsClassifier(n_neighbors=5)## Fit the model on the training data.knn.fit(X_train, y_train)## See how the model performs on the test data.knn.score(X_test, y_test)
The model actually has a 100% accuracy score, since this is a very simplistic data set with distinctly separable classes. But there you have it. That’s how to implement K-Nearest Neighbors with scikit-learn. Load your favorite data set and give it a try!
Checking for permutation of a palindrome in JavaScript

We are required to write a JavaScript function that takes in a string as the first and the only argument.
The task of our function is to check whether any rearrangement in the characters of the string results into a palindrome string or not. If yes, then our function should return true, false otherwise.
For example −
If the input string is −
const str = 'amadm';
Then the output should be −
const output = true;
because the string can be rearranged to form 'madam' which is a palindrome string.
The code for this will be −
 Live Demo
const str = 'amadm';
const canFormPalindrome = (str = '') => {
   const hash = {};
   let count = 0;
   for (let i = 0; i < str.length; i++) {
      let c = str[i];
      if(c === ' '){
         continue;
      };
      if(hash[c]){
         delete hash[c];
      }else{
         hash[c] = true;
      };
      count++;
   };
   if(count % 2 === 0){
      return Object.keys(hash).length === 0;
   }else{
      return Object.keys(hash).length === 1;
   };
};
console.log(canFormPalindrome(str));
And the output in the console will be −
true
How to Read a File Line by Line to String in Golang? - GeeksforGeeks

22 Jun, 2020
To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows:
GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. Go language is a general-purpose programming language mainly meant for building large scale complex software.
package main  import (    "bufio"    "fmt"    "log"    "os")  func main() {      // os.Open() opens specific file in     // read-only mode and this return     // a pointer of type os.    file, err := os.Open("sample.txt")      if err != nil {        log.Fatalf("failed to open")      }      // The bufio.NewScanner() function is called in which the    // object os.File passed as its parameter and this returns a    // object bufio.Scanner which is further used on the    // bufio.Scanner.Split() method.    scanner := bufio.NewScanner(file)      // The bufio.ScanLines is used as an     // input to the method bufio.Scanner.Split()    // and then the scanning forwards to each    // new line using the bufio.Scanner.Scan()    // method.    scanner.Split(bufio.ScanLines)    var text []string      for scanner.Scan() {        text = append(text, scanner.Text())    }      // The method os.File.Close() is called    // on the os.File object to close the file    file.Close()      // and then a loop iterates through     // and prints each of the slice values.    for _, each_ln := range text {        fmt.Println(each_ln)    }}
Output:
Golang-File-Handling
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to compare times in Golang?
Golang Maps
How to Trim a String in Golang?
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to convert a string in lower case in Golang?
C# | Check if an array object is equal to another array object - GeeksforGeeks

06 Jan, 2022
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Equals(Object) method which is inherited by Array class from object class is used to check whether an array is equal to another array or not.
Syntax: 
public virtual bool Equals (object obj);
Here, obj is the object which is to be compared with the current object.Return Value: This method return true if the specified object is equal to the current object otherwise it returns false.
Below programs illustrate the use of above-discussed method:
Example 1: 
C#
// C# code to check if a Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG {     // Main Method    public static void Main()    {         // Two-dimensional array        int[, ] intarray = new int[, ] { { 1, 2 },                                         { 3, 4 },                                         { 5, 6 },                                         { 7, 8 } };         // check if intarray is        // equal to itself or not        Console.WriteLine(intarray.Equals(intarray));    }}}
True
 
Example 2:
C#
// C# code to check if an Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG {     // Main Method    public static void Main()    {              // Creating and initializing new the String        String[] arr1 = new String[4] { "Sun", "Mon", "Tue", "Thu" };                          // taking anotther array        String[] arr2 = new String[4] { "Sun", "Mon", "Tue", "Thu" };                  // check if arr1 is        // equal to arr2 or not        Console.WriteLine(arr1.Equals(arr2));                 // assigning arr1 reference to arr3        String[] arr3 = new String[4];        arr3 = arr1;                 // check if arr2 is        // equal to arr3 or not        Console.WriteLine(arr2.Equals(arr3));                 // check if arr1 is        // equal to arr3 or not        // it will return true as both        // array object refer to same        Console.WriteLine(arr1.Equals(arr3));             }}}
False
False
True
 
Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality. 
sweetyty
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Common Language Runtime (CLR) in C#
C# | Encapsulation
How to get the Width and Height of the screen in JavaScript?

Javascript has provided window.screen object that contains information regarding the user's screen. The information includes height and width, and also many other features. To find the height and width of the screen the methods provided by javascript are screen.height and screen.width respectively.
scree.height;
scree.width;
In the following example, the width of the screen is displayed using the screen.width method.
Live Demo
<html>
<body>
<p id="width"> </p>
   <script>
      document.getElementById("width").innerHTML =
      "Screen width is " + screen.width;
   </script>
</body>
</html>
1366
In the following example, the height of the screen is displayed using the screen.height method.
Live Demo
<html>
<body>
   <p id="height"> </p>
   <script>
      document.getElementById("height").innerHTML =
      "Screen heigth is " + screen.height;
   </script>
</body>
</html>
768
DoubleStream sorted() in Java - GeeksforGeeks

06 Dec, 2018
DoubleStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
Syntax :
DoubleStream sorted()

Where, DoubleStream is a sequence of primitive double-valued 
elements. This is the double primitive specialization of Stream.

Return Value : DoubleStream sorted() method returns the new stream having the elements in sorted order.
Example 1 : Using DoubleStream sorted() to sort the numbers in given DoubleStream.
// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream        DoubleStream stream = DoubleStream.of(10.2, 9.3, 8.4,                                              7.5, 6.6);          // displaying the stream with sorted elements        // using DoubleStream.sorted() function        stream.sorted().forEach(System.out::println);    }}
6.6
7.5
8.4
9.3
10.2

Example 2 : Using DoubleStream sorted() to sort the random numbers generated by DoubleStream generator().
// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream by generating        // random elements using DoubleStream.generate()        DoubleStream stream = DoubleStream.generate(()          -> (double)(Math.random() * 10000)).limit(5);          // displaying the stream with sorted elements        // using DoubleStream.sorted() function        stream.sorted().forEach(System.out::println);    }}
1279.6146863795122
6927.016817313592
7037.390703089559
8374.314582282514
9112.609381925824

Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
file parameter of Python’s print() Function

23 Oct, 2020
print() function in Python3 supports a ‘file‘ argument, which specifies where the function should write a given object(s) to. If not specified explicitly, it is sys.stdout by default.
It serves two essential purposes:
Print to STDERR
Print to external file
Note : The ‘file’ parameter is found only in Python 3.x or later. Printing to STDERR :
Specify the file parameter as sys.stderr instead of the default value. This is very useful when debugging a small program (It would be better to use a debugger in other cases).
# Code for printing to STDERRimport sys  print('GeeksForGeeks', file = sys.stderr)
Output :
GeeksForGeeks

 Printing to a specific file :
Instead of the default value, specify the file parameter with the name of the required file. If the file does not exist, a new file by that name is created and written to.
# Code for printing to a filesample = open('samplefile.txt', 'w')  print('GeeksForGeeks', file = sample)sample.close()
Output (in “samplefile.txt”) :
GeeksForGeeks

Note : Try this in interpreter on your system, since such file can’t be accessed on Online IDE.
python-io
Python
Technical Scripter
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queries to print all divisors of number

23 Dec, 2017
Given a positive integer ‘n’ and query ‘q’. Print all the divisors of number ‘n’.
Input: 6
Output: 1 2 3 6
Explanation
Divisors of 6 are: 1, 2, 3, 6

Input: 10
Output: 1 2 5 10

Naive approach is to iterate through 1 to sqrt(n) for every query ‘q’ and print the divisors accordingly. See this to understand more. Time complexity of this approach is q*sqrt(n) which is not sufficient for large number of queries.
Efficient approach is to use factorization by using sieve base approach.
Create a list of consecutive integers from 1 to ‘n’.
For any number ‘d’, iterate through all the multiples of ‘d’ i.e., d, 2d, 3d, ... etc. Meanwhile push the divisor ‘d’ for every multiples.
// C++ program to print divisors of// number for multiple query#include <iostream>#include <vector>using namespace std;  const int MAX = 1e5;  // Initialize global divisor vector// array of sequence containervector<int> divisor[MAX + 1];  // Sieve based approach to pre-// calculate all divisors of numbervoid sieve(){    for (int i = 1; i <= MAX; ++i) {        for (int j = i; j <= MAX; j += i)            divisor[j].push_back(i);    }}  // Utility function to print divisors// of given numberinline void printDivisor(int& n){    for (auto& div : divisor[n])        cout << div << " ";}  // Driver codeint main(){    sieve();      int n = 10;    cout << "Divisors of " << n << " = ";    printDivisor(n);      n = 30;    cout << "\nDivisors of " << n << " = ";    printDivisor(n);    return 0;}
Output 
Divisors of 10 = 1 2 5 10 
Divisors of 30 = 1 2 3 5 6 10 15 303

Time complexity: O(len) for each query, where len is equal to total divisors of number ‘n’.Auxiliary space: O(MAX)
divisors
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extracting each word from a String using Regex in Java

11 Dec, 2018
Given a string, extract words from it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z.
Examples:
Input : Funny?? are not you?
Output : Funny
         are
         not
         you

Input : Geeks for geeks?? 
Output : Geeks
         for
         geeks

We have discussed a solution for C++ in this post : Program to extract words from a given String
We have also discussed basic approach for java in these posts : Counting number of lines, words, characters and paragraphs in a text file using Java and Print first letter in word using Regex.
In this post, we will discuss Regular Expression approach for doing the same. This approach is best in terms of Time Complexity and is also used for large input files. Below is the regular expression for any word.
[a-zA-Z]+

// Java program to demonstrate extracting words// from string using Regex  import java.util.regex.Matcher;import java.util.regex.Pattern;  public class Test {    public static void main(String[] args)     {        String s1 = "Geeks for Geeks";        String s2 = "A Computer Science Portal for Geeks";                  Pattern p = Pattern.compile("[a-zA-Z]+");                  Matcher m1 = p.matcher(s1);        Matcher m2 = p.matcher(s2);                  System.out.println("Words from string \"" + s1 + "\" : ");        while (m1.find()) {            System.out.println(m1.group());        }                  System.out.println("Words from string \"" + s2 + "\" : ");        while (m2.find()) {            System.out.println(m2.group());        }              }}
Output:
Words from string "Geeks for Geeks" : 
Geeks
for
Geeks
Words from string "A Computer Science Portal for Geeks" : 
A
Computer
Science
Portal
for
Geeks

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-regular-expression
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js split() function

14 Oct, 2021
The split() function is a string function of Node.js which is used to split string into sub-strings. This function returns the output in array form.Syntax:  
string.split( separator )
Parameters: This function accepts single parameter separator which holds the character to split the string.Return Value: The function returns the splitted string and generates array as result.Below programs demonstrate the working of split() function:Program 1:  
javascript
function splitStr(str) {          // Function to split string    var string = str.split("*");          console.log(string);}  // Initialize stringvar str = "Welcome*to*GeeksforGeeks";  // Function callsplitStr(str);    
Output:  
[ 'Welcome', 'to', 'GeeksforGeeks' ]
Program 2:  
javascript
function splitStr(str, separator) {          // Function to split string    var string = str.split(separator);          console.log(string);}  // Initialize stringvar str = "GeeksforGeeks/A/computer/science/portal";  var separator = "/";  // Function callsplitStr(str, separator);
Output:  
[ 'GeeksforGeeks', 'A', 'computer', 'science', 'portal' ]
 
anikakapoor
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Releasing GIL and mixing threads from C and Python - GeeksforGeeks

29 Mar, 2019
Releasing GIL in C extension:Give a C extension code and one needs to concurrently execute it with other threads in the Python interpreter. For this Global Interpreter Lock (GIL) has to be released and reacquired.
Code #1 : Releasing and Reacquiring GIL by inserting following macros
#include "Python.h"...PyObject *pyfunc(PyObject *self, PyObject *args){    ...    Py_BEGIN_ALLOW_THREADS          // Threaded C code.     // Must not use Python API functions    ...    Py_END_ALLOW_THREADS    ...    return result;}
Mixing Threads from C and Python:Considering a situation, that a given program involves a mix of C, Python and threads. But some of the given threads are created from C outside the control of the Python interpreter and also certain threads utilize functions in the Python C API.
What’s solution then?If there is a mix of Python, C and threads, proper initialization and management of Python’s Global Interpreter Lock (GIL) is important. Given code below explains the situation, their code can be used anywhere (prior to the creation of threads) in the C program.
Code #2 :
#include <Python.h>...if (!PyEval_ThreadsInitialized()){    PyEval_InitThreads();}...
For any C involving Python objects or the Python C API, GIL needs to be acquired and released first. This can be performed using PyGILState_Ensure() and PyGILState_Release() as in the code given below. Every call to PyGILState_Ensure() must have a matching call to PyGILState_Release().
Code #3 :
...// Make sure we own the GIL// Use functions in the interpreterPyGILState_STATE state = PyGILState_Ensure();  ...// Restore previous GIL state and return PyGILState_Release(state);...
Note :It is not so easy to have so much things going at once, involving a mix of a Python code, C code and their threads. To perform so, it is to be taken care that the interpreter is properly initialized and that C code involving the interpreter has the proper GIL management calls, it all should work.Also, the PyGILState_Ensure() call does not immediately preempt or interrupt the interpreter. If other code is currently executing, this function will block until that code decides to release the Global Interpreter Lock (GIL).
Python-ctype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How to iterate through Excel rows in Python? - GeeksforGeeks

25 Feb, 2021
In this article, we are going to discuss how to iterate through Excel Rows in Python. In order to perform this task, we will be using the Openpyxl module in python. Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows a Python program to read and modify Excel files.
We will be using this excel worksheet in the below examples:
Approach #1:
We will create an object of openpyxl, and then we’ll iterate through all rows from top to bottom.
Python3
# import moduleimport openpyxl  # load excel with its pathwrkbk = openpyxl.load_workbook("Book1.xlsx")  sh = wrkbk.active  # iterate through excel and display datafor i in range(1, sh.max_row+1):    print("\n")    print("Row ", i, " data :")          for j in range(1, sh.max_column+1):        cell_obj = sh.cell(row=i, column=j)        print(cell_obj.value, end=" ")
Output:
Approach #2
We will create an object of openpyxl, and then we’ll iterate through all rows using iter_rows() method.
Python3
# import moduleimport openpyxl  # load excel with its pathwrkbk = openpyxl.load_workbook("Book1.xlsx")  sh = wrkbk.active  # iterate through excel and display datafor row in sh.iter_rows(min_row=1, min_col=1, max_row=12, max_col=3):    for cell in row:        print(cell.value, end=" ")    print()
Output:
Picked
Python-excel
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | NLTK nltk.tokenize.ConditionalFreqDist() - GeeksforGeeks

22 Nov, 2019
With the help of nltk.tokenize.ConditionalFreqDist() method, we are able to count the frequency of words in a sentence by using tokenize.ConditionalFreqDist() method.
Syntax : tokenize.ConditionalFreqDist()Return : Return the frequency distribution of words in a dictionary.
Example #1 :In this example we can see that by using tokenize.ConditionalFreqDist() method, we are able to count the occurrence of words in a sentence.
# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize     # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist()     # Create a string inputgfg = "Geeks for Geeks"     for word in word_tokenize(gfg):   condition = len(word)   tk[condition][word] += 1     print(tk)
Output :
FreqDist({‘Geeks’: 2, ‘for’: 1})
Example #2 :
# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize     # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist()     # Create a string inputgfg = "G F G"     for word in word_tokenize(gfg):   condition = len(word)   tk[condition][word] += 1     print(tk)
Output :
FreqDist({‘G’: 2, ‘F’: 1})
ManasChhabra2
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Numbers in Java (With 0 Prefix and with Strings) - GeeksforGeeks

30 May, 2018
Consider the following Java program.
import java.io.*;class GFG{    public static void main (String[] args)    {        int x = 012;        System.out.print(x);    }}
Output:
10
The reason for above output is, when a 0 is prefixed the value is considered octal, since 12 in octal is 10 in decimal, the result is 10. Similarly, if i = 0112, result will be 74 (in decimal). This behavior is same as C/C++ (see this).
Also,
import java.io.*;class GFG{    public static void main (String[] args)    {        String s = 3 + 2 + "hello" + 6 + 4;        System.out.print(s);    }}
Output :
5hello64
Java takes the numbers before the strings are introduced as int and once the string literals are introduced, all the following numbers are considered as strings.
This article is contributed by Hiresh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Constructors in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
How to show an Axes Subplot in Python?

To show an axes subplot in Python, we can use show() method. When multiple figures are created,
then those images are displayed using show() method.
Create x and y data points using numpy.
Plot x and y using plot() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(10)
y = np.exp(x)
plt.plot(x, y)
plt.show()
Docker - Logging

Docker has logging mechanisms in place which can be used to debug issues as and when they occur. There is logging at the daemon level and at the container level. Let’s look at the different levels of logging.
At the daemon logging level, there are four levels of logging available −
Debug − It details all the possible information handled by the daemon process.
Debug − It details all the possible information handled by the daemon process.
Info − It details all the errors + Information handled by the daemon process.
Info − It details all the errors + Information handled by the daemon process.
Errors − It details all the errors handled by the daemon process.
Errors − It details all the errors handled by the daemon process.
Fatal − It only details all the fatal errors handled by the daemon process.
Fatal − It only details all the fatal errors handled by the daemon process.
Go through the following steps to learn how to enable logging.
Step 1 − First, we need to stop the docker daemon process, if it is already running. It can be done using the following command −
sudo service docker stop 

Step 2 − Now we need to start the docker daemon process. But this time, we need to append the –l parameter to specify the logging option. So let’s issue the following command when starting the docker daemon process.
sudo dockerd –l debug &

The following points need to be noted about the above command −
dockerd is the executable for the docker daemon process.
dockerd is the executable for the docker daemon process.
The –l option is used to specify the logging level. In our case, we are putting this as debug
The –l option is used to specify the logging level. In our case, we are putting this as debug
& is used to come back to the command prompt after the logging has been enabled.
& is used to come back to the command prompt after the logging has been enabled.
Once you start the Docker process with logging, you will also now see the Debug Logs being sent to the console.
Now, if you execute any Docker command such as docker images, the Debug information will also be sent to the console.
Logging is also available at the container level. So in our example, let’s spin up an Ubuntu container first. We can do it by using the following command.
sudo docker run –it ubuntu /bin/bash 

Now, we can use the docker log command to see the logs of the container.
Docker logs containerID 

containerID − This is the ID of the container for which you need to see the logs.
containerID − This is the ID of the container for which you need to see the logs.
On our Docker Host, let’s issue the following command. Before that, you can issue some commands whilst in the container.
sudo docker logs 6bfb1271fcdd 

From the output, you can see that the commands executed in the container are shown in the logs.

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page
How to use Boto3 to start the scheduler of a crawler in AWS Glue Data Catalog

In this article, we will see how a user can start the scheduler of a crawler in AWS Glue Data Catalog.
Start the scheduler of a crawler available in AWS Glue Data Catalog.
 Problem Statement: Use boto3 library in Python to start the scheduler of a crawler.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2:
crawler_name is the required parameter in this function.
Step 2:
crawler_name is the required parameter in this function.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for glue.
Step 4: Create an AWS client for glue.
Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName.
Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName.
Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException.
Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException.
Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler.
Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler.
The following code starts the scheduler of a crawler −
import boto3
from botocore.exceptions import ClientError

def start_scheduler_of_a_crawler(crawler_name)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.start_crawler_schedule(CrawlerName=crawler_name)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in start_scheduler_of_a_crawler: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in start_scheduler_of_a_crawler: " + e.__str__())
print(start_scheduler_of_a_crawler("Data Dimension"))
{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}
Python os.renames() Method

Python method renames() is recursive directory or file renaming function. It does the same functioning as  os.rename(), but it also moves a file to a directory, or a whole tree of directories, that do not exist.
Following is the syntax for renames() method −
os.renames(old, new)

old − This is the actual name of the file or directory to be renamed.
old − This is the actual name of the file or directory to be renamed.
new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist.
new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist.
This method does not return any value.
The following example shows the usage of renames() method.
# !/usr/bin/python

import os, sys
print "Current directory is: %s" %os.getcwd()

# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())

# renaming file "aa1.txt"
os.renames("aa1.txt","newdir/aanew.txt")

print "Successfully renamed."

# listing directories after renaming and moving "aa1.txt"
print "The dir is: %s" %os.listdir(os.getcwd())
When we run above program, it produces following result −
Current directory is: /tmp
The dir is:
 [  'a1.txt','resume.doc','a3.py','aa1.txt','Administrator','amrood.admin' ]
Successfully renamed.
The dir is:
 [  'a1.txt','resume.doc','a3.py','Administrator','amrood.admin' ]

The file aa1.txt is not visible here, as it is been moved to newdir and renamed as aanew.txt. The directory newdir and its contents are shown below −
[ 'aanew.txt' ]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Display the Pandas DataFrame in table style and border around the table and not around the rows - GeeksforGeeks

21 Aug, 2020
Let us see how to style a Pandas DataFrame such that it has a border around the table. We will be using the set_table_styles() method of the Styler class in the Pandas module.
Syntax : set_table_styles(self, table_styles)
Parameters :table_styles : List, each individual table_style should be a dictionary with selector and props keys.
Returns : Styler
Example 1 :
# import the moduleimport pandas as pd   # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting',                       'Jayasurya', 'Jayawardene', 'Kohli',                       'Haq', 'Kallis', 'Ganguly', 'Dravid'],             'runs': [18426, 14234, 13704, 13430, 12650,                      11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs)    # making a yellow borderdf.style.set_table_styles([{'selector' : '',                            'props' : [('border',                                        '10px solid yellow')]}])
Output :
Example 2 :
# import the moduleimport pandas as pd   # create a DataFrame df = pd.DataFrame({"A":[14, 4, 5, 4, 1],                     "B":[5, 2, 54, 3, 2],                      "C":[20, 20, 7, 3, 8],                     "D":[14, 3, 6, 2, 6]})  # making a green borderdf.style.set_table_styles([{'selector' : '',                            'props' : [('border',                                        '2px solid green')]}])
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe