code-rag-bench/online-tutorials huggingface dataset:
C# int.Parse Method

Convert a string representation of number to an integer, using the int.Parse method in C#. If the string cannot be converted, then the int.Parse method returns an exception
Let’s say you have a string representation of a number.
string myStr = "200";
Now to convert it to an integer, use the int.Parse(). It will get converted.
int.Parse(myStr);
 Live Demo
using System.IO;
using System;
class Program {
   static void Main() {
      int res;
      string myStr = "200";
      res = int.Parse(myStr);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}
String is a numeric representation: 200
Using BigInt to calculate long factorials in JavaScript

We are required to write a JavaScript function that takes in a number as the only input. The function should calculate the factorial of big numbers (greater than 10) whose factorial can be accommodated in the simple let or type variables using the new bigInt variable of JavaScript. Lastly the function should convert the factorial to a string and return the string.
For example − If the input is −
const num = 45;
Then the output should be −
const output = '119622220865480194561963161495657715064383733760000000000';
The code for this will be −
const num = 45;
const longFactorial = (num) => {
   var bigInt = BigInt(num);
   var factorial = 1n;
   for (let i = 0n; i < bigInt ; i++) {
      factorial *= bigInt − i;
   }
   return String(factorial);
}
console.log(longFactorial(45));
And the output in the console will be −
119622220865480194561963161495657715064383733760000000000
How to check whether a JavaScript date is valid?

To check whether a JavaScript date is valid or not, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <body>  
      <script>
         var date1, date2;  
         date1 = new Date("2018/1/1");  
         if( ! isNaN ( date1.getMonth() )) {
            document.write("Valid date1: "+date1);
         }else{
            document.write("<br>Invalid date1");
         }
         date2 = new Date("20181/1");  
         if( ! isNaN ( date2.getMonth() )) {
            document.write("<br> Valid date2: "+date2);  
         }else{
            document.write("<br>Invalid date2");
         }  
      </script>  
   </body>
</html>
Valid date1: Mon Jan 01 2018 00:00:00 GMT+0530 (India Standard Time)
Valid date2: Mon Jan 01 20181 00:00:00 GMT+0530 (India Standard Time)
VBA - Strings

Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes " ".
variablename = "string"

str1 = "string"   ' Only Alphabets
str2 = "132.45"   ' Only Numbers
str3 = "!@#$;*"  ' Only Special Characters
Str4 = "Asc23@#"  ' Has all the above
There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail.
Returns the first occurrence of the specified substring. Search happens from the left to the right.
Returns the first occurrence of the specified substring. Search happens from the right to the left.
Returns the lower case of the specified string.
Returns the upper case of the specified string.
Returns a specific number of characters from the left side of the string.
Returns a specific number of characters from the right side of the string.
Returns a specific number of characters from a string based on the specified parameters.
Returns a string after removing the spaces on the left side of the specified string.
Returns a string after removing the spaces on the right side of the specified string.
Returns a string value after removing both the leading and the trailing blank spaces.
Returns the length of the given string.
Returns a string after replacing a string with another string.
Fills a string with the specified number of spaces.
Returns an integer value after comparing the two specified strings.
Returns a string with a specified character for specified number of times.
Returns a string after reversing the sequence of the characters of the given string.

    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Java - toString() Method

This method returns a String object representing the specified character value, that is, a one-character string.
String toString(char ch)

Here is the detail of parameters −
ch − Primitive character type.
ch − Primitive character type.
This method returns String object.
public class Test {

