code-rag-bench/online-tutorials huggingface dataset:
MongoEngine - MongoDB

NoSQL databases have seen rise in popularity in the last decade. In today’s world of real time web applications, huge amount of data is being generated with mobile and embedded devices. Traditional relational databases (like Oracle, MySQL, etc.) are not suitable for strings. The processing of such data is also difficult as they have fixed and predefined schema, and are not scalable. NOSQL databases have flexible schema and are stored in distributed manner on a large number of community servers.
NOSQL databases are classified on the basis of organization of data. MongoDB is a popular Document Store NOSQL database. Fundamental constituent of a MongoDB database is called a document. A document is a collection of key-value pairs stored in JSON format. More than one documents are stored in a collection. A collection can be considered as analogous to a table in any relational database, and a Document as row in a table. However, it should be noted that since MongoDB is schema less, number of key-value pairs in each document of a Collection need not be the same.
MongoDB is developed by MongoDB Inc. It is a general-purpose, distributed document based database. It is available in enterprise as well as community edition. Latest version of Community version for Windows operating system can be downloaded from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.6-signed.msi.
Install MongoDB in a folder of your choice and start the server with the following command−
D:\mongodb\bin>mongod

Server is now ready for incoming connection requests at port 27017. MongoDB databases are stored in bin/data directory. This location can be changed by –dbpath option in above command.
In another command terminal, start MongoDB console with the following command −
D:\mongodb\bin>mongo

MongoDB prompt is similar to what we normally see in MySQL or SQLite terminal. All database operations such as creating database, inserting a document, updating and deleting as well as retrieval of documents can be done from within the console.
E:\mongodb\bin>mongo
MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("0d848b11-acf7-4d30-83df-242d1d7fa693") }
MongoDB server version: 4.0.6
---
>
Default database in use is test.
> db
Test

With 'use' command any other database is set as current. If the named database does not exist, new one is created.
> use mydb
switched to db mydb

Please refer to our detailed tutorial on MongoDB at https://www.tutorialspoint.com/mongodb/index.htm.
 Print
 Add Notes
 Bookmark this page
PHP Tutorial

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
With our online "PHP Tryit" editor, you can edit the PHP code, and click 
on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Insert the missing part of the code below to output "Hello World".
 "Hello World";

Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All PHP Examples
Learn by taking a quiz! This quiz will give you a signal of how much you know, or do not know, about PHP.
Start PHP Quiz!
W3Schools' PHP reference contains different categories of all PHP functions, keywords and constants, along with examples.
Get certified by completing the PHP course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
ggplot2 - Time Series

A time series is a graphical plot which represents the series of data points in a specific time order. A time series is a sequence taken with a sequence at a successive equal spaced points of time. Time series can be considered as discrete-time data. The dataset which we will use in this chapter is “economics” dataset which includes all the details of US economic time series.
The dataframe includes following attributes which is mentioned below −
Load the required packages and set the default theme to create a time series.
> library(ggplot2)
> theme_set(theme_minimal())
> # Demo dataset
> head(economics)
# A tibble: 6 x 6
date           pce            pop          psavert       uempmed       unemploy
<date>         <dbl>         <dbl>         <dbl>         <dbl>         <dbl>
1 1967-07-01    507.          198712        12.6          4.5           2944
2 1967-08-01    510.          198911        12.6          4.7           2945
3 1967-09-01    516.          199113        11.9          4.6           2958
4 1967-10-01    512.          199311        12.9          4.9           3143
5 1967-11-01    517.          199498        12.8          4.7           3066
6 1967-12-01    525.          199657        11.8          4.8           3018

Create a basic line plots which creates a time series structure.
> # Basic line plot
> ggplot(data = economics, aes(x = date, y = pop))+
+ geom_line(color = "#00AFBB", size = 2)

We can plot the subset of data using following command −
> # Plot a subset of the data
> ss <- subset(economics, date > as.Date("2006-1-1"))
> ggplot(data = ss, aes(x = date, y = pop)) +
+ geom_line(color = "#FC4E07", size = 2)

