code-rag-bench/online-tutorials huggingface dataset:
How To Organize Data Science Project Notebooks With Extensions | Towards Data Science

While working on a Data Science project notebook, I create code and markdown cells every minute, print variables, get results, visualize data, try tens of visualizations to find the best looking ones... If I don’t keep well organized during all this process, I can’t manage to come to the end of the project until the deadline.
In this article, I am going to share the Jupyter notebook extensions I use everyday while working on a project.
In the terminal:
pip install jupyter_contrib_nbextensions
In Jupyter notebook:
! pip install jupyter_contrib_nbextensions
After installing notebook extensions, click on the Home tab, then click Nbextensions.
Select Collapsible Headings, Codefolding, Table of Contents(2), Autopep8, and ExecuteTime.
After opening your notebook you will see the following toolbar.
Time to discover these 5 extensions:
This extension is going to keep you organized in your technical presentations.
Here is all your project: Only one line!
It is very easy to navigate through these collapsible headings.
This is kind of a collapsible heading in code cells. If you use this extension, your code is going to look shorter. Long code cells are hidden. The little blue left-right arrow shows that you can open this line.
This is the icon for the table of contents extension in the notebook.
When you click it, a window pops up on the left.
You can change settings by clicking the settings button.
The best thing in this extension is, you do nothing. The table of contents is prepared automatically. You just put headings to markdown cells, and it automatically gives numbers to your headings. Love it!
What is PEP-8 style?
PEP-8 is a guideline on how to write easy-to-read and consistent code. It is written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001.
How to install autopep8?
python3 -m pip install autopep8
This code installs the autopep8 to Python3
How to use autopep8?
Go to the cell you want to fit the pep8 standards. Just click this icon at the toolbar.
It will change your code from something like this,
into something like that.
Cool!
Execution time is important if you are working with a huge amount of data. You try to decrease computing costs and make your code run faster. Instead of using the %timeit or %time commands, you can measure running time and timestamps for all cells.
Jupyter notebook has around 60 extensions. I shared only 5 of them that make my life easier. Discover the other extensions by just clicking on them.
Any suggestions to seymatas@gmail.com will be very appreciated!
Compute the Negative Binomial Density in R Programming - dnbinom() Function - GeeksforGeeks

25 Jun, 2020
dnbinom() function in R Language is used to compute the value of negative binomial density. It also creates a plot of the negative binomial density.
Syntax: dnbinom(vec, size, prob)
Parameters:vec: x-values for binomial densitysize: Number of trialsprob: Probability
Example 1:
# R program to compute# Negative Binomial Density  # Vector of x-valuesx <- seq(0, 10, by = 1)  # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5)y
Output:
 [1] 0.0009765625 0.0048828125 0.0134277344 0.0268554688 0.0436401367
 [6] 0.0610961914 0.0763702393 0.0872802734 0.0927352905 0.0927352905
[11] 0.0880985260

Example 2:
# R program to compute# Negative Binomial Density  # Vector of x-valuesx <- seq(0, 100, by = 1)  # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5)  # Plot a graphplot(y)
Output:
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
What characters are valid for JavaScript variable names?

To check the valid characters for JavaScript variable names, you should follow the below given naming conventions, which discuss about other rules to name a variable −
Name can begin with $ and _ characters, for example, _result.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
Here are the correct forms of a variable name in JavaScrip −
result
 _result
The following is an incorrect form for a variable name −
2result
Java SQL Timestamp setTime() function with examples - GeeksforGeeks