   public static void main(String args[]) {
      System.out.println(Character.toString('c'));
      System.out.println(Character.toString('C'));
   }
}
This will produce the following result −
c
C


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML fonts
How to find the 95% confidence interval for the glm model in R?

To find the confidence interval for a lm model (linear regression model), we can use confint function and there is no need to pass the confidence level because the default is 95%. This can be also used for a glm model (general linear model). Check out the below examples to see the output of confint for a glm model.
Live Demo
> set.seed(3214)
> x1<-rpois(20,5)
> y1<-sample(0:1,20,replace=TRUE)
> Model1<-glm(y1~x1,family="binomial")
> summary(Model1)
Call:
glm(formula = y1 ~ x1, family = "binomial")

Deviance Residuals:
Min 1Q Median 3Q Max
-1.6360 -1.4156 0.7800 0.8567 0.9946

Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.34851 1.17554 0.296 0.767
x1 0.09794 0.21421 0.457 0.648

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 24.435 on 19 degrees of freedom
Residual deviance: 24.221 on 18 degrees of freedom
AIC: 28.221

Number of Fisher Scoring iterations: 4

> confint(Model1)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -1.9946211 2.8014055
x1 -0.3179604 0.5537196
Live Demo
> x2<-runif(200,2,5)
> y2<-sample(0:1,200,replace=TRUE)
> Model2<-glm(y2~x2,family="binomial")
> summary(Model2)
Call:
glm(formula = y2 ~ x2, family = "binomial")

Deviance Residuals:
Min 1Q Median 3Q Max
-1.162 -1.152 -1.145 1.202 1.211

Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.009208 0.631317 -0.015 0.988
x2 -0.013999 0.169522 -0.083 0.934

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 277.08 on 199 degrees of freedom
Residual deviance: 277.07 on 198 degrees of freedom
AIC: 281.07

Number of Fisher Scoring iterations: 3

> confint(Model2)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -1.2517839 1.2317974
x2 -0.3473611 0.3192271
Live Demo
> x3<-runif(5000,2,5)
> y3<-sample(0:1,5000,replace=TRUE)
> Model3<-glm(y3~x3,family="binomial")
> summary(Model3)
Call:
glm(formula = y3 ~ x3, family = "binomial")

Deviance Residuals:
Min 1Q Median 3Q Max
-1.177 -1.166 -1.156 1.188 1.199

Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.03254 0.11913 0.273 0.785
x3 -0.01674 0.03288 -0.509 0.611

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 6930.6 on 4999 degrees of freedom
Residual deviance: 6930.3 on 4998 degrees of freedom
AIC: 6934.3

Number of Fisher Scoring iterations: 3

> confint(Model3)
Waiting for profiling to be done...
2.5 % 97.5 %
(Intercept) -0.20096508 0.2660569
x3 -0.08119495 0.0476911
Generating any custom JSON in ABAP

You can use class ZCL_MDP_JSON Library that can encode/parse any JSON. JSON is supported natively in ABAP by the following features:
With the use of JSON-XML- it is known as special XML format that can be used for JSON data to be described using an XML representation. 
By defining a mapping between ABAP types and JSON. This is used in serializations and deserializations using the identity transformation ID.
As you can specify JSON data in different forms as an XML source in the statement CALL TRANSFORMATION and JSON can be specified as a target.
Check out the following sample code:
Example:
DATA text TYPE string VALUE `Hi JSON, ABAP here!`.
DATA writer TYPE REF TO cl_sxml_string_writer.
DATA json TYPE xstring.
“ABAP to JSON
writer =cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE text = text
   RESULT XML writer.
json = writer->get_output( ).
“JSON to ABAP
text =`{“TEXT”:”Hi ABAP, JSON here!”}`.
CALL TRANSFORMATION id SOURCE XML text
   RESULT text = text.
JSON/ABAP Serializer and Deserializer
In SAP ERP7.40, you have a simple transformation that can be used to convert ABAP to JSON and JSON to ABAP. This is most suitable when you require maximum performance and not worried about using Serializer and de-serializer.
You can also refer to the below link: 
https://wiki.scn.sap.com/wiki/display/Snippets/One+more+ABAP+to+JSON+Serializer+and+Deserializer
ABAP to JSON usage example:
DATA: lt_flight TYPE STANDARD TABLE OF sflight,
   lrf_descr TYPE REF TO cl_abap_typedescr,
   lv_json  TYPE string.
SELECT * FROM sflight INTO TABLE lt_flight.

* serialize table lt_flight into JSON, skipping initial fields and converting ABAP field names into camelCase
lv_json =/ui2/cl_json=>serialize( data = lt_flight compress = abap_true pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).
WRITE / lv_json.
CLEAR lt_flight.

* deserialize JSON string json into internal table lt_flight doing camelCase to ABAP like field name mapping
/ui2/cl_json=>deserialize(EXPORTING json = lv_json pretty_name =/ui2/cl_json=>pretty_mode-camel_case CHANGING data = lt_flight ).

* serialize ABAP object into JSON string
lrf_descr = cl_abap_typedescr=>describe_by_data( lt_flight ).
lv_json =/ui2/cl_json=>serialize( lrf_descr ).
WRITE / lv_json.
rand package in Golang - GeeksforGeeks

08 Jun, 2020
Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random numbers for security-sensitive work, then use the crypto/rand package.
Note: In this package, the mathematical interval notation such as [0, n) is used.
type Rand
type Source
type Zipf
Example 1:
// Golang program to illustrate // how to Get Intn Type Random  // Number package main      import (     "fmt"    "math/rand")      // Main function func main() {          // Finding random numbers of int type     // Using Intn() function     res_1 := rand.Intn(7)     res_2 := rand.Intn(8)     res_3 := rand.Intn(2)          // Displaying the result     fmt.Println("Random Number 1: ", res_1)     fmt.Println("Random Number 2: ", res_2)     fmt.Println("Random Number 3: ", res_3) } 
Output:
Random Number 1:  6
Random Number 2:  7
Random Number 3:  1

Example 2:
// Golang program to illustrate // how to get a random number package main    import (     "fmt"    "math/rand")    // Main function func main() {        // Finding random numbers of int type     // Using Int31() function     res_1 := rand.Int31()     res_2 := rand.Int31()     res_3 := rand.Int31()        // Displaying the result     fmt.Println("Random Number 1: ", res_1)     fmt.Println("Random Number 2: ", res_2)     fmt.Println("Random Number 3: ", res_3) } 
Output:
Random Number 1:  1298498081
Random Number 2:  2019727887
Random Number 3:  1427131847

Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Python program to sort a list of tuples alphabetically

When it is required to sort a list of tuples in alphabetical order, the 'sort' method can be used. When using this, the contents of the original tuple get changed, since in-place sorting is performed.
The 'sort' function sorts the values in ascending order by default. If the order of sorting is specified as descending, it is sorted in descending order.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same −
Live Demo
def sort_tuple_vals(my_tup):  
   my_tup.sort(key = lambda x: x[0])
   return my_tup
my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56),("Nysa", 35), ("May", "Pink")]
     