Here we will plot the variables psavert and uempmed by dates. Here we must reshape the data using the tidyr package. This can be achieved by collapsing psavert and uempmed values in the same column (new column). R function: gather()[tidyr]. The next step involves creating a grouping variable that with levels = psavert and uempmed.
> library(tidyr)
> library(dplyr)
Attaching package: ‘dplyr’
The following object is masked from ‘package:ggplot2’: vars
The following objects are masked from ‘package:stats’: filter, lag
The following objects are masked from ‘package:base’: intersect, setdiff, setequal, union
> df <- economics %>%
+    select(date, psavert, uempmed) %>%
+    gather(key = "variable", value = "value", -date)
> head(df, 3)
# A tibble: 3 x 3
date          variable     value
<date> <chr>   <dbl>
1 1967-07-01   psavert       12.6
2 1967-08-01   psavert       12.6
3 1967-09-01   psavert       11.9

Create a multiple line plots using following command to have a look on the relationship between “psavert” and “unempmed” −
> ggplot(df, aes(x = date, y = value)) +
+    geom_line(aes(color = variable), size = 1) +
+    scale_color_manual(values = c("#00AFBB", "#E7B800")) +
+    theme_minimal()

 Print
 Add Notes
 Bookmark this page
Jackson Annotations - @JsonAnyGetter

@JsonAnyGetter allows a getter method to return Map which is then used to serialize the additional properties of JSON in the similar fashion as other properties.
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonTester { 
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper(); 
      try{
         Student student = new Student(); 
         student.add("Name", "Mark"); 
         student.add("RollNo", "1"); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      } 
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   private Map<String, String> properties; 
   public Student(){ 
      properties = new HashMap<>(); 
   } 
   public Map<String, String> getProperties(){ 
      return properties; 
   } 
   public void add(String property, String value){ 
      properties.put(property, value); 
   } 
}
{
   "properties" : {
      "RollNo" : "1",
      "Name" : "Mark"
   } 
}

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.annotation.JsonAnyGetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonTester {
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try{
         Student student = new Student(); 
         student.add("Name", "Mark"); 
         student.add("RollNo", "1"); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) {
         e.printStackTrace();
      } 
   }
}
class Student {
   private Map<String, String> properties;
   public Student(){
      properties = new HashMap<>();
   }
   @JsonAnyGetter
   public Map<String, String> getProperties(){
      return properties;
   }
   public void add(String property, String value){
      properties.put(property, value);
   }
}
{
   "RollNo" : "1",
   "Name" : "Mark"
}

 Print
 Add Notes
 Bookmark this page
Python – Weibull Maximum Distribution in Statistics

10 Jan, 2020
scipy.stats.weibull_max() is a Weibull maximum continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : Weibull maximum continuous random variable
Code #1 : Creating Weibull maximum continuous random variable
# importing library  from scipy.stats import weibull_max     numargs = weibull_max .numargs a, b = 0.2, 0.8rv = weibull_max (a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9DA07FDC8

Code #2 : Weibull maximum continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = weibull_max .rvs(a, b, size = 10) print ("Random Variates : \n", R)   # PDF x = np.linspace(weibull_max.ppf(0.01, a, b),                weibull_max.ppf(0.99, a, b), 10)R = weibull_max.pdf(x, 1, 3)print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 [ 7.99998841e-01  7.96362853e-01 -1.36808367e+00 -5.04876338e-01
 -8.07612996e+03  2.47694796e-01  7.80624490e-01  7.99996977e-01
  7.95962734e-01  6.94775447e-01]

Probability Distribution : 
 [0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000
 0.00000000e+000 0.00000000e+000 1.59673931e-301 1.41364401e-201
 1.25154393e-101 1.10803158e-001]

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print("Distribution : \n", distribution) 
Output :
Distribution : 
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0.]
  
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np   x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = weibull_max.pdf(x, a, b) y2 = weibull_max.pdf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
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 program to split a string by the given list of strings