25 Oct, 2019
The setTime() function is a part of Timestamp class of Java SQL.The function is used to set the time of the Timestamp object. The function takes time in milliseconds which represents the time in milliseconds after 1st January, 1970.
Function Signature:
public void setTime(long t)
Syntax:
ts1.setTime(l);
Parameters: The function accepts a long value l as parameter which is to be set as the time.
Return value: The function does not return any value.
Exception: The function does not throw any exceptions.
Below programs illustrates the use of setTime() function
Example 1: Create a timestamp and use the setTime() to change the time of timestamp object.
// Java program to demonstrate the// use of setTime() function  import java.sql.*;  public class solution {    public static void main(String args[])    {        // Create two timestamp objects        Timestamp ts = new Timestamp(10000);          // Display the timestamp object        System.out.println("Timestamp time: "                           + ts.toString());          // Set the value of timestamp object        // using setTime function        ts.setTime(1000000000);          // Display the new timestamp object        System.out.println("New Timestamp time: "                           + ts.toString());    }}
Timestamp time: 1970-01-01 00:00:10.0
New Timestamp time: 1970-01-12 13:46:40.0

Example 2: Create a timestamp and use the setTime() to change the time of timestamp object by passing negative long value as parameter. Giving negative long value represents the time before 1st January 1970
// Java program to demonstrate the// use of setTime() function  import java.sql.*;  public class solution {    public static void main(String args[])    {        // Create two timestamp objects        Timestamp ts = new Timestamp(10000);          // Display the timestamp object        System.out.println("Timestamp time: "                           + ts.toString());          // Set the value of timestamp object        // using setTime function        ts.setTime(-1000000000);          // Display the new timestamp object        System.out.println("New Timestamp time: "                           + ts.toString());    }}
Timestamp time: 1970-01-01 00:00:10.0
New Timestamp time: 1969-12-20 10:13:20.0

Reference: https://docs.oracle.com/javase/9/docs/api/java/sql/Timestamp.html#setTime-long-
shubham_singh
Java-Functions
Java-Sql package
Java-TimeStamp
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
C program to write an image in PGM format

The PGM is the Portable Gray Map. If we want to store a 2d array in C as images in PNG, JPEG, or any other image format, we have to do lots of work to encode the data in some specified format before writing into a file.
The Netpbm format gives an easy and portable solution. The Netpbm is an open source package of graphics program and it is used basically in linux or Unix platform. It also works under Microsoft Windows systems.
Each file starts with a two-byte magic number. This magic number is used to identify the type of the file. The types are PBM, PGM, PPM etc. It also identifies the encoding (ASCII or Binary). The magic number is a capital P followed by a single digit number.
The ASCII encoding allows human readability and easy transfer to other platforms; the binary format is more efficient in file size but it may have native byte-order issues.
How to write PGM files?
Set the magic number P2
Add whitespace (Space, Tabs, CRs, LFs)
Add width, formatted as ASCII character in decimal
Add Whitespace
Add height, formatted as ASCII character in decimal
Add Whitespace
Put the maximum gray value, again in ASCII decimal
Add Whitespace
Width x Height gray values, each in ASCII decimal (Range between 0 and maximum value), separated by whitespace from top to bottom.
#include <stdio.h>
main() {
   int i, j;
   int w = 13, h = 13;
   // This 2D array will be converted into an image The size is 13 x 13
   int image[13][13] = {
      { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 },
      { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31},
      { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47},
      { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63},
      { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79},
      { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 },
      { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111},
      { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127},
      { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143},
      { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159},
      { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175},
      { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191},
      { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207}
   };
   FILE* pgmimg;
   pgmimg = fopen("my_pgmimg.pgm", "wb"); //write the file in binary mode
   fprintf(pgmimg, "P2\n"); // Writing Magic Number to the File
   fprintf(pgmimg, "%d %d\n", w, h); // Writing Width and Height into the
   file
   fprintf(pgmimg, "255\n"); // Writing the maximum gray value
   int count = 0;
   for (i = 0; i < h; i++) {
      for (j = 0; j < w; j++) {
         fprintf(pgmimg, "%d ", image[i][j]); //Copy gray value from
         array to file
      }
      fprintf(pgmimg, "\n");
   }
   fclose(pgmimg);
}
The PGM image is looking like below
wxPython – Disable Button