print("The tuple is ")
print(my_tup)
print("After sorting the tuple alphabetically, it becomes : ")
print(sort_tuple_vals(my_tup))
The tuple is
[('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]
After sorting the tuple alphabetically, it becomes :
[('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]
A function named 'sort_tuple_vals' is defined, that takes a tuple as a parameter.
It uses the sort method and the lambda function to sort the elements in the tuple.
This is returned when the function is called.
Now the tuple is defined, and the function is called by passing this tuple as the parameter.
The output is displayed on the console.
Tryit Editor v3.7

Tryit: box-shadow with color
Copy Files from Docker Container to Local Machine

If you are working on a project that requires frequent copying of files and folders either from container to your local machine or from the local machine to the container, docker provides an easy and simple way to do that. If you have already built a docker image which is of large size and contains a large number of files and in the midst of the project you want to copy files to and from the container, it’s highly inefficient to put the files in the docker build context and build images repeatedly. Instead, docker allows easy copying of files to and from containers.
In this article, we will learn about the commands that will allow us to do so. We will look for commands for copying the files from both local machine to container and vice versa.
If you want to copy a file from your container to your local machine, you can use the following command.
sudo docker cp <Container ID>:<Path of file inside the container> <Path in the local machine>
For example,
If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /usr/src/app/file.txt in the container to /home/username/Desktop/folder in the local machine, you can use the command -
sudo docker cp f4628571q5gc:/usr/src/app/file.txt home/username/Desktop/folder/
If you want to paste the file in the current directory of you local machine, you can simply use -
sudo docker cp f4628571q5gc:/usr/src/app/file.txt . (Don’t forget the dot)
If you want to copy all the files from a particular folder in container, to a folder in the local machine, use the following command -
sudo docker cp f4628571q5gc:/usr/src/app/ home/username/Desktop/folder/
If you want to copy a file from your local machine to a container, you can use the following command.
sudo docker cp <Path in the local machine> <Container ID>:<Path of file inside the container>
For example,
If you have an ubuntu container, with ID f4628571q5gc and you want to copy a file from path /home/username/Desktop/folder/file.txt in the local machine to /usr/src/app/ in the container, you can use the command -
sudo docker cp /home/username/Desktop/folder/file.txt f4628571q5gc:/usr/src/app/
If you want to copy all the files from a folder in your local machine to a folder in the container, use the following command -
sudo docker cp /home/username/Desktop/folder f4628571q5gc:/usr/src/app/
To conclude, after you have already built an image with a build context and you want to copy files and folders to and from the container, you can easily do that using the commands mentioned above.
base64.b64encode() in Python

26 Mar, 2020
With the help of base64.b64encode() method, we can encode the string into the binary form.
Syntax : base64.b64encode(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using base64.b64encode() method, we are able to get the encoded string which can be in binary form by using this method.
# import base64from base64 import b64encode  s = b'GeeksForGeeks'# Using base64.b64encode() methodgfg = b64encode(s)  print(gfg)
Output :
b’R2Vla3NGb3JHZWVrcw==’
Example #2 :
# import base64from base64 import b64encode  s = b'I love python'# Using base64.b64encode() methodgfg = b64encode(s)  print(gfg)
Output :
b’SSBsb3ZlIHB5dGhvbg==’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CLAHE Histogram Equalization – OpenCV

09 Nov, 2021
In this tutorial, we are going to see how to apply Contrast Limited Adaptive Histogram Equalization (CLAHE) to equalize images. CLAHE is a variant of Adaptive histogram equalization (AHE) which takes care of over-amplification of the contrast. CLAHE operates on small regions in the image, called tiles, rather than the entire image. The neighboring tiles are then combined using bilinear interpolation to remove the artificial boundaries. This algorithm can be applied to improve the contrast of images.
We can also apply CLAHE to color images, where usually it is applied on the luminance channel and the results after equalizing only the luminance channel of an HSV image are much better than equalizing all the channels of the BGR image. In this tutorial, we are going to learn how to apply CLAHE and process a given input image for histogram equalization.
Parameters :When applying CLAHE, there are two parameters to be remembered:clipLimit – This parameter sets the threshold for contrast limiting. The default value is 40. tileGridSize – This sets the number of tiles in the row and column. By default this is 8×8. It is used while the image is divided into tiles for applying CLAHE.  
Code for above: 
Python3
import cv2import numpy as np # Reading the image from the present directoryimage = cv2.imread("image.jpg")# Resizing the image for compatibilityimage = cv2.resize(image, (500, 600)) # The initial processing of the image# image = cv2.medianBlur(image, 3)image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # The declaration of CLAHE# clipLimit -> Threshold for contrast limitingclahe = cv2.createCLAHE(clipLimit = 5)final_img = clahe.apply(image_bw) + 30 # Ordinary thresholding the same image_, ordinary_img = cv2.threshold(image_bw, 155, 255, cv2.THRESH_BINARY) # Showing all the three imagescv2.imshow("ordinary threshold", ordinary_img)cv2.imshow("CLAHE image", final_img)
Input image: 
input image
Output:  
Ordinary Threshold
CLAHE Applied
 
stevekim121
Image-Processing
OpenCV
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
Placement new operator in C++

In this section we will see what is the placement new operator in C++. This placement new is another variation of new operator. The normal new operator performs two things. It allocates memory, and then constructs an object in allocated memory.
The new operator allocates memory in the heap section and constructs objects there. But for the placement new operator, it constructs object at the given address. To deallocate memory, we can use delete keyword if the memory is allocated using new operator. But for placement new there is no placement delete feature.
So in a nutshell, placement new allows you to "construct" an object on memory that's already allocated to a given variable. This is useful for optimizations as it is faster to not reallocate and reuse the same memory that is already assigned to it. It can be used as follows:
new (address) (type) initializer
We can specify an address where we want a new object of given type to be constructed. For example.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int a = 5;
   cout << "a = " << a << endl;
   cout << "&a = " << &a << endl;
   // Placement new changes the value of X to 100
   int *m = new (&a) int(10);
   cout << "\nAfter using placement new:" << endl;
   cout << "a = " << a << endl;
   cout << "m = " << m << endl;
   cout << "&a = " << &a << endl;
   return 0;
}
a = 5
&a = 0x22fe34
After using placement new:
a = 10
m = 0x22fe34
&a = 0x22fe34
How to call loading function with React useEffect?

05 Jan, 2021
The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates. 
If we pass only a callback, the callback will run after each render. If we just want to run the useEffect function after the initial render, as a second argument, we can give it an empty array. If we pass a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. 
For example, the callback will run after the first render and after any render that one of varOne or varTwo is changed for the following code:
useEffect(() => console.log('Hi '), [varOne, varTwo])
If we pass the second argument an empty array after each render’s React will compare the array and will see nothing was changed and callback will be called only after the first render.
Syntax:
const MyComponent = (props) {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);
  return <div> {/* jsx code */} </div>;
}
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Filename: App.js
Javascript
import React, { useEffect, useState } from "react";  const App = (props) => {  const [btnText, updatebtnText] = useState("")    const loadDataOnlyOnce = () => {    updatebtnText("Hello kapil")  }      // This function will called only once  useEffect(() => {    loadDataOnlyOnce();  }, [])    return (    <div style={{ margin: 200 }}>      <button onClick={() => updatebtnText("Hi")} >        {btnText}      </button>    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
After clicking button, the text changes
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
Lodash _.groupBy() Method
Python | sympy.Matrix().row_insert()

25 Jun, 2019
With the help of Matrix().row_insert() method, we can insert a row in a matrix having dimension nxm, where dimension of inserted row is 1xm.
Syntax : Matrix().row_insert()Return : Return a new matrix.
Example #1 :In this example, we are able to insert a row in a matrix by using Matrix().row_insert() method.
# Import all the methods from sympyfrom sympy import *  # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]])  # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(1, Matrix([[3, 4]]))   print(new_mat)
Output :
Matrix([[1, 2], [3, 4], [2, 1]])
Example #2 :
# Import all the methods from sympyfrom sympy import *  # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]])  # use the row_insert() method for matrixnew_mat = gfg_mat.row_insert(2, Matrix([[13, 24]]))   print(new_mat)
Output :
Matrix([[1, 2], [2, 1], [13, 24]])
SymPy
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
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
How to add a new element to HTML DOM in JavaScript?

To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element.
1) First, create a div section and add some text to it using <p> tags. 
2) Create an element <p> using document.createElement("p").
3) Create a text, using document.createTextNode(), so as to insert it in the above-created element("p").
4) Using appendChild() try to append the created element, along with text, to the existing div tag.
Thus a new element is created(<p>) and appended to the existing element(<div>).
In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output. 
Live Demo
<html>
<body>
<div id="new">
<p id="p1">Tutorix</p>
<p id="p2">Tutorialspoint</p>
</div>
<script>
   var tag = document.createElement("p");
   var text = document.createTextNode("Tutorix is the best e-learning platform");
   tag.appendChild(text);
   var element = document.getElementById("new");
   element.appendChild(tag);