01 Oct, 2020
Given a list of strings. The task is to split the string by the given list of strings. 
Input : test_str = ‘geekforgeeksbestforgeeks’, sub_list = [“best”] Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’] Explanation : “best” is extracted as different list element.
Input : test_str = ‘geekforgeeksbestforgeeksCS’, sub_list = [“best”, “CS”] Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’, “CS”] Explanation : “best” and “CS” are extracted as different list element.  
Method : Using re.split() + | operator
In this, we perform the task of split using regex split() with | operator to check for all the words that need to be put separately.
Python3
# Python3 code to demonstrate working of # Separate specific Strings# Using re.split() + | operatorimport re  # initializing stringtest_str = 'geekforgeeksisbestforgeeks'  # printing original Stringprint("The original string is : " + str(test_str))  # initializing list words sub_list = ["best"]  # regex to for splits()# | operator to include all strings temp = re.split(rf"({'|'.join(sub_list)})", test_str)res = [ele for ele in temp if ele]   # printing result print("The segmented String : " + str(res)) 
The original string is : geekforgeeksisbestforgeeks
The segmented String : ['geekforgeeksis', 'best', 'forgeeks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python – seaborn.residplot() method

17 Aug, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.
This method is used to plot the residuals of linear regression. This method will regress y on x and then draw a scatter plot of the residuals. You can optionally fit a lowess smoother to the residual plot, which can help in determining if there is a structure to the residuals.
Syntax: seaborn.residplot(x, y, data=None, lowess=False, x_partial=None, y_partial=None, order=1,   robust=False, dropna=True, label=None, color=None, scatter_kws=None, line_kws=None, ax=None)
Parameters: The description of some main parameters are given below:
x: Data or column name in ‘data’ for the predictor variable.
y: Data or column name in ‘data’ for the response variable.
data: (optional) DataFrame having `x` and `y` are column names.
lowess: (optional) Fit a lowess smoother to the residual scatterplot.
dropna: (optional) This parameter takes boolean value. If True, ignore observations with missing data when fitting and plotting.
Return: Axes with the regression plot.
Below is the implementation of above method:
Example 1:
Python3
# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("tips")  # draw residplotsns.residplot(x = "total_bill",              y = "tip",              data = data)  # show the plotplt.show()  # This code is contributed# by Deepanshu Rustagi.
Output:
Example 2:
Python3
# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt  # loading datasetdata = sns.load_dataset("iris")  # draw residplot# with lowess = Truesns.residplot(x = "petal_length",              y = "petal_width",              data = data,              lowess = True)  # show the plotplt.show()  # This code is contributed# by Deepanshu Rustagi.
Output:
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find frequency of each word in a string in C#

To find the frequency of each word in a string, you can try to run the following code −
 Live Demo
using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {
      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }

   public static void Main() {
      String s = "Football!";
      int []cal = new int[maxCHARS];
      calculate(s, cal);
      for (int i = 0; i < maxCHARS; i++)
      if(cal[i] > 1) {
         Console.WriteLine("Character "+(char)i);
         Console.WriteLine("Occurrence = " + cal[i] + " times");
      }
   }
}
Character l
Occurrence = 2 times
Character o
Occurrence = 2 times
Above, we have set a string and an integer array. This helps us in getting the repeated values. The method calculates −
static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}
The value are then printed that shows the duplicate elements as well −
for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
   Console.WriteLine("Character "+(char)i);
   Console.WriteLine("Occurrence = " + cal[i] + " times");
}
F# - Basic Syntax