18 Jun, 2020
In this article we are going to learn about how can we disable a button present in a frame. Sometimes when we dont want user to press a button we can disable a button and the button become unclickable.In order to disable a button we can use Disable() function associated with wx.Button class of wxPython.
Syntax: wx.Button.Disable(Self)
Parameters: No parameters required in Disable() function.
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()      def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)        self.pnl = wx.Panel(self)        bmp = wx.Bitmap('download.jpg')                  # CREATE BUTTON AT POINT (20, 20)        self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20),                                size =(100, 30),  name ="button")        # SET BUTTON DISABLED        self.st.Disable()        self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre()  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output Image:
Python wxPython-Button
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Lodash _.random() Method

09 Sep, 2020
The _.random() method is used to return a random number which is in the range provided to the function. If floating is true, or either lower or upper are floats, a floating-point number is returned instead of an integer.
Syntax:
_.random([lower = 0], [upper = 1], [floating])

Parameters: This method accepts three parameters as mentioned above and described below:
lower: This parameter holds the lower bound.
upper: This parameter holds the upper bound.
floating: This parameter specifies returning a floating-point number.
Return Value: This method returns the random number.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");            // Use of _.random method console.log(_.random(10)); console.log(_.random(10, 12)); console.log(_.random(10, 12)); console.log(_.random(10.3, 12.5)); 
Output:
3
11
10
12.000118273018167

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // lower and upper valuelet lower = 2; let upper = 11;     // Printing 5 random values // in range 2 and 11 for (let i = 0; i < 5; i++) {     console.log(_.random(lower, upper)); }
Output:
9
5
2
11
5

JavaScript-Lodash
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to get or set the selection state of JCheckBox in Java

The following is an example to get or set the selection state of JCheckBox:
import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class SwingDemo extends JFrame {
   public SwingDemo() {
      setSize(500, 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new FlowLayout(FlowLayout.CENTER));
      JCheckBox checkBox = new JCheckBox("Demo");
      checkBox.setSelected(true);
      boolean sel = checkBox.isSelected();
      if (sel)
         System.out.println("Check box selected!");
      getContentPane().add(checkBox);
   }
   public static void main(String[] args) {
      new SwingDemo().setVisible(true);
   }
}
Since the checkbox is selected by default, the following output would be visible in EclipseIDE:
Import and Merge Multiple CSV Files in R - GeeksforGeeks

17 Jun, 2021

In this article, we will be looking at the approach to merge multiple CSV files in the R programming language.
dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.
plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together.
readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’).
list.files() function: This function produces a character vector of the names of files or directories in the named directory.
Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
Syntax: lapply(X, FUN, ...)
bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one.
Syntax:
bind_rows(..., .id = NULL)
Parameter:
...: Data frames to combine.
.id: Data frame identifier.
To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language.
Data in Use:
Example:
R
 

 
 










library("dplyr")                                                 
library("plyr")                                                
library("readr")   
  
gfg_data <- list.files(path = "C:/Users/Geetansh Sahni/Documents/R/Data",  
                      pattern = "*.csv", full.names = TRUE) %>% 
 lapply(read_csv) %>%                                           
 bind_rows                                                       
  
gfg_data






 Output:

Picked


R-CSV


R Language

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
How to change Colors in ggplot2 Line Plot in R ?
How to filter R DataFrame by values in a column?
Linear Discriminant Analysis in R Programming
R - Operators
Convert a JSON object to XML format in Java?


A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert a JSONObject into an XML format using org.json.XML class, this provides static methods to convert an XML text into a JSONObject and to convert a JSONObject into an XML text. The XML.toString() method convert a JSON object into a well-formed, element-normal XML string.
public static java.lang.String toString(java.lang.Object object) throws JSONException
import java.io.*;
import org.json.*;
public class JSONtoXMLTest {
   public static void main(String[] args) throws JSONException {
      String json = "{employee : { age:30, name : Raja, technology:Java}}";
      //Convert JSON to XML
      String xml = convert(json, "root"); // This method converts json object to xml string
      System.out.println(xml);
   }
   public static String convert(String json, String root) throws JSONException {
      JSONObject jsonObject = new JSONObject(json);
      String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">" + XML.toString(jsonFileObject) + "</"+root+">";
      return xml;
   }
}
<?xml version="1.0" encoding="ISO-8859-15"?>
<root>
   <employee>
      <name>Raja</name>
      <technology>Java</technology>
      <age>30</age>
   </employee>