</script>
</body>
</html>
Tutorix

Tutorialspoint

Tutorix is the best e-learning platform
Python | Create Test DataSets using Sklearn

11 Feb, 2022
Python’s Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It’s fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator.  
Python3
# importing librariesfrom sklearn.datasets import make_blobs # matplotlib for plotingfrom matplotlib import pyplot as pltfrom matplotlib import style
Python3
# Creating Test DataSets using sklearn.datasets.make_blobsfrom sklearn.datasets import make_blobsfrom matplotlib import pyplot as pltfrom matplotlib import style style.use("fivethirtyeight") X, y = make_blobs(n_samples = 100, centers = 3,               cluster_std = 1, n_features = 2) plt.scatter(X[:, 0], X[:, 1], s = 40, color = 'g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:  
make_blobs with 3 centers
 
 
Python3
# Creating Test DataSets using sklearn.datasets.make_moonfrom sklearn.datasets import make_moonsfrom matplotlib import pyplot as pltfrom matplotlib import style X, y = make_moons(n_samples = 1000, noise = 0.1)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:  
make_moons with 1000 data points
 
 
Python3
# Creating Test DataSets using sklearn.datasets.make_circlesfrom sklearn.datasets import make_circlesfrom matplotlib import pyplot as pltfrom matplotlib import style style.use("fivethirtyeight") X, y = make_circles(n_samples = 100, noise = 0.02)plt.scatter(X[:, 0], X[:, 1], s = 40, color ='g')plt.xlabel("X")plt.ylabel("Y") plt.show()plt.clf()
Output:  
make _circle with 100 data points
 