You have seen the basic structure of an F# program, so it will be easy to understand other basic building blocks of the F# programming language.
An F# program consists of various tokens. A token could be a keyword, an identifier, a constant, a string literal, or a symbol. We can categorize F# tokens into two types −
Keywords
Symbol and Operators
The following table shows the keywords and brief descriptions of the keywords. We will discuss the use of these keywords in subsequent chapters.
In type definitions and type extensions, indicates the end of a section of member definitions.
In verbose syntax, used to specify the end of a code block that starts with the begin keyword.
Used to declare, define, or invoke a constructor that creates or that can create an object.
Also used in generic parameter constraints to indicate that a type must have a certain constructor.
Indicates the absence of an object.
Also used in generic parameter constraints.
Used with Boolean conditions as a Boolean or operator. Equivalent to ||.
Also used in member constraints.
Used to declare a structure type.
Also used in generic parameter constraints.
Used for OCaml compatibility in module definitions.
Used in conditional expressions.
Also used to perform side effects after object construction.
Some reserved keywords came from the OCaml language −
Some other reserved keywords are kept for future expansion of F#.
F# provides two types of comments −
One line comment starts with // symbol.
Multi line comment starts with (* and ends with *).
Generally, you don’t have any explicit entry point for F# programs. When you compile an F# application, the last file provided to the compiler becomes the entry point and all top level statements in that file are executed from top to bottom.
A well-written program should have a single top-level statement that would call the main loop of the program.
A very minimalistic F# program that would display ‘Hello World’ on the screen −
(* This is a comment *)
(* Sample Hello World program using F# *)
printfn "Hello World!"
When you compile and execute the program, it yields the following output −
Hello World!

 Print
 Add Notes
 Bookmark this page
How to extract certain substring from a string using Java?

You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.
Live Demo
public class Substring {
   public static void main(String args[]) {

      String str = "Welcome to Tutorialspoint";
      String sub = str.substring(10, 25);
      System.out.println(sub);
   }
}
Tutorialspoint
Matplotlib.axes.Axes.redraw_in_frame() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.redraw_in_frame() function in axes module of matplotlib library is used to efficiently update Axes data.
Syntax: Axes.redraw_in_frame(self)
Parameters: This method does not accepts any parameters.
Returns: This method does not return any value.
Note: This method can only be used after an initial draw which caches the renderer.
Below examples illustrate the matplotlib.axes.Axes.redraw_in_frame() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt    fig, ax = plt.subplots()      def tellme(s):     ax.set_title(s, fontsize = 12, fontweight ="bold")     fig.canvas.draw()    ax.redraw_in_frame()      tellme('matplotlib.axes.Axes.redraw_in_frame() function \Example')   plt.show() 
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as npimport time    fig, ax = plt.subplots()line, = ax.plot(np.random.randn(100))  tstart = time.time()num_plots = 0fig.canvas.draw()while time.time()-tstart < 5:    line.set_ydata(np.random.randn(100))    ax.redraw_in_frame()    num_plots += 1      ax.set_title('matplotlib.axes.Axes.redraw_in_frame() \function Example')   plt.show() 
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python Dictionary copy() - GeeksforGeeks

30 Sep, 2021
Python Dictionary copy() method returns a shallow copy of the dictionary.
dict.copy()
The copy() method doesn’t take any parameters.
This method doesn’t modify the original, dictionary just returns copy of the dictionary.
Input : original = {1:'geeks', 2:'for'}
        new = original.copy()
Output : original:  {1: 'one', 2: 'two'}
         new:  {1: 'one', 2: 'two'}
As we are not passing any parameters 
there is no chance of any error.
Python3
# Python program to demonstrate working# of dictionary copyoriginal = {1: 'geeks', 2: 'for'} # copying using copy() functionnew = original.copy() # removing all elements from the list# Only new list becomes empty as copy()# does shallow copy.new.clear() print('new: ', new)print('original: ', original)
Output: 
new:  {}
original:  {1: 'geeks', 2: 'for'}
Python3
# given dictionarydict1 = {10: 'a', 20: [1, 2, 3], 30: 'c'}print("Given Dictionary:", dict1) # new dictionary and# copying using copy() methoddict2 = dict1.copy()print("New copy:", dict2) # Updating dict2 elements and# checking the change in dict1dict2[10] = 10dict2[20][2] = '45'  # list item updated print("Updated copy:", dict2)
Output:
Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}
Unlike copy(), the assignment operator does deep copy. 
Python3
# Python program to demonstrate difference# between = and copy()original = {1: 'geeks', 2: 'for'} # copying using copy() functionnew = original.copy() # removing all elements from new list# and printing bothnew.clear()print('new: ', new)print('original: ', original) original = {1: 'one', 2: 'two'} # copying using =new = original # removing all elements from new list# and printing bothnew.clear()print('new: ', new)print('original: ', original)
Output: 
new:  {}
original:  {1: 'geeks', 2: 'for'}
new:  {}
original:  {}
kumar_satyam
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Extracting the real and imaginary parts of an NumPy array of complex numbers - GeeksforGeeks