</root>
Magic Number | Practice | GeeksforGeeks

A magic number is defined as a number that can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), ....
Given the value of n, find the n'th Magic number modulo 109+7.
Example 1:
Input: n = 1
Output: 5
Explanation: 1'st Magic number is 5.
â€‹Example 2:
Input: n = 2
Output: 25
Explanation: 2'nd Magic number is 25. 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function nthMagicNo() which takes n input and returns the answer.

Expected Time Complexity: O(log n)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ n ≤ 105
+1
prasadkandekar5553 months ago
Ohhh....! 110037 test cases 
0
Panasa Teja10 months ago
Panasa Teja
Executed in 0.43sec https://uploads.disquscdn.c...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to change the width of whisker lines in a boxplot using ggplot2 in R?

In R, by default the whisker lines are as wide as the box of the boxplot but it would be great if we reduce that width or increase it because it will get attention of the viewer in that way. This can be done by using the width argument inside the stat_boxplot function of ggplot2 package. Check out the below example to understand how it works.
Consider the below data frame −
Live Demo
> x<-sample(LETTERS[1:2],20,replace=TRUE)
> y<-rpois(20,5)
> df<-data.frame(x,y)
> df
x y
1 B 5
2 B 4
3 A 6
4 A 9
5 B 2
6 B 4
7 B 6
8 B 2
9 B 4
10 B 8
11 B 3
12 A 7
13 B 5
14 A 7
15 A 2
16 B 7
17 B 7
18 A 2
19 B 5
20 B 5
Loading ggplot2 package and creating boxplot −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar")
Creating the boxplot with different whisker lines width −
> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar",width=0.05)
> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar",width=0.40)
How to Count the Number of Vowels in a string using Python?

Declare a string object containing all vowels.
>>> vowels='aeiou'
Set up a count variable initialize to 0
>>> count=0
Check if each character of input string belong to vowel string. If yes increment the count
>>> string='Hello How are you?'
>>> for s in string:
            if s in vowels: count=count+1
In the end display value of count
>>> count
7
Write a Regular Expression to remove all special characters from a JavaScript String?

To remove all special characters from a JavaScript string, you can try to run the following code −
<html>
   <head>
      <script>
         var str = "@!Welcome to our website$$";
         document.write(str);
         
         // Removing Special Characters
         document.write("<br>"+str.replace(/[^\w\s]/gi, ''));
      </script>
   </head>
   
   <body>
   </body>
</html>
How to use .data files from UCI. Don’t be frightened by the .data... | by Jacob Toftgaard Rasmussen | Towards Data Science