acenayeem01
devbrat0srivastava
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Random Forest Regression in Python
ML | Underfitting and Overfitting
ML | Monte Carlo Tree Search (MCTS)
Changing Class Members in Python

14 Dec, 2021
In the previous fact, we have seen that Python doesn’t have the static keyword. All variables that are assigned a value in the class declaration are class variables.
We should be careful when changing the value of a class variable. If we try to change a class variable using an object, a new instance (or non-static) variable for that particular object is created and this variable shadows the class variables. Below is a Python program to demonstrate the same.
Python3
# Class for Computer Science Studentclass CSStudent:    stream = 'cse'     # Class Variable    def __init__(self, name, roll):        self.name = name        self.roll = roll # Driver program to test the functionality# Creating objects of CSStudent classa = CSStudent("Geek", 1)b = CSStudent("Nerd", 2) print ("Initially")print ("a.stream =", a.stream )print ("b.stream =", b.stream ) # This thing doesn't change class(static) variable# Instead creates instance variable for the object# 'a' that shadows class member.a.stream = "ece" print ("\nAfter changing a.stream")print ("a.stream =", a.stream )print ("b.stream =", b.stream )
Output: 
Initially
a.stream = cse
b.stream = cse

After changing a.stream
a.stream = ece
b.stream = cse
We should change class variables using class names only. 
Python3
# Program to show how to make changes to the# class variable in Python # Class for Computer Science Studentclass CSStudent:    stream = 'cse'     # Class Variable    def __init__(self, name, roll):        self.name = name        self.roll = roll # New object for further implementationa = CSStudent("check", 3)print "a.stream =", a.stream # Correct way to change the value of class variableCSStudent.stream = "mec"print "\nClass variable changes to mec" # New object for further implementationb = CSStudent("carter", 4) print "\nValue of variable steam for each object"print "a.stream =", a.streamprint "b.stream =", b.stream
Output: 
a.stream = cse