02 Sep, 2020
Numpy library gives us functions such as real() and imag() to find real and imaginary parts of a complex number. 
real() : To find real part of the complex number
imag() : To find imaginary part of the complex number
Example 1 :
# importing the moduleimport numpy as np  # creating a NumPy arraycomplex_num = np.array([-1 + 9j, 2 - 77j,                        31 - 25j, 40 - 311j,                        72 + 11j])  # traversing the listfor i in range(len(complex_num)):      print("{}. complex number is {}".format(i + 1, complex_num[i]))      print ("The real part is: {}".format(complex_num[i].real))      print ("The imaginary part is: {}\n".format(complex_num[i].imag))
Output :
1. complex number is (-1+9j)
The real part is: -1.0
The imaginary part is: 9.0

2. complex number is (2-77j)
The real part is: 2.0
The imaginary part is: -77.0

3. complex number is (31-25j)
The real part is: 31.0
The imaginary part is: -25.0

4. complex number is (40-311j)
The real part is: 40.0
The imaginary part is: -311.0

5. complex number is (72+11j)
The real part is: 72.0
The imaginary part is: 11.0

Example 2 : The imaginary value of real number will be 0.
# importing the moduleimport numpy as np  # creating a NumPy arraycomplex_num = np.array([-1, 31, 0.5])  # traversing the listfor i in range(len(complex_num)):      print("{}. Number is {}".format(i + 1, complex_num[i]))      print ("The real part is: {}".format(complex_num[i].real))      print ("The imaginary part is: {}\n".format(complex_num[i].imag))
Output :
1. Number is -1.0
The real part is: -1.0
The imaginary part is: 0.0

2. Number is 31.0
The real part is: 31.0
The imaginary part is: 0.0

3. Number is 0.5
The real part is: 0.5
The imaginary part is: 0.0

Python numpy-arrayManipulation
Python-numpy
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
strings.Join() Function in Golang With Examples - GeeksforGeeks

10 May, 2020
strings.Join() Function in Golang concatenates all the elements present in the slice of string into a single string. This function is available in the string package.
Syntax:
func Join(s []string, sep string) string

Here, s is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string.
Return Value: It returns a string.
Example 1:
// Golang program to illustrate the// use of strings.Join Function  package main  // importing fmt and stringsimport (    "fmt"    "strings")  // calling main methodfunc main() {      // array of strings.    str := []string{"Geeks", "For", "Geeks"}      // joining the string by separator    fmt.Println(strings.Join(str, "-"))}
Output:
Geeks-For-Geeks

Example 2:
// Golang program to illustrate the// use of strings.Join Function  package main  // importing fmt and stringsimport (    "fmt"    "strings")  // calling main methodfunc main() {    // array of strings.    str := []string{"A", "Computer-science", "portal", "for", "Geeks"}    // joining the string by separator in middle.    fmt.Println(strings.Join(str, " "))}
Output:
A Computer-science portal for Geeks

Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
Create a shared Folder between Host OS and Guest OS ( Virtual Box) - GeeksforGeeks