You will learn how to use the data sets from UCI that come with the .data file type in this quick article.
Kaggle.com is a great choice for finding data to use in your data science projects. The site is filled with interesting data sets, notebooks from other scientists and tutorials. All the data sets I have encountered on Kaggle have been .csv files, this is very convenient when working with pandas.
You might wonder (at least I did) if Kaggle is the only place where data can be found.
Hint: It is not!
You will also find awesome data sets on UCI Machine Learning Repository. An example of an interesting data set is the Breast Cancer Wisconsin (Original) Data Set.
I recently wanted to use this exact data set to practice my classification skills. However, I quickly ran into some trouble (or so I thought). The data I had downloaded was contained in a .data file...
How do you work with that?I certainly didn’t know.
As I have only ever worked with .csv files (I am a relatively new data scientist) all I know how to do is use the pandas read_csv() function to import my data sets into a DataFrame.
To download the data first click on the Data Folder which well take you to a second page (lower half of the following picture), here you click on the file you want to download.
The .data file can be opened with Microsoft Excel or Notepad. I tried doing the latter:
You can see that all the data points are separated with a comma!
Naturally I tried to implement the data in Google Colab. I was very curious as to whether it would work or not.
As you can see there is no problem with using read_csv() to read the data into a DataFrame.
This really shows how powerful Pandas are I think!
There is just one small thing missing I think. The column names. So lets add those.
Scroll down a bit on the page of a data set on UCI, and you will find the Attribute information. This provides the names for the features in the corresponding data set. Now we can add those to our DataFrame.
You add column names to your DataFrame with the .columns property on the DataFrame. Take a look:
Here is all the code from Google Colab if you want to try it yourself (you will have to download the data from UCI and upload it to the Colab document):
import pandas as pddataset = pd.read_csv('breast-cancer-wisconsin.data')dataset.columns = ['Id', 'Clump_thickness', 'Uniformity_cell_size', 'Uniformity_cell_shape', 'Marginal_adhesion', 'Single_e_cell_size', 'Bare_nuclei', 'Bland_chromatin', 'Normal_nucleoli', 'Mitoses', 'Class']dataset.head()
Did you know?The .data file type is actually a text file. It is used by a data mining software called analysis studio, however, the program is no longer being developed (source: Fileinfo, visited 15–08–2020).
I hope this short article was useful to you. I am happy that I now know that I can use .data files from UCI without a problem!
Keep learning! — Jacob Toftgaard Rasmussen
What are the modes a file can be opened using Python?

Files in python can be opened in the following modes.
 
These modes can be used in combinations and need to be passed as the second argument when opening a file. If you don't specify a mode, files are opened in readonly text mode.
f = open("test.txt") # Equivalent to rt or race
f = open("test.txt", 'w') # Write in text mode
f = open("test.bmp", 'r+b') # Read/write in binary mode
f = open("test.txt", 'a') # Append mode
JavaScript TypeError - Setting getter-only property "x" - GeeksforGeeks

18 Aug, 2020
This JavaScript exception setting getter-only property works in strict-mode only and occurs if the user tries to set a new value to a property for which only a getter is specified.
Message:
TypeError: Assignment to read-only properties is 
           not allowed in strict mode (Edge)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Cannot set property "prop" of #<Object> 
           which has only a getter (Chrome)


Error Type:
TypeError

Cause of the Error: The user is trying to set a new value to a property for which only a getter is defined.
Example 1: In this example, the getter method is defined for the object. Property can not be accessed directly.
HTML
<script>"use strict";function GFG_Fun() {   var temp = null;   Object.defineProperty(this, 'temp', {     get: function() {      return temp;     }  });}var obj = new GFG_Fun(); obj.temp;obj.temp = 100; // Error here</script>
Output:
TypeError: Cannot set property temp of 
#<GFG_Fun> which has only a getter

Example 2: In this example, the getter method is defined for the object ‘Person’. Property ‘Age’can not be accessed directly.
HTML
<script>"use strict";function Person(ageP) {   var age = ageP;   Object.defineProperty(this, 'age', {     get: function() {      return age;     }  });}var p = new Person(22);p.age = 30;  // TypeError</script>
Output:
TypeError: Cannot set property age of 
#<Person> which has only a getter

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to quickly swap two arrays of same size in C++? - GeeksforGeeks

28 May, 2017
Given two arrays a[] and b[] of same size, we need to swap their contents.
Example :
Input : a[] = {1, 2, 3, 4}
        b[] = {5, 6, 7, 8}
Output : a[] = {5, 6, 7, 8}
         b[] = {1, 2, 3, 4}