Class variable changes to mec

Value of variable steam for each object
a.stream = mec
b.stream = mec
This article is contributed by Nikhil Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
blackmath
ugs18091cseakash
punamsingh628700
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

HTML Web Storage
Tryit: HTML local storage
How to check if a "lateInit" variable has been initialized in Kotlin?

Any variable which is initialized after its declaration is known as a "late
initialized variable". In conventional programming languages, any non-NULL
type of variable need to be initialized in the constructor. But sometimes, by
mistake, developers forget to do these NULL checks which causes a
programming error. In order to avoid this situation, Kotlin introduced a new
modifier called as "lateInit". Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not.
In order to create a "lateInit" variable, we just need to add the keyword
"lateInit" as an access modifier of that variable. Following are the couple of
conditions that need to be followed in order to use "lateInit" in Kotlin −
Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit".
Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit".
"lateInit" is only allowed with non-NULLable data types.
"lateInit" is only allowed with non-NULLable data types.
"lateInit" does not work with primitive data types.
"lateInit" does not work with primitive data types.
"lateInit" can be used when the variable property does not have any getter and setter methods.
"lateInit" can be used when the variable property does not have any getter and setter methods.
In this example, we will declare a variable as a "lateInit" variable and we will be using our Kotlin library function to check whether the variable is initialized or not.
class Tutorial {

   lateinit var name : String

   fun checkLateInit(){
      println(this::name.isInitialized)
      // it will print false as the value is not initialized

      // initializing name
      name = "www.tutorialspoint.com/"
      println(this::name.isInitialized)
      // It will return true
   }
}

fun main() {
   var obj=Tutorial();
   obj.checkLateInit();
}
Once you execute the code, it will generate the following output −
false
true
In the second case, the variable name is initialized, hence it returns True.
Google Guice - First Application

Let's create a sample console based application where we'll demonstrate dependency injection using Guice binding mechanism step by step.
//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}
//Binding Module
class TextEditorModule extends AbstractModule {
   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}