30 Mar, 2019
How to create a shared folder between host Operating System and Guest Operating system?
This is the scenario that you run Windows as your host operating system and Ubuntu in a VirtualBox, and that you want to access a specific Windows folder from Ubuntu.In short-Share a folder between Host OS-> Windows and Guest OS ->Ubuntu(Virtual box)
Step 1Install install Guest Additions from VirtualBox’s menu go to Devices->Install Guest AdditionsThis will mount a virtual CD on your /media/cdrom. As root user Open this /media/cdrom added folder using Open with terminal option(Right click with mouse).
Step 2Run the program VBoxLinuxAdditions.run. When the program completes reboot your VirtualBox.
$ sudo ./VBoxLinuxAdditions.run
Step 3Create a shared folder. From Virtual menu go to Devices->Shared Folders then add a new folder in the list, this folder should be the one in windows which you want to share with Ubuntu(Guest OS).Make this created folder auto-mount.Example -> Make a folder on Desktop with name Ubuntushare and add this folder.
Step 4When done with you shared folder(s) specification, we mount folder from Ubuntu(Guest OS).Create a mountpoint, this a directory in Ubuntu that will share files with the shared folder from Windows.Run this to create a directory in Ubuntu
$ sudo mkdir ~/Desktop/windowsshare
Step 5With your mountpoint created you can now mount the shared folder.Run this command to share the folder:
$ sudo mount -t vboxsf Ubuntushare ~/Desktop/windowsshare
Ubuntushare is the name of folder we add in VirtualBox Devices section this folder is in Windows(Host OS).~/Desktop/windowsshare is the directory in Ubuntu(Guest OS)
CONGRATULATIONS->Now you can share the files between Windows and Ubuntu. Try adding any file in windows(Host OS) Ubuntu share folder now check Ubuntu(Guest OS) windowsshare directory the file will be reflected.
This article is contributed by SHAURYA UPPAL. 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.
arnab1729
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Top Programming Languages for Android App Development
How to Run a Python Script using Docker?
Setting up the environment in Java
C# | How to insert an element in an Array? - GeeksforGeeks

28 Aug, 2019
An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C#.
Let’s say we have an array and we want to insert an element at a specific position in this array.
Here’s how to do it.
First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posCreate a new array with the size one greater than the previous sizeCopy all the elements from previous array into the new array till the position posInsert the element x at position posInsert the rest of the elements from the previous array into the new array after the pos
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Create a new array with the size one greater than the previous size
Copy all the elements from previous array into the new array till the position pos
Insert the element x at position pos
Insert the rest of the elements from the previous array into the new array after the pos
// C# program to insert an // element in an arrayusing System;  public class GFG {      // Main Method    static public void Main()    {          int n = 10;        int[] arr = new int[n];        int i;          // initial array of size 10        for (i = 0; i < n; i++)            arr[i] = i + 1;          // print the original array        for (i = 0; i < n; i++)            Console.Write(arr[i] + " ");        Console.WriteLine();          // element to be inserted        int x = 50;          // position at which element         // is to be inserted        int pos = 5;          // create a new array of size n+1        int[] newarr = new int[n + 1];          // insert the elements from the         // old array into the new array        // insert all elements till pos        // then insert x at pos        // then insert rest of the elements        for (i = 0; i < n + 1; i++) {            if (i < pos - 1)                newarr[i] = arr[i];            else if (i == pos - 1)                newarr[i] = x;            else                newarr[i] = arr[i - 1];        }          // print the updated array        for (i = 0; i < n + 1; i++)            Console.Write(newarr[i] + " ");        Console.WriteLine();    }}
Output:
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 50 5 6 7 8 9 10

CSharp-Arrays
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
JavaScript Math max() Method - GeeksforGeeks

09 Feb, 2022
Below is the example of the Math max() method.  
Example:  
javascript
<script type="text/javascript">     document.write("When  positive numbers are passed"+                    " as parameters: " + Math.max(10, 32, 2));</script>
Output:  
When  positive numbers are passed as parameters: 32
The Math.max() method is used to return the largest of zero or more numbers. The result is “-Infinity” if no arguments are passed and the result is NaN if at least one of the arguments cannot be converted to a number.The max() is a static method of Math, therefore, it is always used as Math.max(), rather than as a method of a Math object created.Syntax:  
Math.max(value1, value2, ...)
Parameters: This method accepts as ingle parameter that can be used n number of times as mentioned above and described below:  
value: This values sent to math.max() method for finding the largest.
Return values: The Math.max() method returns the largest of the given numbers.Below examples illustrates the Math max() method in JavaScript:  
Example 1:  
Input : Math.max(10, 32, 2)
Output: 32
Example 2:  
Input : Math.max(-10, -32, -1)
Output: -1
Example 3:  
Input : Math.max()
Output: -Infinity
Example 4:  
Input : Math.max(10,2,NaN)
Output: NaN
More codes for the above method are as follows: Program 1: When negative numbers are passed as parameters.  
javascript
<script type="text/javascript">         document.write("Result : " + Math.max(-10, -32, -1));</script>
Output:  
Result : -1
Program 2: When no parameters are passed.  
javascript
<script type="text/javascript">         document.write("Result : " + Math.max());</script>
Output:  
Result : -Infinity
Program : When NaN is passed as a parameter.  
javascript
<script type="text/javascript">         document.write("Result : " + Math.max(10,2,NaN));</script>
Output:  
Result : NaN
Supported Browsers:  
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
 