A simple solution is to iterate over elements of both arrays and swap them one by one.
A quick solution is to use std::swap(). It can directly swap arrays if they are of same size.
// Illustrating the use of swap function// to swap two arrays#include <iostream>#include <utility>using namespace std;  // Driver Programint main (){    int a[] = {1, 2, 3, 4};    int b[] = {5, 6, 7, 8};    int n = sizeof(a)/sizeof(a[0]);      swap(a, b);      cout << "a[] = ";    for (int i=0; i<n; i++)        cout << a[i] << ", ";      cout << "\nb[] = ";    for (int i=0; i<n; i++)        cout << b[i] << ", ";      return 0;}
Output :
a[] = 5, 6, 7, 8, 
b[] = 1, 2, 3, 4,
This article is contributed by Shambhavi Singh. 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.
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Inline Functions in C++
Exception Handling in C++
Destructors in C++
new and delete operators in C++ for dynamic memory
std::string class in C++
Sorting a vector in C++
Display hello world using React.js

create-react-app is a command to create a React.js project with default configuration. Create-react-app will help in running react applications. Command will be executed on npm or yarn
If npm and node.js is installed on computer, install create-react-app globally with command −
npm install –g create-react-app
Creation of project − to create a project once above commands are executed, run below command −
npx create-react-app hello-world-example
npx comes with npm version 5.2+ , npm version can be checked on terminal using npm –version
If npm version is 5.2+, then react.js project can be directly created with command −
npx create-react-app hello-world-example
If npm version is 6+, npm init react-app hello-world is also an option to create React.js project.
With yarn, we have command − yarn create react-app hello-world-example
Once above commands are done , change directory to hello-world-example
With create-react-app, webpack or babel required for using advanced JavaScript features are preconfigured and we can only concentrate on writing code.
cd hello-world-example
To execute the application, run the below command on terminal −
npm start
npm start runs a live development server and the code changes will automatically refresh the browser and reflect the changes.
A browser window will be opened, if not opened automatically open a browser manually and type url − localhost:3000 in the address bar. 3000 is the default port used in React application. Port number can be changed if any issue with port number.
The default text on application run is shown below −
To update open the project using any code editor tools e.g. visual studio code
Open the file App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
   return (
      <div className="App">
         <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>Edit <code>src/App.js</code> and save to reload.</p>
            <a
               className="App-link"
               href="https://reactjs.org"
               target="_blank"
               rel="noopener noreferrer">
               Learn React
            </a>
         </header>
      </div>
   );
}
export default App;
Change the content of return statement to just hello World text −
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
   return (
      <div className="App">
         Hello World !
      </div>
   );
}
export default App;
The text on the browser will be changed immediately
Create index on create table in MySQL?

Let us first create a table and index −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20),
   StudentAge int,
   StudentCountryName varchar(100),
   INDEX first_Name_index(StudentFirstName)
   );
Query OK, 0 rows affected (1.01 sec)
Check the description of the table −
mysql> desc DemoTable;
This will produce the following output −
+--------------------+--------------+------+-----+---------+----------------+
| Field              | Type         | Null | Key | Default | Extra          |
+--------------------+--------------+------+-----+---------+----------------+
| StudentId          | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentFirstName   | varchar(20)  | YES  | MUL | NULL    |                |
| StudentAge         | int(11)      | YES  |     | NULL    |                |
| StudentCountryName | varchar(100) | YES  |     | NULL    |                |
+--------------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
DATESINPERIOD function

Returns a table that contains a column of dates that begins with the start_date and continues for the specified number_of_intervals.
DATESINPERIOD (<dates>, <start_date>, <number_of_intervals>, <interval>) 