class TextEditor {
   private SpellChecker spellChecker;
   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck(); 
Create a java class named GuiceTester.
GuiceTester.java
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck(); 
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}


//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}
Compile and run the file, you will see the following output.
Inside checkSpelling.


    27 Lectures 
     1.5 hours 

 Lemuel Ogbunude
 Print
 Add Notes
 Bookmark this page
How to add a title to an existing line border in Java?

Here, we will see how to add a title to an existing Line border. Let’s say we have a label and the border is to be set −
LineBorder linedBorder = new LineBorder(Color.blue);
TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title");
JLabel label = new JLabel();
label.setBorder(titledBorder);
The following is an example to add a title to an existing line border −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      LineBorder linedBorder = new LineBorder(Color.blue);
      TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title");
      JLabel label = new JLabel();
      label.setBorder(titledBorder);
      Container contentPane = frame.getContentPane();
      contentPane.add(label, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
CSS Overflow

The CSS overflow property controls what 
happens to content that is too big to fit into an area.
The overflow property specifies whether to clip 
the content or 
to add scrollbars when the content of an element is too big to fit in the specified 
area.
The overflow property has the following values:
visible - Default. The overflow is not clipped. 
The content renders outside the element's box
hidden - The overflow is clipped, and the rest of the content will be invisible
scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
auto - Similar to scroll, 
but it adds scrollbars only when necessary
Note: The overflow property only works for block elements with a specified height.
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
By default, the overflow is visible, meaning that it is not clipped and it 
renders outside the element's box:
With the hidden value, the overflow is clipped, and the rest of the content is hidden:
Setting the value to scroll, the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):
The auto value is similar to scroll, 
but it adds scrollbars only when necessary:
The overflow-x and overflow-y properties specifies 
whether to change the overflow of content just horizontally or vertically (or 
both):
overflow-x specifies what to do with the left/right edges of the 
content.
overflow-y specifies what to do with the top/bottom edges of the 
content.
Force a scroll bar to the <div> element with class="intro".
<style>
.intro {
  width: 200px;
  height: 70px;
  : ;
}
</style>

<body>

<div class="intro">
Lorem ipsum dolor sit amet,consectetur adipiscing elit.Phasellus imperdiet, nulla et dictum interdum,nisi lorem egestas odio,vitae scelerisque enim ligula venenatis dolor.
</div>

</body>

Start the Exercise
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.
C | Pointer Basics | Question 6 - GeeksforGeeks

04 Feb, 2013
#include<stdio.h>int main(){    int arr[] = {10, 20, 30, 40, 50, 60};    int *ptr1 = arr;    int *ptr2 = arr + 5;    printf("Number of elements between two pointer are: %d.",                                 (ptr2 - ptr1));    printf("Number of bytes between two pointers are: %d",                                (char*)ptr2 - (char*) ptr1);    return 0;}
Assume that an int variable takes 4 bytes and a char variable takes 1 byte(A) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 20(B) Number of elements between two pointer are: 20.Number of bytes between two pointers are: 20(C) Number of elements between two pointer are: 5.Number of bytes between two pointers are: 5(D) Compiler Error(E) Runtime ErrorAnswer: (A)Explanation: Array name gives the address of first element in array. So when we do ‘*ptr1 = arr;’, ptr1 starts holding the address of element 10. ‘arr + 5’ gives the address of 6th element as arithmetic is done using pointers. So ‘ptr2-ptr1’ gives 5. When we do ‘(char *)ptr2’, ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers.
C-Pointers
Pointers
C Language
C Quiz
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Misc | Question 7
Output of C programs | Set 64 (Pointers)
time.Weekday() Function in Golang With Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Weekday() function in Go language is used to check the English name of the day. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func (d Weekday) String() string

Return value: It returns English name of the day.
Example 1:
// Golang program to illustrate the usage of// Weekday() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Main functionfunc main() {      // Calling Weekday method using    // Now function    weekday := time.Now().Weekday()      // Prints the current weekday    fmt.Println("Weekday is: ", weekday)}
Output:
Weekday is:  Thursday