surinderdawra388
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
jQuery | hover() with Examples - GeeksforGeeks

15 Nov, 2021
The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element.Syntax:
$(selector).hover(Function_in, Function_out);

Here selector is the selected element.Parameter: It accepts two parameters which are specified below-
Function_in: It specifies the function to run when the mouse-enter event occurs.
Function_out: It is optional and specifies the function to run when the mouse-leave event occurs.
Return Value: It returns the background color effect with the selected element.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <script>        <!-- jQuery code to show the working of hover() method -->        $(document).ready(function() {            $("p").hover(function() {                $(this).css("background-color", "green");            }, function() {                $(this).css("background-color", "yellow");            });        });    </script>    <style>        p {            width: 55%;            height: 80px;            padding: 20px;            margin: 10px;            border: 2px solid green;            font-size: 50px;        }    </style></head>  <body>    <!--move the mouse in and out over this paragraph        and background color will change-->    <p>GeeksforGeeks !</p>  </body>  </html>
Output:Before mouse pointer is moved over the paragraph-After mouse pointer is moved over the paragraph-After mouse pointer is moved out from the paragraph-
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Taking multiple inputs from user in Python

In this tutorial, we are going to learn how to take multiple inputs from the user in Python.
The data entered by the user will be in the string format. So, we can use the split() method to divide the user entered data.
Let's take the multiple strings from the user.
# taking the input from the user
strings = input("Enter multiple names space-separated:- ")
# spliting the data
strings = strings.split()
# printing the data
print(strings)
If you run the above code, then you will get the following result.
Enter multiple names space-separated:- Python JavaScript Django React
['Python', 'JavaScript', 'Django', 'React']
What if we want to take multiple numbers as input? We can convert each input to an integer using the map and int function. Let's see an example.
# taking the input from the user
numbers = input("Enter multiple numbers space-separated:- ")
# spliting the data and converting each string number to int
numbers = list(map(int, numbers.split()))
# printing the data
print(numbers)
If you run the above code, then you will get the following result.
Enter multiple numbers space-separated:- 1 2 3 4 5
[1, 2, 3, 4, 5]
You can modify the code according to your needs and take the input from the users. If you
queries in the tutorial, mention them in the comment section.
How to get last day of the previous month in MySQL?

With the help of following MySQL query, we can get the last day of previous month −
mysql> SELECT LAST_DAY(now() - INTERVAL 1 MONTH) AS 'LAST DAY OF PREVIOUS MONTH';

+----------------------------+
| LAST DAY OF PREVIOUS MONTH |
+----------------------------+
| 2017-09-30                 |
+----------------------------+
1 row in set (0.00 sec)
Python | Pandas Series.str.zfill()

21 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas zfill() method is used to fill left side of string with zeros. If length of string is more than or equal to the width parameter, then no zeroes are prefixed. Since this is a string method, it is only applicable on series of strings and .str has to be prefixed every time before calling this method.
Usage: This function can be used whenever dealing with numeric data stored in string format. For example, If a series contains binary numbers with different bit size. Then to do operations like 1’s compliment addition, every binary needs to be of same bit size.
Syntax: Series.str.zfill(width)
Parameters:width: Maximum width of output string after prefixing zeroes.
Return type: Series with prefixed zeroes.
To download the data set used in following examples, click here.
In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below.
Example: Prefixing zeroes to salary column.
In this example, a width of 8 is set and zeroes are prefixed to Salary column using zfill() method. Since the Salary column has data type of int64, it’s converted to string first using astype() method.
# importing pandas import pandas as pd     # making data frame from csv at url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/employees.csv")   # converting to string dtypedata["Salary"]= data["Salary"].astype(str)  # width of output stringwidth = 10  # calling method and overwriting seriesdata["Salary"]= data["Salary"].str.zfill(width)  # displaydata
Output:As shown in the output image, zeroes have been prefixed and length of every string in salary column is 10 now.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if an object is iterable in Python?