dates
A column that contains dates.
start_date
A date expression.
number_of_intervals
An integer that specifies the number of intervals to add to or subtract from the dates.
interval
The interval by which to shift the dates.
The value for interval can be one of the following −
year
quarter
month
day
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time.
The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them.
The result table includes only dates that are specified in the dates parameter.
= CALCULATE ( 
   SUM (Sales [Sales Amount]), 
   DATESINPERIOD (Sales[Date], DATE (2015,1,1),3, MONTH)
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Python | Pandas dataframe.clip()

16 Nov, 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 dataframe.clip() is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe.
Syntax: DataFrame.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs)
Parameters:lower : Minimum threshold value. All values below this threshold will be set to it.upper : Maximum threshold value. All values above this threshold will be set to it.axis : Align object with lower and upper along the given axis.inplace : Whether to perform the operation in place on the data.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.
Example #1: Use clip() function to trim values of a data frame below and above a given threshold value.
# importing pandas as pdimport pandas as pd  # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, -9, 5, 3],                   "B":[-1, -4, 6, 4, 11, 3],                   "C":[11, 4, -8, 7, 3, -2]})  # Printing the data frame for visualizationdf
Now trim all the values below -4 to -4 and all the values above 9 to 9. Values in-between -4 and 9 remaining the same.
# Clip in range (-4, 9)df.clip(-4, 9)
Output :
Notice, there is not any value in the data frame greater than 9 and smaller than -4 Example #2: Use clip() function to clips using specific lower and upper thresholds per column element in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating a dataframe using dictionary  df = pd.DataFrame({"A":[-5, 8, 12, -9, 5, 3],                   "B":[-1, -4, 6, 4, 11, 3],                   "C":[11, 4, -8, 7, 3, -2]})  # Printing the dataframedf
when axis=0, then the value will be clipped across the rows. We are going to provide upper and lower threshold for all the column element (i.e. equivalent to the no. of rows)
Creating a Series to store the lower and upper threshold value for each column element.
# lower limit for each individual column element.lower_limit = pd.Series([1, -3, 2, 3, -2, -1])  # upper limit for each individual column element.upper_limit = lower_limit + 5  # Print lower_limitlower_limit  # Print upper_limitupper_limit
Output :
Now we want to apply these limits on the dataframe.
# applying different limit value for each column elementdf.clip(lower_limit, upper_limit, axis = 0)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to create an empty DataFrame and append rows & columns to it in Pandas?

02 Jul, 2020
Let’s discuss how to create an empty DataFrame and append rows & columns to it in Pandas. There are multiple ways in which we can do this task.
Method #1: Create a complete empty DataFrame without any column name or indices and then appending columns one by one to it.
# import pandas library as pdimport pandas as pd  # create an Empty DataFrame objectdf = pd.DataFrame()  print(df)  # append columns to an empty DataFramedf['Name'] = ['Ankit', 'Ankita', 'Yashvardhan']df['Articles'] = [97, 600, 200]df['Improved'] = [2200, 75, 100]  df
Output:
Method #2: Create an empty DataFrame with columns name only then appending rows one by one to it using append() method.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
# import pandas library as pdimport pandas as pd  # create an Empty DataFrame# object With column names onlydf = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'])print(df)  # append rows to an empty DataFramedf = df.append({'Name' : 'Ankit', 'Articles' : 97, 'Improved' : 2200},                 ignore_index = True)df = df.append({'Name' : 'Aishwary', 'Articles' : 30, 'Improved' : 50},                ignore_index = True)df = df.append({'Name' : 'yash', 'Articles' : 17, 'Improved' : 220},               ignore_index = True)  df
Output:
Method #3: Create an empty DataFrame with a column name and indices and then appending rows one by one to it using loc[] method.
# import pandas library as pdimport pandas as pd  # create an Empty DataFrame object With# column names and indices df = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'],                    index = ['a', 'b', 'c'])  print("Empty DataFrame With NaN values : \n\n", df)  # adding rows to an empty # dataframe at existing indexdf.loc['a'] = ['Ankita', 50, 100]df.loc['b'] = ['Ankit', 60, 120]df.loc['c'] = ['Harsh', 30, 60]  df
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
numpy.repeat() in Python

28 Mar, 2022
The numpy.repeat() function repeats elements of the array – arr. Syntax : 
numpy.repeat(arr, repetitions, axis = None)
Parameters : 
array       : [array_like]Input array. 
repetitions : No. of repetitions of each array elements along the given axis.
axis        : Axis along which we want to repeat values. By default, it returns 
           a flat output array.