Example 2:
// Golang program to illustrate the usage of// Weekday() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Main functionfunc main() {      // Calling Weekday method using    // Now function    weekday := time.Now().Weekday()      // Prints the current     // weekday in int form    fmt.Println("Weekday in number is: ", int(weekday))}
Output:
Weekday in number is:  4

GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Time Formatting in Golang
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Comparing dates in Python

Comparing dates and times is a very crucial requirement in any programming language. Python has a datetime library which has many inbuilt functions to use date and time. Interestingly date and time can also be compared like mathematical comparison between various numbers.
In the below example we have chosen to dates by passing the value of year, month and date to the date function. Then we compare the dates using a if condition and we get the appropriate result.
import datetime
# Get default date format
print("Today is: ",datetime.date.today())
date1 = datetime.date(2019, 7, 2)
date2 = datetime.date(2019, 6, 5)

# Compare dates
if (date1 > date2):
   print("Date1 > Date2")
elif (date1 < date2):
   print("Date1 < Date2")
else:
   print("Dates are equal")

# Get Default date time format
print(datetime.datetime.now())
date_time1 = datetime.datetime(2019, 7, 2,23,15,9)
date_time2 = datetime.datetime(2019, 7, 2,23,15,9)

# Compare date time
print(date_time2)
if (date_time1 == date_time2):
   print("Date Time 1 is equal to Date Time 2")
else:
   print("Date times are unequal")
Running the above code gives us the following result −
Today is: 2019-08-01
Date1 > Date2
2019-08-01 16:34:01.061242
2019-07-02 23:15:09
Date Time 1 is equal to Date Time 2
jQuery Traversing Siblings

With jQuery you can traverse sideways in the DOM 
tree to find siblings of an element.
Siblings share the same parent. 
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:
You can also use an optional parameter to filter the search for siblings.
The following example returns all sibling elements of <h2> that are <p> 
elements:
The next() method returns the next sibling element of the selected element.
The following example returns the next sibling of <h2>:
The nextAll() method returns all next sibling elements of the selected element.
The following example returns all next sibling elements of 
<h2>:
The nextUntil() method returns all next sibling elements between two given 
arguments.
The following example returns all sibling elements 
between a <h2> and a <h6> element:
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they 
return previous sibling elements (traverse backwards along sibling 
elements in the DOM tree, instead of forward).
Use a jQuery method to get all siblings elements of an <h2> element.
$("h2").();

Start the Exercise
For a complete overview of all jQuery Traversing methods, please go to our
jQuery Traversing Reference.
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.
How to Display Random ASCII Art on Linux Terminal?

09 Apr, 2021
Here we are going to see how to print the drawing on the terminal in the form of ASCII characters.ASCII-Art-Splash-Screen is a tool written in python that pulls a random drawing from a repository and shows it every time you open the terminal. This work on UNIX-based systems like Linux and macOS. 
Now let’s see how to install the ASCII-Art-Splash-Screen tool on our Linux system.
The followings are the two requirements to install the ASCII-Art-Splash-Screen tool:
Python3 (Installation of python on Linux)
curl (CLI tool to download files)
Let’s see how to install curl:
To install curl on the Debian based system like Ubuntu and Kali Linux use the following command:
sudo apt install curl
For systems like RHEL/CentOS:
 yum install curl
For the Fedora 22+:
dnf install curl
Before moving further make sure that you have installed these dependencies on the system.
Now let’s see how to install ASCII-Art-Splash-Screen tool. First clone the GitHub repository on the system using the following command:
git clone https://github.com/DanCRichards/ASCII-Art-Splash-Screen.git 
After this move into the local repository and then copy the ascii.py file into the home directory. Use the following commands to do this:
cd ASCII-Art-Splash-Screen/
cp ascii.py ~/
Now to get the ASCII art on the terminal when we open the terminal we need to put python3 ascii.py command into the .bashrc file. Use the following command to put this command into .bashrc file
echo "python3 ascii.py" >> ~/.bashrc
We have successfully installed the ASCII-Art-Splash-Screen  tool on our Linux system. 
Now when you open a new terminal you will see the new ASCII art on the terminal every time. Here are some of them.
ASCII art1
ASCII art2
ASCII art3
This is how we can print the ASCII art on an open new terminal.
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.