13 Jan, 2021
In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case).  In this article, we are going to see how to check if an object is iterable in Python.
Examples: 
Input: “Hello”
Output: object is not iterable
Explanation: Object could be like( h, e, l, l, o)
Input: 5
Output: ‘int’ object is not iterable
Example 1:
Python3
# codename = "Hello"  for letter in name:  print(letter, end = " ")
Output:
H e l l o
Example 2:
Python3
# codenumber = 5 for i in number:  print(i)
Output
TypeError: 'int' object is not iterable
However, an int object is not iterable and so is a float object. The integer object number is not iterable, as we are not able to loop over it.
We are going to explore the different ways of checking whether an object is iterable or not. We use the hasattr() function to test whether the string object name has __iter__ attribute for checking iterability. However, this check is not comprehensive.
Method 1: Using __iter__ method check.
Python3
# codename = 'Roster'  if hasattr(name, '__iter__'):  print(f'{name} is iterable')    else:  print(f'{name} is not iterable')
Output:
Roster is iterable
Method 2: Using the Iterable class of collections.abc module.
We could verify that an object is iterable by checking whether it is an instance of the Iterable class. The instance check reports the string object as iterable correctly using the Iterable class. This works for Python 3 as well. For Python 3.3 and above, you will have to import the Iterable class from collections.abc and not from collections like so:
Python3
# codefrom collections.abc import Iterable    name = 'Roster'  if isinstance(name, Iterable):  print(f"{name} is iterable")    else:  print(f"{name} is not iterable")
Output:
Roster is iterable
Method 3: Using the iter() builtin function.
The iter built-in function works in the following way:
Checks whether the object implements __iter__, and calls that to obtain an iterator.
If that fails, Python raises TypeError, usually saying “C object is not iterable,” where C is the class of the target object.
Code:
Python3
# codename = "Roster"  try:  iter(name)  print("{} is iterable".format(name))     except TypeError:  print("{} is not iterable".format(name))
Output:
Roster is iterable
Python collections-module
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check if key has Non-None value in dictionary

26 Jul, 2019
Sometimes, while working with Python dictionaries, we might come across a problem in which we need to find if a particular key of dictionary is valid i.e it is not False or has a non None value. This kind of problem can occur in Machine Learning domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using ifThis task can simply be solved using the conditional operator "if". The if statement autochecks for the truthness of any statement and hence with the key’s value.
# Python3 code to demonstrate working of# Check if key has Non-None value in dictionary# Using if  # Initialize dictionarytest_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using if# Check if key has Non-None value in dictionaryres = Falseif test_dict['gfg']:    res = True      # printing result print("Does gfg have a Non-None value? : " + str(res))
The original dictionary : {‘gfg’: None, ‘is’: 4, ‘for’: 2, ‘CS’: 10}Does gfg have a Non-None value? : False
 
Method #2 : Using bool() + get()The above functions together can be used to perform this particular task. The get performs the task of getting the value corresponding a key and bool function checks for truthfulness.
# Python3 code to demonstrate working of# Check if key has Non-None value in dictionary# Using bool() + get()  # Initialize dictionarytest_dict = {'gfg' : None, 'is' : 4, 'for' : 2, 'CS' : 10}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using bool() + get()# Check if key has Non-None value in dictionaryres = bool(test_dict.get('gfg'))      # printing result print("Does gfg have a Non-None value? : " + str(res))
The original dictionary : {‘gfg’: None, ‘is’: 4, ‘for’: 2, ‘CS’: 10}Does gfg have a Non-None value? : False
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.