Return : 
An array with repetitions of array - arr elements as per repetitions, number of times 
we want to repeat arr  
Code 1 : 
Python
# Python Program illustrating# numpy.repeat() import numpy as geek #Working on 1Darr = geek.arange(5)print("arr : \n", arr) repetitions = 2a = geek.repeat(arr, repetitions)print("\nRepeating arr 2 times : \n", a)print("Shape : ", a.shape) repetitions = 3a = geek.repeat(arr, repetitions)print("\nRepeating arr 3 times : \n", a)# [0 0 0 ..., 4 4 4] means [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]# since it was long output, so it uses [ ... ]print("Shape : ", a.shape)
Output : 
arr : 
 [0 1 2 3 4]

Repeating arr 2 times : 
 [0 0 1 1 2 2 3 3 4 4]
Shape :  (10,)

Repeating arr 3 times : 
 [0 0 0 ..., 4 4 4]
Shape :  (15,)
Code 2 : 
Python
# Python Program illustrating# numpy.repeat() import numpy as geek arr = geek.arange(6).reshape(2, 3)print("arr : \n", arr) repetitions = 2print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 1))print("arr Shape : \n", geek.repeat(arr, repetitions).shape)  repetitions = 2print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 0))print("arr Shape : \n", geek.repeat(arr, repetitions).shape)    repetitions = 3print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 1))print("arr Shape : \n", geek.repeat(arr, repetitions).shape)
Output : 
arr : 
 [[0 1 2]
 [3 4 5]]

Repeating arr : 
 [[0 0 1 1 2 2]
 [3 3 4 4 5 5]]
arr Shape : 
 (12,)

Repeating arr : 
 [[0 1 2]
 [0 1 2]
 [3 4 5]
 [3 4 5]]
arr Shape : 
 (12,)

Repeating arr : 
 [[0 0 0 ..., 2 2 2]
 [3 3 3 ..., 5 5 5]]
arr Shape : 
 (18,)
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kothavvsaakash
Python numpy-arrayManipulation
Python-numpy
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Motherboard parts – North Bridge

27 Sep, 2021
Motherboard comprises of many parts embedded in it. In this article, a part named North Bridge is being discussed. A motherboard has a chip set logic architecture consisting of two chipsets: 
1. North Bridge
2. South Bridge 
We have explained here, only North Bridge. 
1. North Bridge : North bridge is also called as Host Bridge. The north bridge is directly connected to the Central Processing Unit(CPU) for processing tasks that need the highest performance. These chip sets act as a medium for communication between the CPU and parts of motherboard thereby, Memory Controller Hub, being the other name for North Bridge. 
History : The name North bridge was derived while designing the architecture of the chip sets. It was designed in such way that the CPU would have a easy access for connecting parts of motherboard. 
Features : 
A north bridge communicates with processor via Front Side Bus or FSB for short.
It controls the interaction with motherboard parts such as Accelerated Graphics Port (AGP), Peripheral Component Interconnect (PCI), and other crucial parts.
Advantages : 
Easy communication is being established between parts of motherboard via North Bridge.
Faster data transfer due to easy communication access.
Disadvantages There is no major disadvantages. 
sumitgumber28
sagar0719kumar
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lex Program to remove comments from C program

11 Jul, 2022
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out

Let’s see LEX program to accept string starting with vowel.Examples:
Input : 
//testing
#include 
int main()
{
 /* multiline comment
    continue....
 */
 return 0;
}

Output :
#include 
int main()
{
 
 return 0;
}


Below is the implementation:
/% Lex Program to remove comments from C program    and save it in a file %//*Definition Section*/%{%}  /*Starting character sequence for multiline comment*/start \/\*/*Ending character sequence for multiline comment*/end  \*\/  /*Rule Section*/%%  /*Regular expression for single line comment*/\/\/(.*) ;/*Regular expression for multi line comment*/ {start}.*{end} ;  %%  /*Driver function*/int main(int k,char **argcv){yyin=fopen(argcv[1],"r");yyout=fopen("out.c","w");/*call the yylex function.*/yylex();return 0;}
Output:
psil123
Lex program
C Programs
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.