title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Web Scraping Google Sheets with RSelenium | by Matt.0 | Towards Data Science
I love to learn new things and one of ways I learn best is by doing. Also it’s been said that you never fully understand a topic until you are able to explain it , I think blogging is a low barrier to explaining things. Someone I met at a local data science meetup in Montréal wanted help web scraping to get team standings from the PuzzledPint. I jumped at the opportunity because I knew this would be my opportunity to finally learn RSelenium! Static scraping ignores JavaScript. It fetches web pages from the server without the help of a browser. You get exactly what you see in “view page source”, and then you slice and dice it. If the content you’re looking for is available, you need to go no further. However, if the content is something like an `iframe`, you need dynamic scraping. Dynamic scraping uses an actual browser (or a headless browser) and lets JavaScript do its thing. Then, it queries the DOM to extract the content it’s looking for. Sometimes you need to automate the browser by simulating a user to get the content you need. In order for me to get the same details for the remaining posts, i would need to first navigate to the next page, which involves clicking the Next button at the bottom of the search results page. RSelenium provides R bindings for the Selenium Webdriver API. Selenium is a project focused on automating web browsers. You need to follow the installation instructions for Docker Toolbox on Windows or Ubuntu. Docker is used to run applications by using containers. Containers are simply a bundle of libraries and other dependencies in one package. You can think of it like a virtual machine, but rather than creating a whole OS it allows applications to use the same Linux kernel with only the things not already running on the host computer. Basically, it gives a significant performance boost and reduces the size of the application. Moreover, you can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code. You’ll also need to install TightVNC which will allow you to see how you’re manipulating the web page in real-time with RSelenium. Next follow the instructions to create a Docker container running a selenium server and its own firefox. Note: Once you’ve set up the docker container (and everytime you restart your computer or start-up fresh again) open the Docker Quickstart Terminal and run the following command. docker run -d -p 4445:4444 selenium/standalone-firefox:2.53.0 Now that you’ve booted your Docker Quickstart Terminal go into R and connect to a running server. library(RSelenium)remDr <- remoteDriver( remoteServerAddr = "192.168.99.100", port = 4445L)remDr$open() Navigate to the page using Rselenium. # navigate to the website of interestremDr$navigate("http://www.puzzledpint.com/standings/")# confirm you got thereremDr$getTitle()0 Okay let’s get a live screen shot of the site in the Viewer tab of RStudio. remDr$screenshot(display = TRUE) Keep in mind that this is just a static screen shot. Your going to want to use TightVNC to get a live view of your interactions while your developing your pipeline so you can see how your interacting with the website. It’s important to be watching TightVNC as you use the ...$highlightElement() in-between your ...$findElement() and ...$switchToFrame()/...$clickElement() commands so that you actually know your selecting the appropriate things! Open the TighVNC Viewer and enter the port number; in this case 192.168.99.100 and enter that in the Remote Host: field. Click Connect and for the password enter the word: secret. Note: If TightVNC ever stops working (on Windows 10 it did often) and gives you the Error: “NO CONNECTION COULD BE MADE BECAUSE THE TARGET MACHINE ACTIVELY REFUSED IT” then follow the steps for “Debugging Using VNC” here. Web pages are a set of nest objects (together, they are known as the Document Object Model or DOM for short). It’s a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Interacting with the DOM will be very important for us with RSelenium. Hadley Wickham recommends using Selectorgadget, a Chrome extension, to help identify the web page elements you need. And he recommends this page for learning more about selectors. For example by using SelectorGadget you can the table you’re interested in. In this case it says it’s an iframe. To isolate just the Montréal standings we’ll click another box to only select the one of interest: iframe:nth-child(68). In the context of a web browser, a frame is a part of a web page or browser window which displays content independent of its container, with the ability to load content independently. In this case the website is pulling in data from another source to display these tables interactively apart from the main standings page. Luckily for me they are all from Google Sheets so this will make it much easier for me. Unfortunately, you can’t find the links for these sheets with `selectorgadget`. You will need to take a closer look at the source code using the Developer’s Tool called `Inspector` in either Chrome of Firefox. If you have Windows and Firefox you would click Open Menu then Web Developer > Inspector or just Ctrl+Shift+c. Then I used the search box to look for the link (src=) for Montréal. For me it was a big pain to actually find what I was looking for as sometimes the highlight looks like what you want but it’s not. For example: In the end I guess to figure out HTML it involves gradual “Denial and Error” attempts. It’s worth mentioning that administrators may want to protect certain parts of their website for a number of reasons, such as “indexing of an unannounced site, traversal of parts of the site which require vast resources of the server, recursive traversal of an infinite URL space, etc.” Therefore, one should always check if they have permission. One way to do this, is to use the robotstxt package to check if your web-bot has permission to access certain parts of a web-page. # check permissionslibrary(robotstxt)paths_allowed("https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156") If it says TRUE on the specific page you have permission. Alternatively, just go to the robots.txt file on the url of the main page to get a broader sense of what is (and isn’t) allowed. Sometimes websites can be composed using frames. These are in effect seperate webpages which are brought together in a frameset. We will need to jump back-and-forth between these frames. library(RSelenium)library(XML)library(janitor)library(lubridate)library(magrittr)library(dplyr)remDr <- remoteDriver( remoteServerAddr = "192.168.99.100", port = 4445L)remDr$open()# Now open TightVNC to follow along with Selenium driving the browser. Set 192.168.99.100:5901 and password: secret# navigate to the main pageremDr$navigate("https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156")# https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=552987877# look for table elementtableElem <- remDr$findElement(using = "id", "pageswitcher-content")# switch to tableremDr$switchToFrame(tableElem)# parse htmldoc <- htmlParse(remDr$getPageSource()[[1]])table_tmp <- readHTMLTable(doc)table_tmp <- table_tmp[[1]][-2,-1]table_tmp <- table_tmp[-1,]colnames(table_tmp) <- c("team_name", "team_size", "start_time", "end_time", "total_time", "puzzels_solved")table_tmp$city <- rep("montreal", nrow(table_tmp))table_tmp$date <- rep(Sys.Date()-5, nrow(table_tmp)) Now that we have the first month we can create a for loop for the rest of the dates. First let’s switch back the outer frame and select the elements we will be manipulating. # switch back to the main/outter frameremDr$switchToFrame(NULL)# find the elements you'll manipulate with Inspector mode in a browserwebElems <- remDr$findElements(using = "css", ".switcherItem") # Month/Year tabs at the bottomarrowElems <- remDr$findElements(using = "css", ".switcherArrows") # Arrows to scroll left and right at the bottomtableElem <- remDr$findElement(using = "id", "pageswitcher-content") # The inner table frame So I know there’s going to be many tables, but just how many? We can check this use this via length(webElems). There is actually 49 tables in total but since we started on the first one above there is only 48 links. Rather than hard-coding 1:48 it’s better to do it via code as there will be more tables added in the future. # Create NULL object to be used in forloopbig_df <- NULLfor (i in seq(length(webElems))){ # for every check <- try(expression, silent = TRUE) # or suppressMessages(try(expression, silent = TRUE))if (any(class(check) == "try-error")) { # choose the i'th Month/Year tab webElem <- webElems[[i]] webElem$clickElement()# Find the tableElem again other wise you get a StaleElementReference ## TO DO: look into WebDriverWait: https://stackoverflow.com/questions/5709204/random-element-is-no-longer-attached-to-the-dom-staleelementreferenceexception tableElem <- remDr$findElement(using = "id", "pageswitcher-content") # The inner table frame# switch to table frameremDr$switchToFrame(tableElem)Sys.sleep(3)# parse html with XML packagedoc <- htmlParse(remDr$getPageSource()[[1]])Sys.sleep(3)# Extract data from HTML table in HTML doucmenttable_tmp <- readHTMLTable(doc)Sys.sleep(3)# put this into a format you can usetable <- table_tmp[[1]][-2,-1]table <- table[-1,]# rename the columnscolnames(table) <- c("team_name", "team_size", "start_time", "end_time", "total_time", "puzzels_solved")# add city name to a columntable$city <- rep("Montreal", nrow(table))# add the Month/Year this table was extracted fromtoday <- Sys.Date() %m-% months(i + 1)table$date <- today# concatenate each table togetherbig_df <- dplyr::bind_rows(big_df, table)# Switch back to the main frameremDr$switchToFrame(NULL)arrowElem <- arrowElems[[1]]# once you "click"" the element it is "held down" as far as I know there is no way to " unclick"# to prevent it from scrolling too far I make sure not to take too long by setting the sleep shortarrowElem$clickElement()# give it "just enough time" to scroll rightSys.sleep(0.3)# switch back to outer frame to re-start the loopremDr$switchToFrame(NULL) }}temp1 <- dplyr::bind_rows(table_tmp, big_df) The problem here is that the for loop eventually fails at the end when it tries to click the right arrow but it’s as far to the right as it can go — therefore it won’t download the last few tables (~5). Typically one would handle such conditions with something like: check <- try(expression, silent = TRUE) # or suppressMessages(try(expression, silent = TRUE))if (any(class(check) == "try-error")) { # do stuff} and it usually works fine, including when using selenium. The issue encountered here however is clicking on the arrow once would always bring me to the last visible sheets — skipping everything in middle. Therefore my work around to get the remaining sheets was this: # ctrl+x from the google sheet then use the read.delim() to assign it to an objectmarch <- read.delim("clipboard")february <- read.delim("clipboard")january <- read.delim("clipboard")december <- read.delim("clipboard")november <- read.delim("clipboard")# add the city and datejanuary$city <- rep("montreal", nrow(january))january$date <- rep("2015-01-30", nrow(january))february$city <- rep("montreal", nrow(february))february$date <- rep("2015-02-15", nrow(february))march$city <- rep("montreal", nrow(march))march$date <- rep("2015-03-15", nrow(march))december$city <- rep("montreal", nrow(december))december$date <- rep("2014-12-15", nrow(december))november$city <- rep("montreal", nrow(november))november$date <- rep("2014-11-15", nrow(november))# clean up the column namesjanuary %<>% janitor::clean_names()february %<>% janitor::clean_names()march %<>% janitor::clean_names()december %<>% janitor::clean_names()november %<>% janitor::clean_names()# concatenate these five dataframes togetherxyz <- bind_rows(march, february, january, december, november)# convert characters into actual datesxyz$date <-as.Date(xyz$date)# reorder the columnsxyz %<>% dplyr::select(team_name, team_size, start_time, end_time, total_time, puzzles, city, date)# rename this column to match temp1xyz <- rename(xyz, puzzels_solved = puzzles)# change to a characterxyz$puzzels_solved <- as.character(xyz$puzzels_solved)# add NA for team sizexyz$team_size <- rep(NA, nrow(xyz))# concatenate this onto the larger dataframetemp2 <- bind_rows(temp1, xyz)# save the objectwrite_csv(temp2, "puzzeld_pint_raw.csv") Big thanks to Nate on SO for pointing out an alternative solution that solves the task of scrapping the tables but not the task of exception handling in the above sense. remDr <- RSelenium::remoteDriver( remoteServerAddr = "192.168.99.100", port = 4445L)remDr$open(silent = TRUE)# navigate to the main page# needs no be done once before looping, else content is not availableremDr$navigate("https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156")# I. Preliminaries:# # 1. build the links to all spreadsheets# 2. define the function create_table# # 1.# get page sourcehtml <- remDr$getPageSource()[[1]]# split it line by linehtml <- unlist(strsplit(html, '\n'))# restrict to script sectionscript <- grep('^\\s*var\\s+gidMatch', html, value = TRUE)# split the script by semi-colonscript <- unlist(strsplit(script, ';'))# retrieve informationsheet_months <- gsub('.*name:.{2}(.*?).{1},.*', '\\1', grep('\\{name\\s*\\:', script, value = TRUE), perl = TRUE)sheet_gid <- gsub('.*gid:.{2}(.*?).{1},.*', '\\1', grep('\\gid\\s*\\:', script, value = TRUE), perl = TRUE)sheet_url <- paste0('https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pubhtml/sheet?headers%5Cx3dfalse&gid=', sheet_gid)# 2.# table yielding function# just for readability in the loopcreate_table <- function (remDr) { # parse html with XML package doc <- XML::htmlParse(remDr$getPageSource()[[1]]) Sys.sleep(3) # Extract data from HTML table in HTML document table_tmp <- XML::readHTMLTable(doc) Sys.sleep(3) # put this into a format you can use table <- table_tmp[[1]][-2, -1] # add a check-up for size mismatch table_fields <- as.character(t(table[1,])) if (! any(grepl("size", tolower(table_fields)))) { table <- table[-1, ] # rename the columns colnames(table) <- c("team_name", "start_time", "end_time", "total_time", "puzzels_solved") table$team_size <- NA_integer_ table <- table[,c("team_name", "team_size", "start_time", "end_time", "total_time", "puzzels_solved")] } else { table <- table[-1, ] # rename the columns colnames(table) <- c("team_name", "team_size", "start_time", "end_time", "total_time", "puzzels_solved") } # add city name to a column table$city <- rep("Montreal", nrow(table)) # add the Month/Year this table was extracted from today <- Sys.Date() lubridate::month(today) <- lubridate::month(today)+1 table$date <- today # returns the table table}# II. Scrapping the content# # 1. selenium to generate the pages# 2. use create_table to extract the table# big_df <- NULLfor (k in seq_along(sheet_url)) { # 1. navigate to the page remDr$navigate(sheet_url[k]) # remDr$screenshot(display = TRUE) maybe one wants to see progress table <- create_table(remDr) # 2. concatenate each table together big_df <- dplyr::bind_rows(big_df, table) # inform progress cat(paste0('\nGathered table for: \t', sheet_months[k]))}# close sessionremDr$close() To perform the task, what was done was firstly generating the links to all spreadsheets in the document. To do this: Navigate once to the document Extract source code Extract the sheet months and URLs (via gid digit) using regex Once this is done, loop through the Urls, gather and bind the tables There is a small function called create_table which returns the final table in the proper format with a safety measure for the number of columns (some of the spreadsheets do not have the team_size field - in those cases I set it to NA_integer). If you find this article useful feel free to share it with others or recommend this article! 😃 As always, if you have any questions or comments feel free to leave your feedback below or you can always reach me on LinkedIn. Till then, see you in the next post! 😄
[ { "code": null, "e": 392, "s": 172, "text": "I love to learn new things and one of ways I learn best is by doing. Also it’s been said that you never fully understand a topic until you are able to explain it , I think blogging is a low barrier to explaining things." }, { "code": null, "e": 619, "s": 392, "text": "Someone I met at a local data science meetup in Montréal wanted help web scraping to get team standings from the PuzzledPint. I jumped at the opportunity because I knew this would be my opportunity to finally learn RSelenium!" }, { "code": null, "e": 964, "s": 619, "text": "Static scraping ignores JavaScript. It fetches web pages from the server without the help of a browser. You get exactly what you see in “view page source”, and then you slice and dice it. If the content you’re looking for is available, you need to go no further. However, if the content is something like an `iframe`, you need dynamic scraping." }, { "code": null, "e": 1417, "s": 964, "text": "Dynamic scraping uses an actual browser (or a headless browser) and lets JavaScript do its thing. Then, it queries the DOM to extract the content it’s looking for. Sometimes you need to automate the browser by simulating a user to get the content you need. In order for me to get the same details for the remaining posts, i would need to first navigate to the next page, which involves clicking the Next button at the bottom of the search results page." }, { "code": null, "e": 1537, "s": 1417, "text": "RSelenium provides R bindings for the Selenium Webdriver API. Selenium is a project focused on automating web browsers." }, { "code": null, "e": 1627, "s": 1537, "text": "You need to follow the installation instructions for Docker Toolbox on Windows or Ubuntu." }, { "code": null, "e": 2278, "s": 1627, "text": "Docker is used to run applications by using containers. Containers are simply a bundle of libraries and other dependencies in one package. You can think of it like a virtual machine, but rather than creating a whole OS it allows applications to use the same Linux kernel with only the things not already running on the host computer. Basically, it gives a significant performance boost and reduces the size of the application. Moreover, you can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code." }, { "code": null, "e": 2409, "s": 2278, "text": "You’ll also need to install TightVNC which will allow you to see how you’re manipulating the web page in real-time with RSelenium." }, { "code": null, "e": 2514, "s": 2409, "text": "Next follow the instructions to create a Docker container running a selenium server and its own firefox." }, { "code": null, "e": 2693, "s": 2514, "text": "Note: Once you’ve set up the docker container (and everytime you restart your computer or start-up fresh again) open the Docker Quickstart Terminal and run the following command." }, { "code": null, "e": 2755, "s": 2693, "text": "docker run -d -p 4445:4444 selenium/standalone-firefox:2.53.0" }, { "code": null, "e": 2853, "s": 2755, "text": "Now that you’ve booted your Docker Quickstart Terminal go into R and connect to a running server." }, { "code": null, "e": 2959, "s": 2853, "text": "library(RSelenium)remDr <- remoteDriver( remoteServerAddr = \"192.168.99.100\", port = 4445L)remDr$open()" }, { "code": null, "e": 2997, "s": 2959, "text": "Navigate to the page using Rselenium." }, { "code": null, "e": 3130, "s": 2997, "text": "# navigate to the website of interestremDr$navigate(\"http://www.puzzledpint.com/standings/\")# confirm you got thereremDr$getTitle()0" }, { "code": null, "e": 3206, "s": 3130, "text": "Okay let’s get a live screen shot of the site in the Viewer tab of RStudio." }, { "code": null, "e": 3239, "s": 3206, "text": "remDr$screenshot(display = TRUE)" }, { "code": null, "e": 3457, "s": 3239, "text": "Keep in mind that this is just a static screen shot. Your going to want to use TightVNC to get a live view of your interactions while your developing your pipeline so you can see how your interacting with the website." }, { "code": null, "e": 3685, "s": 3457, "text": "It’s important to be watching TightVNC as you use the ...$highlightElement() in-between your ...$findElement() and ...$switchToFrame()/...$clickElement() commands so that you actually know your selecting the appropriate things!" }, { "code": null, "e": 3865, "s": 3685, "text": "Open the TighVNC Viewer and enter the port number; in this case 192.168.99.100 and enter that in the Remote Host: field. Click Connect and for the password enter the word: secret." }, { "code": null, "e": 4087, "s": 3865, "text": "Note: If TightVNC ever stops working (on Windows 10 it did often) and gives you the Error: “NO CONNECTION COULD BE MADE BECAUSE THE TARGET MACHINE ACTIVELY REFUSED IT” then follow the steps for “Debugging Using VNC” here." }, { "code": null, "e": 4406, "s": 4087, "text": "Web pages are a set of nest objects (together, they are known as the Document Object Model or DOM for short). It’s a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Interacting with the DOM will be very important for us with RSelenium." }, { "code": null, "e": 4586, "s": 4406, "text": "Hadley Wickham recommends using Selectorgadget, a Chrome extension, to help identify the web page elements you need. And he recommends this page for learning more about selectors." }, { "code": null, "e": 4821, "s": 4586, "text": "For example by using SelectorGadget you can the table you’re interested in. In this case it says it’s an iframe. To isolate just the Montréal standings we’ll click another box to only select the one of interest: iframe:nth-child(68)." }, { "code": null, "e": 5622, "s": 4821, "text": "In the context of a web browser, a frame is a part of a web page or browser window which displays content independent of its container, with the ability to load content independently. In this case the website is pulling in data from another source to display these tables interactively apart from the main standings page. Luckily for me they are all from Google Sheets so this will make it much easier for me. Unfortunately, you can’t find the links for these sheets with `selectorgadget`. You will need to take a closer look at the source code using the Developer’s Tool called `Inspector` in either Chrome of Firefox. If you have Windows and Firefox you would click Open Menu then Web Developer > Inspector or just Ctrl+Shift+c. Then I used the search box to look for the link (src=) for Montréal." }, { "code": null, "e": 5766, "s": 5622, "text": "For me it was a big pain to actually find what I was looking for as sometimes the highlight looks like what you want but it’s not. For example:" }, { "code": null, "e": 5853, "s": 5766, "text": "In the end I guess to figure out HTML it involves gradual “Denial and Error” attempts." }, { "code": null, "e": 6140, "s": 5853, "text": "It’s worth mentioning that administrators may want to protect certain parts of their website for a number of reasons, such as “indexing of an unannounced site, traversal of parts of the site which require vast resources of the server, recursive traversal of an infinite URL space, etc.”" }, { "code": null, "e": 6331, "s": 6140, "text": "Therefore, one should always check if they have permission. One way to do this, is to use the robotstxt package to check if your web-bot has permission to access certain parts of a web-page." }, { "code": null, "e": 6511, "s": 6331, "text": "# check permissionslibrary(robotstxt)paths_allowed(\"https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156\")" }, { "code": null, "e": 6698, "s": 6511, "text": "If it says TRUE on the specific page you have permission. Alternatively, just go to the robots.txt file on the url of the main page to get a broader sense of what is (and isn’t) allowed." }, { "code": null, "e": 6885, "s": 6698, "text": "Sometimes websites can be composed using frames. These are in effect seperate webpages which are brought together in a frameset. We will need to jump back-and-forth between these frames." }, { "code": null, "e": 7977, "s": 6885, "text": "library(RSelenium)library(XML)library(janitor)library(lubridate)library(magrittr)library(dplyr)remDr <- remoteDriver( remoteServerAddr = \"192.168.99.100\", port = 4445L)remDr$open()# Now open TightVNC to follow along with Selenium driving the browser. Set 192.168.99.100:5901 and password: secret# navigate to the main pageremDr$navigate(\"https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156\")# https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=552987877# look for table elementtableElem <- remDr$findElement(using = \"id\", \"pageswitcher-content\")# switch to tableremDr$switchToFrame(tableElem)# parse htmldoc <- htmlParse(remDr$getPageSource()[[1]])table_tmp <- readHTMLTable(doc)table_tmp <- table_tmp[[1]][-2,-1]table_tmp <- table_tmp[-1,]colnames(table_tmp) <- c(\"team_name\", \"team_size\", \"start_time\", \"end_time\", \"total_time\", \"puzzels_solved\")table_tmp$city <- rep(\"montreal\", nrow(table_tmp))table_tmp$date <- rep(Sys.Date()-5, nrow(table_tmp))" }, { "code": null, "e": 8151, "s": 7977, "text": "Now that we have the first month we can create a for loop for the rest of the dates. First let’s switch back the outer frame and select the elements we will be manipulating." }, { "code": null, "e": 8585, "s": 8151, "text": "# switch back to the main/outter frameremDr$switchToFrame(NULL)# find the elements you'll manipulate with Inspector mode in a browserwebElems <- remDr$findElements(using = \"css\", \".switcherItem\") # Month/Year tabs at the bottomarrowElems <- remDr$findElements(using = \"css\", \".switcherArrows\") # Arrows to scroll left and right at the bottomtableElem <- remDr$findElement(using = \"id\", \"pageswitcher-content\") # The inner table frame" }, { "code": null, "e": 8696, "s": 8585, "text": "So I know there’s going to be many tables, but just how many? We can check this use this via length(webElems)." }, { "code": null, "e": 8910, "s": 8696, "text": "There is actually 49 tables in total but since we started on the first one above there is only 48 links. Rather than hard-coding 1:48 it’s better to do it via code as there will be more tables added in the future." }, { "code": null, "e": 10755, "s": 8910, "text": "# Create NULL object to be used in forloopbig_df <- NULLfor (i in seq(length(webElems))){ # for every check <- try(expression, silent = TRUE) # or suppressMessages(try(expression, silent = TRUE))if (any(class(check) == \"try-error\")) { # choose the i'th Month/Year tab webElem <- webElems[[i]] webElem$clickElement()# Find the tableElem again other wise you get a StaleElementReference ## TO DO: look into WebDriverWait: https://stackoverflow.com/questions/5709204/random-element-is-no-longer-attached-to-the-dom-staleelementreferenceexception tableElem <- remDr$findElement(using = \"id\", \"pageswitcher-content\") # The inner table frame# switch to table frameremDr$switchToFrame(tableElem)Sys.sleep(3)# parse html with XML packagedoc <- htmlParse(remDr$getPageSource()[[1]])Sys.sleep(3)# Extract data from HTML table in HTML doucmenttable_tmp <- readHTMLTable(doc)Sys.sleep(3)# put this into a format you can usetable <- table_tmp[[1]][-2,-1]table <- table[-1,]# rename the columnscolnames(table) <- c(\"team_name\", \"team_size\", \"start_time\", \"end_time\", \"total_time\", \"puzzels_solved\")# add city name to a columntable$city <- rep(\"Montreal\", nrow(table))# add the Month/Year this table was extracted fromtoday <- Sys.Date() %m-% months(i + 1)table$date <- today# concatenate each table togetherbig_df <- dplyr::bind_rows(big_df, table)# Switch back to the main frameremDr$switchToFrame(NULL)arrowElem <- arrowElems[[1]]# once you \"click\"\" the element it is \"held down\" as far as I know there is no way to \" unclick\"# to prevent it from scrolling too far I make sure not to take too long by setting the sleep shortarrowElem$clickElement()# give it \"just enough time\" to scroll rightSys.sleep(0.3)# switch back to outer frame to re-start the loopremDr$switchToFrame(NULL) }}temp1 <- dplyr::bind_rows(table_tmp, big_df)" }, { "code": null, "e": 11022, "s": 10755, "text": "The problem here is that the for loop eventually fails at the end when it tries to click the right arrow but it’s as far to the right as it can go — therefore it won’t download the last few tables (~5). Typically one would handle such conditions with something like:" }, { "code": null, "e": 11168, "s": 11022, "text": "check <- try(expression, silent = TRUE) # or suppressMessages(try(expression, silent = TRUE))if (any(class(check) == \"try-error\")) { # do stuff}" }, { "code": null, "e": 11436, "s": 11168, "text": "and it usually works fine, including when using selenium. The issue encountered here however is clicking on the arrow once would always bring me to the last visible sheets — skipping everything in middle. Therefore my work around to get the remaining sheets was this:" }, { "code": null, "e": 13026, "s": 11436, "text": "# ctrl+x from the google sheet then use the read.delim() to assign it to an objectmarch <- read.delim(\"clipboard\")february <- read.delim(\"clipboard\")january <- read.delim(\"clipboard\")december <- read.delim(\"clipboard\")november <- read.delim(\"clipboard\")# add the city and datejanuary$city <- rep(\"montreal\", nrow(january))january$date <- rep(\"2015-01-30\", nrow(january))february$city <- rep(\"montreal\", nrow(february))february$date <- rep(\"2015-02-15\", nrow(february))march$city <- rep(\"montreal\", nrow(march))march$date <- rep(\"2015-03-15\", nrow(march))december$city <- rep(\"montreal\", nrow(december))december$date <- rep(\"2014-12-15\", nrow(december))november$city <- rep(\"montreal\", nrow(november))november$date <- rep(\"2014-11-15\", nrow(november))# clean up the column namesjanuary %<>% janitor::clean_names()february %<>% janitor::clean_names()march %<>% janitor::clean_names()december %<>% janitor::clean_names()november %<>% janitor::clean_names()# concatenate these five dataframes togetherxyz <- bind_rows(march, february, january, december, november)# convert characters into actual datesxyz$date <-as.Date(xyz$date)# reorder the columnsxyz %<>% dplyr::select(team_name, team_size, start_time, end_time, total_time, puzzles, city, date)# rename this column to match temp1xyz <- rename(xyz, puzzels_solved = puzzles)# change to a characterxyz$puzzels_solved <- as.character(xyz$puzzels_solved)# add NA for team sizexyz$team_size <- rep(NA, nrow(xyz))# concatenate this onto the larger dataframetemp2 <- bind_rows(temp1, xyz)# save the objectwrite_csv(temp2, \"puzzeld_pint_raw.csv\")" }, { "code": null, "e": 13196, "s": 13026, "text": "Big thanks to Nate on SO for pointing out an alternative solution that solves the task of scrapping the tables but not the task of exception handling in the above sense." }, { "code": null, "e": 16070, "s": 13196, "text": "remDr <- RSelenium::remoteDriver( remoteServerAddr = \"192.168.99.100\", port = 4445L)remDr$open(silent = TRUE)# navigate to the main page# needs no be done once before looping, else content is not availableremDr$navigate(\"https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pub?output=html&widget=true#gid=690408156\")# I. Preliminaries:# # 1. build the links to all spreadsheets# 2. define the function create_table# # 1.# get page sourcehtml <- remDr$getPageSource()[[1]]# split it line by linehtml <- unlist(strsplit(html, '\\n'))# restrict to script sectionscript <- grep('^\\\\s*var\\\\s+gidMatch', html, value = TRUE)# split the script by semi-colonscript <- unlist(strsplit(script, ';'))# retrieve informationsheet_months <- gsub('.*name:.{2}(.*?).{1},.*', '\\\\1', grep('\\\\{name\\\\s*\\\\:', script, value = TRUE), perl = TRUE)sheet_gid <- gsub('.*gid:.{2}(.*?).{1},.*', '\\\\1', grep('\\\\gid\\\\s*\\\\:', script, value = TRUE), perl = TRUE)sheet_url <- paste0('https://docs.google.com/spreadsheets/d/1o1PlLIQS8v-XSuEz1eqZB80kcJk9xg5lsbueB7mTg1U/pubhtml/sheet?headers%5Cx3dfalse&gid=', sheet_gid)# 2.# table yielding function# just for readability in the loopcreate_table <- function (remDr) { # parse html with XML package doc <- XML::htmlParse(remDr$getPageSource()[[1]]) Sys.sleep(3) # Extract data from HTML table in HTML document table_tmp <- XML::readHTMLTable(doc) Sys.sleep(3) # put this into a format you can use table <- table_tmp[[1]][-2, -1] # add a check-up for size mismatch table_fields <- as.character(t(table[1,])) if (! any(grepl(\"size\", tolower(table_fields)))) { table <- table[-1, ] # rename the columns colnames(table) <- c(\"team_name\", \"start_time\", \"end_time\", \"total_time\", \"puzzels_solved\") table$team_size <- NA_integer_ table <- table[,c(\"team_name\", \"team_size\", \"start_time\", \"end_time\", \"total_time\", \"puzzels_solved\")] } else { table <- table[-1, ] # rename the columns colnames(table) <- c(\"team_name\", \"team_size\", \"start_time\", \"end_time\", \"total_time\", \"puzzels_solved\") } # add city name to a column table$city <- rep(\"Montreal\", nrow(table)) # add the Month/Year this table was extracted from today <- Sys.Date() lubridate::month(today) <- lubridate::month(today)+1 table$date <- today # returns the table table}# II. Scrapping the content# # 1. selenium to generate the pages# 2. use create_table to extract the table# big_df <- NULLfor (k in seq_along(sheet_url)) { # 1. navigate to the page remDr$navigate(sheet_url[k]) # remDr$screenshot(display = TRUE) maybe one wants to see progress table <- create_table(remDr) # 2. concatenate each table together big_df <- dplyr::bind_rows(big_df, table) # inform progress cat(paste0('\\nGathered table for: \\t', sheet_months[k]))}# close sessionremDr$close()" }, { "code": null, "e": 16187, "s": 16070, "text": "To perform the task, what was done was firstly generating the links to all spreadsheets in the document. To do this:" }, { "code": null, "e": 16217, "s": 16187, "text": "Navigate once to the document" }, { "code": null, "e": 16237, "s": 16217, "text": "Extract source code" }, { "code": null, "e": 16299, "s": 16237, "text": "Extract the sheet months and URLs (via gid digit) using regex" }, { "code": null, "e": 16368, "s": 16299, "text": "Once this is done, loop through the Urls, gather and bind the tables" }, { "code": null, "e": 16613, "s": 16368, "text": "There is a small function called create_table which returns the final table in the proper format with a safety measure for the number of columns (some of the spreadsheets do not have the team_size field - in those cases I set it to NA_integer)." }, { "code": null, "e": 16708, "s": 16613, "text": "If you find this article useful feel free to share it with others or recommend this article! 😃" } ]
Types of pragma directives in C - GeeksforGeeks
04 Apr, 2021 Pragma Directives: The pragma directive is used to control the actions of the compiler in a particular portion of a program without affecting the program as a whole. Pragma directives are included in the C program to take effect. The effect of pragma will be applied from the point where it is included to the end of the compilation unit or until another pragma changes its status. A #pragma directive is an instruction to the compiler and is usually ignored during preprocessing. Syntax: #pragma string Here, the string can be one of the instructions given to the compiler with any required parameters. Types of Pragma Directives: The syntax of pragma copyright is: #pragma copyright “string” Here, the string specifies the set of characters included in the copyright message in the object file. If no data is specified during pragma copyright then the current year is used in the copyright message: Example: If copy write is written in a below way: #pragma copyright “GFG Private Limited” Then the following string is placed in the object code (assuming the current year is 2020): © Copyright GFG private limited, 2020.All rights reserved. No part of this program may be copied, reproduced, or transmitted without the prior written consent of GFG Private Limited. Note: To see the COPYRIGHT string as well as any other strings in the object file, use the strings(1) command with the -a option. Example: strings -a ObjectFileName.o The syntax of pragma copyrighted is: #pragma COPYRIGHT_DATE “string” Here, the string is a date that will be used by the COPYRIGHT pragma. Consider the following example given below: #pragma COPYRIGHT_DATE “2011-2020” #pragma copyright “GFG Private Limited” The above pragma will place the following string in the object code: © Copyright GFG Private Limited, 2011-2020.All right reserved no part of this program may be photocopied reproduced, or transmitted without the prior written consent of GFG private limited. Note: To see the COPYRIGHT_DATE string as well as any other strings in the object file, use the strings(1) command with the -a option.Example: strings -a ObjectFileName.o The syntax of pragma OPT_LEVEL which is used to set the optimization level to 1, 2, 3 or 4 is: # pragma OPT_LEVEL 1# pragma OPT_LEVEL 2# pragma OPT_LEVEL 3# pragma OPT_LEVEL 4 Like the optimization pragma, even the pragma cannot be used in a function. Finally, OPT_LEVEL 3 and 4 are allowed only at the beginning of the file. Below is an example code snippet in C illustrating the use of pragma opt level: C aCC - O prog.C #pragma OPT_LEVEL 1 // Optimise func1() at level 1 void Func1() { } #pragma OPT_LEVEL 2 // Optimize Func2() to at level 2 void Func2() { } The syntax of using the pragma OPTIMIZE is: #pragma OPTIMIZE ON#pragma OPTIMIZE OFF The pragma optimize is basically used to turn ON/OFF optimization in the section of the source program. However, when using the pragma specifies one of the optimization options on the ACC command (while giving the command to compile the program), otherwise, this pragma is ignored. Also, remember that the pragma optimize cannot be used within a function. Below is an example code snippet in C illustrating the use of optimization pragma: C++ // Set optimization to level 2 // for Prog.C aCC + O2 Prog.C #pragma OPTIMISE OFF void Func1 { // Turn off optimization for // this function } #pragma OPTIMISE ON Void Func2() { // Restore optimization to level 2 } The syntax for HP_SHLIB_VERSION which is used to create different versions of shared library routine is: #pragma HP_SHLIB_VERSION [“]date[“] Example: #pragma HP_SHLIB_VERSION [“]12/20[“] Here, the data argument is of the form month/year, optionally enclosed in quotes. The month must be specified using any number from 1 to 12. The year can be specified as either the last two digits of the year (11 for 2011) or a full year specification (2011). Here are the two-digit real codes from 11 to 20 are used to represent the year from 2011 to 2020, respectively. The pragma should be used only if incompatible changes are made to a source file. The syntax of pragma locality which is used to specify the name to be associated with the code that is written to a relocatable object module is: #pragma LOCALITY “string” Example: #pragma LOCALITY “Geeks For Geeks” In the above example, the string (“Geeks For Geeks”) specifies a name to be used for a coded subspace. After this directive, all code following the directive is associated with the name specified in the string. The smallest scope of a unique LOCALITY pragma is a function. The syntax of pragma VERSION ID can be given as: #pragma VERSIONID “string” Here string is a string of characters that is placed in the object file. Example: #pragma VERSIONID “GFG private limited, Version 1234 5.8.0 1.10” In the above example, the pragma places the character geeks for GFG private limited, Version 1234 5.8.0 1.10 into the object file. The pragma once specifies that the file in which this pragma directory is specified will be included opened only once by the compiler in a building of a particular file it’s syntax can be given as: #pragma once Conclusion: The pragma preprocessor directive is mainly used where each implementation of C supports some features unique to its host machine or operating system. For example, some programs may need to exercise precise control over the memory areas where data is placed or to control the way certain function receives parameters in such cases, #pragma directives provides operating-system-specific features feature for each compiler while retaining overall compatibility with the C language. C Macro C-Macro & Preprocessor Macro & Preprocessor C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File Basics of File Handling in C
[ { "code": null, "e": 25639, "s": 25608, "text": " \n04 Apr, 2021\n" }, { "code": null, "e": 25806, "s": 25639, "text": "Pragma Directives: The pragma directive is used to control the actions of the compiler in a particular portion of a program without affecting the program as a whole. " }, { "code": null, "e": 25870, "s": 25806, "text": "Pragma directives are included in the C program to take effect." }, { "code": null, "e": 26022, "s": 25870, "text": "The effect of pragma will be applied from the point where it is included to the end of the compilation unit or until another pragma changes its status." }, { "code": null, "e": 26121, "s": 26022, "text": "A #pragma directive is an instruction to the compiler and is usually ignored during preprocessing." }, { "code": null, "e": 26129, "s": 26121, "text": "Syntax:" }, { "code": null, "e": 26144, "s": 26129, "text": "#pragma string" }, { "code": null, "e": 26253, "s": 26144, "text": "Here, the string can be one of the instructions given to the compiler with any required parameters. " }, { "code": null, "e": 26281, "s": 26253, "text": "Types of Pragma Directives:" }, { "code": null, "e": 26316, "s": 26281, "text": "The syntax of pragma copyright is:" }, { "code": null, "e": 26343, "s": 26316, "text": "#pragma copyright “string”" }, { "code": null, "e": 26446, "s": 26343, "text": "Here, the string specifies the set of characters included in the copyright message in the object file." }, { "code": null, "e": 26550, "s": 26446, "text": "If no data is specified during pragma copyright then the current year is used in the copyright message:" }, { "code": null, "e": 26600, "s": 26550, "text": "Example: If copy write is written in a below way:" }, { "code": null, "e": 26640, "s": 26600, "text": "#pragma copyright “GFG Private Limited”" }, { "code": null, "e": 26732, "s": 26640, "text": "Then the following string is placed in the object code (assuming the current year is 2020):" }, { "code": null, "e": 26915, "s": 26732, "text": "© Copyright GFG private limited, 2020.All rights reserved. No part of this program may be copied, reproduced, or transmitted without the prior written consent of GFG Private Limited." }, { "code": null, "e": 27045, "s": 26915, "text": "Note: To see the COPYRIGHT string as well as any other strings in the object file, use the strings(1) command with the -a option." }, { "code": null, "e": 27054, "s": 27045, "text": "Example:" }, { "code": null, "e": 27082, "s": 27054, "text": "strings -a ObjectFileName.o" }, { "code": null, "e": 27119, "s": 27082, "text": "The syntax of pragma copyrighted is:" }, { "code": null, "e": 27151, "s": 27119, "text": "#pragma COPYRIGHT_DATE “string”" }, { "code": null, "e": 27267, "s": 27151, "text": "Here, the string is a date that will be used by the COPYRIGHT pragma. Consider the following example given below: " }, { "code": null, "e": 27342, "s": 27267, "text": "#pragma COPYRIGHT_DATE “2011-2020” #pragma copyright “GFG Private Limited”" }, { "code": null, "e": 27411, "s": 27342, "text": "The above pragma will place the following string in the object code:" }, { "code": null, "e": 27601, "s": 27411, "text": "© Copyright GFG Private Limited, 2011-2020.All right reserved no part of this program may be photocopied reproduced, or transmitted without the prior written consent of GFG private limited." }, { "code": null, "e": 27744, "s": 27601, "text": "Note: To see the COPYRIGHT_DATE string as well as any other strings in the object file, use the strings(1) command with the -a option.Example:" }, { "code": null, "e": 27772, "s": 27744, "text": "strings -a ObjectFileName.o" }, { "code": null, "e": 27867, "s": 27772, "text": "The syntax of pragma OPT_LEVEL which is used to set the optimization level to 1, 2, 3 or 4 is:" }, { "code": null, "e": 27948, "s": 27867, "text": "# pragma OPT_LEVEL 1# pragma OPT_LEVEL 2# pragma OPT_LEVEL 3# pragma OPT_LEVEL 4" }, { "code": null, "e": 28098, "s": 27948, "text": "Like the optimization pragma, even the pragma cannot be used in a function. Finally, OPT_LEVEL 3 and 4 are allowed only at the beginning of the file." }, { "code": null, "e": 28178, "s": 28098, "text": "Below is an example code snippet in C illustrating the use of pragma opt level:" }, { "code": null, "e": 28180, "s": 28178, "text": "C" }, { "code": "\n\n\n\n\n\n\naCC - O prog.C \n \n#pragma OPT_LEVEL 1 \n \n // Optimise func1() at level 1 \n void\n Func1() \n{ \n} \n \n#pragma OPT_LEVEL 2 \n \n// Optimize Func2() to at level 2 \nvoid Func2() \n{ \n}\n\n\n\n\n\n", "e": 28397, "s": 28190, "text": null }, { "code": null, "e": 28441, "s": 28397, "text": "The syntax of using the pragma OPTIMIZE is:" }, { "code": null, "e": 28481, "s": 28441, "text": "#pragma OPTIMIZE ON#pragma OPTIMIZE OFF" }, { "code": null, "e": 28585, "s": 28481, "text": "The pragma optimize is basically used to turn ON/OFF optimization in the section of the source program." }, { "code": null, "e": 28763, "s": 28585, "text": "However, when using the pragma specifies one of the optimization options on the ACC command (while giving the command to compile the program), otherwise, this pragma is ignored." }, { "code": null, "e": 28837, "s": 28763, "text": "Also, remember that the pragma optimize cannot be used within a function." }, { "code": null, "e": 28920, "s": 28837, "text": "Below is an example code snippet in C illustrating the use of optimization pragma:" }, { "code": null, "e": 28924, "s": 28920, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// Set optimization to level 2 \n// for Prog.C \naCC + O2 Prog.C \n \n#pragma OPTIMISE OFF \n void Func1 \n{ \n // Turn off optimization for \n // this function \n} \n \n#pragma OPTIMISE ON \nVoid Func2() \n{ \n // Restore optimization to level 2 \n}\n\n\n\n\n\n", "e": 29199, "s": 28934, "text": null }, { "code": null, "e": 29304, "s": 29199, "text": "The syntax for HP_SHLIB_VERSION which is used to create different versions of shared library routine is:" }, { "code": null, "e": 29340, "s": 29304, "text": "#pragma HP_SHLIB_VERSION [“]date[“]" }, { "code": null, "e": 29349, "s": 29340, "text": "Example:" }, { "code": null, "e": 29386, "s": 29349, "text": "#pragma HP_SHLIB_VERSION [“]12/20[“]" }, { "code": null, "e": 29468, "s": 29386, "text": "Here, the data argument is of the form month/year, optionally enclosed in quotes." }, { "code": null, "e": 29527, "s": 29468, "text": "The month must be specified using any number from 1 to 12." }, { "code": null, "e": 29646, "s": 29527, "text": "The year can be specified as either the last two digits of the year (11 for 2011) or a full year specification (2011)." }, { "code": null, "e": 29758, "s": 29646, "text": "Here are the two-digit real codes from 11 to 20 are used to represent the year from 2011 to 2020, respectively." }, { "code": null, "e": 29840, "s": 29758, "text": "The pragma should be used only if incompatible changes are made to a source file." }, { "code": null, "e": 29986, "s": 29840, "text": "The syntax of pragma locality which is used to specify the name to be associated with the code that is written to a relocatable object module is:" }, { "code": null, "e": 30012, "s": 29986, "text": "#pragma LOCALITY “string”" }, { "code": null, "e": 30021, "s": 30012, "text": "Example:" }, { "code": null, "e": 30056, "s": 30021, "text": "#pragma LOCALITY “Geeks For Geeks”" }, { "code": null, "e": 30159, "s": 30056, "text": "In the above example, the string (“Geeks For Geeks”) specifies a name to be used for a coded subspace." }, { "code": null, "e": 30267, "s": 30159, "text": "After this directive, all code following the directive is associated with the name specified in the string." }, { "code": null, "e": 30329, "s": 30267, "text": "The smallest scope of a unique LOCALITY pragma is a function." }, { "code": null, "e": 30380, "s": 30329, "text": "The syntax of pragma VERSION ID can be given as: " }, { "code": null, "e": 30407, "s": 30380, "text": "#pragma VERSIONID “string”" }, { "code": null, "e": 30481, "s": 30407, "text": "Here string is a string of characters that is placed in the object file. " }, { "code": null, "e": 30490, "s": 30481, "text": "Example:" }, { "code": null, "e": 30555, "s": 30490, "text": "#pragma VERSIONID “GFG private limited, Version 1234 5.8.0 1.10”" }, { "code": null, "e": 30686, "s": 30555, "text": "In the above example, the pragma places the character geeks for GFG private limited, Version 1234 5.8.0 1.10 into the object file." }, { "code": null, "e": 30885, "s": 30686, "text": "The pragma once specifies that the file in which this pragma directory is specified will be included opened only once by the compiler in a building of a particular file it’s syntax can be given as: " }, { "code": null, "e": 30898, "s": 30885, "text": "#pragma once" }, { "code": null, "e": 30910, "s": 30898, "text": "Conclusion:" }, { "code": null, "e": 31061, "s": 30910, "text": "The pragma preprocessor directive is mainly used where each implementation of C supports some features unique to its host machine or operating system." }, { "code": null, "e": 31390, "s": 31061, "text": "For example, some programs may need to exercise precise control over the memory areas where data is placed or to control the way certain function receives parameters in such cases, #pragma directives provides operating-system-specific features feature for each compiler while retaining overall compatibility with the C language." }, { "code": null, "e": 31400, "s": 31390, "text": "\nC Macro\n" }, { "code": null, "e": 31425, "s": 31400, "text": "\nC-Macro & Preprocessor\n" }, { "code": null, "e": 31448, "s": 31425, "text": "\nMacro & Preprocessor\n" }, { "code": null, "e": 31461, "s": 31448, "text": "\nC Language\n" }, { "code": null, "e": 31474, "s": 31461, "text": "\nC Programs\n" }, { "code": null, "e": 31679, "s": 31474, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31717, "s": 31679, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31743, "s": 31717, "text": "Exception Handling in C++" }, { "code": null, "e": 31765, "s": 31743, "text": "'this' pointer in C++" }, { "code": null, "e": 31785, "s": 31765, "text": "Multithreading in C" }, { "code": null, "e": 31826, "s": 31785, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31839, "s": 31826, "text": "Strings in C" }, { "code": null, "e": 31880, "s": 31839, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31915, "s": 31880, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31956, "s": 31915, "text": "C Program to read contents of Whole File" } ]
PHP | SplFileInfo getFileInfo() Function - GeeksforGeeks
17 Dec, 2018 The SplFileInfo::getFileInfo() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to get the file information of the file. Syntax: SplFileInfo::getFileInfo( $class ) Parameters: This function accepts single parameter $class which is optional. It is used to specify the name of splfile derived class. Return Value: This function returns the SplFileInfo object. Below programs illustrate the SplFileInfo::getFileInfo() function in PHP: Program 1: <?php // PHP Program to illustrate // Splfileinfo::getFileInfo() function // Create new SPlFileInfo Object$file = new SplFileInfo("gfg.txt"); // Print resultvar_dump( $file->getFileInfo()); ?> object(SplFileInfo)#2 (2) { ["pathName":"SplFileInfo":private]=> string(7) "gfg.txt" ["fileName":"SplFileInfo":private]=> string(7) "gfg.txt" } Program 2: <?php // PHP program to use array to check// multiple files$GFG = array ( "/home/rajvir/Desktop/GeeksforGeeks/dummy.php", "/home/rajvir/Desktop/gfg.txt", "/var/www/html/gfg.php", "demo.c"); foreach ($GFG as $file_name) { // Create new SPlFileInfo Object $file = new SplFileInfo($file_name); // Print result var_dump($file->getFileInfo()); echo "</br>";}?> object(SplFileInfo)#2 (2) { ["pathName":"SplFileInfo":private]=> string(44) "/home/rajvir/Desktop/GeeksforGeeks/dummy.php" ["fileName":"SplFileInfo":private]=> string(9) "dummy.php" } object(SplFileInfo)#1 (2) { ["pathName":"SplFileInfo":private]=> string(28) "/home/rajvir/Desktop/gfg.txt" ["fileName":"SplFileInfo":private]=> string(7) "gfg.txt" } object(SplFileInfo)#2 (2) { ["pathName":"SplFileInfo":private]=> string(21) "/var/www/html/gfg.php" ["fileName":"SplFileInfo":private]=> string(7) "gfg.php" } object(SplFileInfo)#1 (2) { ["pathName":"SplFileInfo":private]=> string(6) "demo.c" ["fileName":"SplFileInfo":private]=> string(6) "demo.c" } Reference: http://php.net/manual/en/splfileinfo.getfileinfo.php PHP-function PHP-SplFileInfo PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to receive JSON POST with PHP ? How to Upload Image into Database and Display it using PHP ? How to fetch data from localserver database and display on HTML table using PHP ? Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 25057, "s": 25029, "text": "\n17 Dec, 2018" }, { "code": null, "e": 25212, "s": 25057, "text": "The SplFileInfo::getFileInfo() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to get the file information of the file." }, { "code": null, "e": 25220, "s": 25212, "text": "Syntax:" }, { "code": null, "e": 25255, "s": 25220, "text": "SplFileInfo::getFileInfo( $class )" }, { "code": null, "e": 25389, "s": 25255, "text": "Parameters: This function accepts single parameter $class which is optional. It is used to specify the name of splfile derived class." }, { "code": null, "e": 25449, "s": 25389, "text": "Return Value: This function returns the SplFileInfo object." }, { "code": null, "e": 25523, "s": 25449, "text": "Below programs illustrate the SplFileInfo::getFileInfo() function in PHP:" }, { "code": null, "e": 25534, "s": 25523, "text": "Program 1:" }, { "code": "<?php // PHP Program to illustrate // Splfileinfo::getFileInfo() function // Create new SPlFileInfo Object$file = new SplFileInfo(\"gfg.txt\"); // Print resultvar_dump( $file->getFileInfo()); ?>", "e": 25734, "s": 25534, "text": null }, { "code": null, "e": 25887, "s": 25734, "text": "object(SplFileInfo)#2 (2) {\n [\"pathName\":\"SplFileInfo\":private]=>\n string(7) \"gfg.txt\"\n [\"fileName\":\"SplFileInfo\":private]=>\n string(7) \"gfg.txt\"\n}\n" }, { "code": null, "e": 25898, "s": 25887, "text": "Program 2:" }, { "code": "<?php // PHP program to use array to check// multiple files$GFG = array ( \"/home/rajvir/Desktop/GeeksforGeeks/dummy.php\", \"/home/rajvir/Desktop/gfg.txt\", \"/var/www/html/gfg.php\", \"demo.c\"); foreach ($GFG as $file_name) { // Create new SPlFileInfo Object $file = new SplFileInfo($file_name); // Print result var_dump($file->getFileInfo()); echo \"</br>\";}?>", "e": 26301, "s": 25898, "text": null }, { "code": null, "e": 26985, "s": 26301, "text": "object(SplFileInfo)#2 (2) {\n [\"pathName\":\"SplFileInfo\":private]=>\n string(44) \"/home/rajvir/Desktop/GeeksforGeeks/dummy.php\"\n [\"fileName\":\"SplFileInfo\":private]=>\n string(9) \"dummy.php\"\n}\nobject(SplFileInfo)#1 (2) {\n [\"pathName\":\"SplFileInfo\":private]=>\n string(28) \"/home/rajvir/Desktop/gfg.txt\"\n [\"fileName\":\"SplFileInfo\":private]=>\n string(7) \"gfg.txt\"\n}\nobject(SplFileInfo)#2 (2) {\n [\"pathName\":\"SplFileInfo\":private]=>\n string(21) \"/var/www/html/gfg.php\"\n [\"fileName\":\"SplFileInfo\":private]=>\n string(7) \"gfg.php\"\n}\nobject(SplFileInfo)#1 (2) {\n [\"pathName\":\"SplFileInfo\":private]=>\n string(6) \"demo.c\"\n [\"fileName\":\"SplFileInfo\":private]=>\n string(6) \"demo.c\"\n}\n" }, { "code": null, "e": 27049, "s": 26985, "text": "Reference: http://php.net/manual/en/splfileinfo.getfileinfo.php" }, { "code": null, "e": 27062, "s": 27049, "text": "PHP-function" }, { "code": null, "e": 27078, "s": 27062, "text": "PHP-SplFileInfo" }, { "code": null, "e": 27082, "s": 27078, "text": "PHP" }, { "code": null, "e": 27099, "s": 27082, "text": "Web Technologies" }, { "code": null, "e": 27103, "s": 27099, "text": "PHP" }, { "code": null, "e": 27201, "s": 27103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27210, "s": 27201, "text": "Comments" }, { "code": null, "e": 27223, "s": 27210, "text": "Old Comments" }, { "code": null, "e": 27273, "s": 27223, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27313, "s": 27273, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27349, "s": 27313, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 27410, "s": 27349, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27492, "s": 27410, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27529, "s": 27492, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27562, "s": 27529, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27607, "s": 27562, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27667, "s": 27607, "text": "How to set the default value for an HTML <select> element ?" } ]
What is BPDU Guard and How to Configure BPDU Guard? - GeeksforGeeks
27 Dec, 2021 Bridge Protocol Data Unit (BPDU) is a spanning tree protocol (STP) message unit which describes the switch port attributes such as MAC address, priority, and cost to achieve which allow switches to participate in the Spanning Tree Protocol to collect information from each other. BPDU Guard is a feature that defends the Layer 2 Spanning Tree Protocol (STP) topology against BPDU-related threats and is designed to protect the switching network. The BPDU guard feature must be activated on ports that should not receive BPDUs from connected devices. If you use the Spanning Tree Protocol (STP) PortFast feature to configure switch ports, you must connect to end devices (workstations, servers, printers, and so on). PortFast is only enabled on the access port to speed up the transition from the access port to the STP forwarding state. End devices should not generate BPDUs because BPDU messages are exchanged by network switches in a normal network environment. To avoid a possible bridging loop, the BPDU Guard blocks interfaces as a preventative measure. The BPDU Guard mechanism is used to keep external influences out of the Spanning Tree domain. BPDU Guard is turned off by default, but it is highly recommended for all ports that have the Port Fast function activated. On ports where Spanning Tree is off, this prevents incorrect information from being injected into the Spanning Tree domain. In Global configuration mode, the BPDU Guard feature can be enabled globally, or per interface in Interface configuration mode. The port gets disabled and the port status is set to Errdisable (same as shutdown status) whenever a BPDU Guard enabled port gets a BPDU from the linked device. The BPDU guard can be enabled or disabled per port. When a BPDU is received on the port, the BPDU guard disables it. Devices behind such ports are effectively blocked from participating in the STP as a result of the disablement. A port must be manually re-enabled after it has been disabled. The BPDU guard is turned off by default. system#configure terminal system(config)#spanning-tree portfast edge bpduguard default system(config)#exit system# system#configure terminal system(config)#no spanning-tree portfast edge bpduguard default system(config)#exit system# system#configure terminal system(config)#interface giga 0/0 system(config-if)#spanning-tree bpduguard enable system(config-if)#exit system(config)#exit system# system#configure terminal system(config)#interface giga 0/0 system(config-if)#spanning-tree bpduguard disable system(config-if)#exit system(config)#exit system# BPDU Guard prevents switching devices from being accidentally connected to PortFast-enabled ports.If someone tries to connect an L2 device to the network, the BPDU guard ensures that it will be rejected. Before the spanning tree is disrupted, it is clipped. BPDU Guard prevents switching devices from being accidentally connected to PortFast-enabled ports. If someone tries to connect an L2 device to the network, the BPDU guard ensures that it will be rejected. Before the spanning tree is disrupted, it is clipped. Whenever the user needs an access switch port with a switch plugged into it, the user needs to visit the CLI of the access switch to disable the BPDU guard. Whenever the user needs an access switch port with a switch plugged into it, the user needs to visit the CLI of the access switch to disable the BPDU guard. Picked Computer Networks Computer Subject Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Block Cipher modes of Operation Intrusion Detection System (IDS) Cryptography and its Types Transport Layer responsibilities SDE SHEET - A Complete Guide for SDE Preparation Introduction to Algorithms Software Engineering | Coupling and Cohesion Software Engineering | Prototyping Model How to Calculate Number of Host in a Subnet?
[ { "code": null, "e": 24119, "s": 24091, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24399, "s": 24119, "text": "Bridge Protocol Data Unit (BPDU) is a spanning tree protocol (STP) message unit which describes the switch port attributes such as MAC address, priority, and cost to achieve which allow switches to participate in the Spanning Tree Protocol to collect information from each other." }, { "code": null, "e": 25084, "s": 24399, "text": "BPDU Guard is a feature that defends the Layer 2 Spanning Tree Protocol (STP) topology against BPDU-related threats and is designed to protect the switching network. The BPDU guard feature must be activated on ports that should not receive BPDUs from connected devices. If you use the Spanning Tree Protocol (STP) PortFast feature to configure switch ports, you must connect to end devices (workstations, servers, printers, and so on). PortFast is only enabled on the access port to speed up the transition from the access port to the STP forwarding state. End devices should not generate BPDUs because BPDU messages are exchanged by network switches in a normal network environment." }, { "code": null, "e": 25521, "s": 25084, "text": "To avoid a possible bridging loop, the BPDU Guard blocks interfaces as a preventative measure. The BPDU Guard mechanism is used to keep external influences out of the Spanning Tree domain. BPDU Guard is turned off by default, but it is highly recommended for all ports that have the Port Fast function activated. On ports where Spanning Tree is off, this prevents incorrect information from being injected into the Spanning Tree domain." }, { "code": null, "e": 25810, "s": 25521, "text": "In Global configuration mode, the BPDU Guard feature can be enabled globally, or per interface in Interface configuration mode. The port gets disabled and the port status is set to Errdisable (same as shutdown status) whenever a BPDU Guard enabled port gets a BPDU from the linked device." }, { "code": null, "e": 26143, "s": 25810, "text": "The BPDU guard can be enabled or disabled per port. When a BPDU is received on the port, the BPDU guard disables it. Devices behind such ports are effectively blocked from participating in the STP as a result of the disablement. A port must be manually re-enabled after it has been disabled. The BPDU guard is turned off by default." }, { "code": null, "e": 26258, "s": 26143, "text": "system#configure terminal\nsystem(config)#spanning-tree portfast edge bpduguard default\nsystem(config)#exit\nsystem#" }, { "code": null, "e": 26376, "s": 26258, "text": "system#configure terminal\nsystem(config)#no spanning-tree portfast edge bpduguard default\nsystem(config)#exit\nsystem#" }, { "code": null, "e": 26536, "s": 26376, "text": "system#configure terminal\nsystem(config)#interface giga 0/0\nsystem(config-if)#spanning-tree bpduguard enable\nsystem(config-if)#exit\nsystem(config)#exit\nsystem#" }, { "code": null, "e": 26698, "s": 26536, "text": "system#configure terminal\nsystem(config)#interface giga 0/0\nsystem(config-if)#spanning-tree bpduguard disable \nsystem(config-if)#exit\nsystem(config)#exit\nsystem#" }, { "code": null, "e": 26956, "s": 26698, "text": "BPDU Guard prevents switching devices from being accidentally connected to PortFast-enabled ports.If someone tries to connect an L2 device to the network, the BPDU guard ensures that it will be rejected. Before the spanning tree is disrupted, it is clipped." }, { "code": null, "e": 27055, "s": 26956, "text": "BPDU Guard prevents switching devices from being accidentally connected to PortFast-enabled ports." }, { "code": null, "e": 27215, "s": 27055, "text": "If someone tries to connect an L2 device to the network, the BPDU guard ensures that it will be rejected. Before the spanning tree is disrupted, it is clipped." }, { "code": null, "e": 27372, "s": 27215, "text": "Whenever the user needs an access switch port with a switch plugged into it, the user needs to visit the CLI of the access switch to disable the BPDU guard." }, { "code": null, "e": 27529, "s": 27372, "text": "Whenever the user needs an access switch port with a switch plugged into it, the user needs to visit the CLI of the access switch to disable the BPDU guard." }, { "code": null, "e": 27536, "s": 27529, "text": "Picked" }, { "code": null, "e": 27554, "s": 27536, "text": "Computer Networks" }, { "code": null, "e": 27571, "s": 27554, "text": "Computer Subject" }, { "code": null, "e": 27589, "s": 27571, "text": "Computer Networks" }, { "code": null, "e": 27687, "s": 27589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27696, "s": 27687, "text": "Comments" }, { "code": null, "e": 27709, "s": 27696, "text": "Old Comments" }, { "code": null, "e": 27744, "s": 27709, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27776, "s": 27744, "text": "Block Cipher modes of Operation" }, { "code": null, "e": 27809, "s": 27776, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27836, "s": 27809, "text": "Cryptography and its Types" }, { "code": null, "e": 27869, "s": 27836, "text": "Transport Layer responsibilities" }, { "code": null, "e": 27918, "s": 27869, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 27945, "s": 27918, "text": "Introduction to Algorithms" }, { "code": null, "e": 27990, "s": 27945, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 28031, "s": 27990, "text": "Software Engineering | Prototyping Model" } ]
Plotting Google Map using folium package?
Folium is a very powerful python library which let you create seveal kind of Leaflet maps. As Leaflet/folium maps are interactive, so they are ideal for making dashborad building. Installing folium is very easy using pip − $pip install folium Like you can see from the below screenshot, you just need to type above command in your console/cmd and pip will install the folium as well as dependencies for your python installation. #Import library import folium #Uses lat then lon. & zoomlevel 4.The bigger the zoom number, the closer in you get. mapOBJ = folium.Map(location=[17.3616, 78.4747], zoom_start = 4, tiles = 'Stamen Terrain') # save method of Map object, will create a map mapOBJ.save('map2.html') import folium import os from folium import features import numpy as np import pandas as pd N = 1000 lons = +5 - np.random.normal(size=N) lats = 48 - np.random.normal(size=N) data = { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'MultiPoint', 'coordinates': [[lon, lat] for (lat, lon) in zip(lats, lons)], }, 'properties': {'prop0': 'value0'} }, ], } m = folium.Map([17.3616, 78.4747], zoom_start = 10) m.add_child(features.GeoJson(data)) m.save('Features.html') import folium from folium import features m = folium.Map([17.3616, 78.4747], zoom_start = 15) mk = features.Marker([17.3616, 78.4747]) pp = folium.Popup('Charminar') ic = features.Icon(color='red') mk.add_child(ic) mk.add_child(pp) m.add_child(mk) m.save('Features_1.html') I have used one new library- vincent, Vincent takes Python data structures (tuples, lists, dicts, and Pandas DataFrames) and translates them into Vega visualization grammar. Using pip, its very easy to install vincent. $pip install vincent C:\WINDOWS\system32>pip install vincent Collecting vincent Downloading https://files.pythonhosted.org/packages/11/bf/a12ecaa21a2e376a16de67e09f64a38a4acd95e04e5dc35ad2f13a6f0bfd/vincent-0.4.4.tar.gz Requirement already satisfied: pandas in c:\python\python361\lib\site-packages (from vincent) (0.20.2) Requirement already satisfied: pytz >= 2011k in c:\python\python361\lib\site-packages (from pandas -> vincent) (2017.2) Requirement already satisfied: python-dateutil >= 2 in c:\python\python361\lib\site-packages (from pandas -> vincent) (2.6.0) Requirement already satisfied: numpy >= 1.7.0 in c:\python\python361\lib\site-packages (from pandas -> vincent) (1.16.0) Requirement already satisfied: six >= 1.5 in c:\python\python361\lib\site-packages (from python-dateutil >= 2 -> pandas -> vincent) (1.10.0) Building wheels for collected packages: vincent Running setup.py bdist_wheel for vincent ... done Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\4c\0d\8a\65f34c765c6094a71cce3e42a49a26533eef61695e9b505f03 Successfully built vincent Installing collected packages: vincent Successfully installed vincent-0.4.4 import folium from folium import features import numpy as np import json import vincent N = 100 multi_iter2 = { 'x': np.random.uniform(size=(N,)), 'y': np.random.uniform(size=(N,)), } scatter = vincent.Scatter(multi_iter2, iter_idx='x', height=100, width=200) data = json.loads(scatter.to_json()) m = folium.Map([17.3616, 78.4747], zoom_start=10) mk = features.Marker([17.3616, 78.4747]) p = folium.Popup('Charminar') v = features.Vega(data, width='100%', height='100%') mk.add_child(p) p.add_child(v) m.add_child(mk) m.save('Features_2.html')
[ { "code": null, "e": 1242, "s": 1062, "text": "Folium is a very powerful python library which let you create seveal kind of Leaflet maps. As Leaflet/folium maps are interactive, so they are ideal for making dashborad building." }, { "code": null, "e": 1285, "s": 1242, "text": "Installing folium is very easy using pip −" }, { "code": null, "e": 1305, "s": 1285, "text": "$pip install folium" }, { "code": null, "e": 1491, "s": 1305, "text": "Like you can see from the below screenshot, you just need to type above command in your console/cmd and pip will install the folium as well as dependencies for your python installation." }, { "code": null, "e": 1772, "s": 1491, "text": "#Import library\nimport folium\n\n#Uses lat then lon. & zoomlevel 4.The bigger the zoom number, the closer in you get.\nmapOBJ = folium.Map(location=[17.3616, 78.4747], zoom_start = 4, tiles = 'Stamen Terrain')\n\n# save method of Map object, will create a map\n\nmapOBJ.save('map2.html')" }, { "code": null, "e": 2359, "s": 1772, "text": "import folium\nimport os\nfrom folium import features\nimport numpy as np\nimport pandas as pd\n\nN = 1000\n\nlons = +5 - np.random.normal(size=N)\nlats = 48 - np.random.normal(size=N)\n\ndata = {\n 'type': 'FeatureCollection',\n 'features': [\n {\n 'type': 'Feature',\n 'geometry': {\n 'type': 'MultiPoint',\n 'coordinates': [[lon, lat] for (lat, lon) in zip(lats, lons)],\n },\n 'properties': {'prop0': 'value0'}\n },\n ],\n}\nm = folium.Map([17.3616, 78.4747], zoom_start = 10)\nm.add_child(features.GeoJson(data))\nm.save('Features.html')" }, { "code": null, "e": 2636, "s": 2359, "text": "import folium\nfrom folium import features\n\nm = folium.Map([17.3616, 78.4747], zoom_start = 15)\nmk = features.Marker([17.3616, 78.4747])\npp = folium.Popup('Charminar')\nic = features.Icon(color='red')\n\nmk.add_child(ic)\nmk.add_child(pp)\nm.add_child(mk)\n\nm.save('Features_1.html')" }, { "code": null, "e": 2810, "s": 2636, "text": "I have used one new library- vincent, Vincent takes Python data structures (tuples, lists, dicts, and Pandas DataFrames) and translates them into Vega visualization grammar." }, { "code": null, "e": 2855, "s": 2810, "text": "Using pip, its very easy to install vincent." }, { "code": null, "e": 2876, "s": 2855, "text": "$pip install vincent" }, { "code": null, "e": 4015, "s": 2876, "text": "C:\\WINDOWS\\system32>pip install vincent\nCollecting vincent\nDownloading https://files.pythonhosted.org/packages/11/bf/a12ecaa21a2e376a16de67e09f64a38a4acd95e04e5dc35ad2f13a6f0bfd/vincent-0.4.4.tar.gz\nRequirement already satisfied: pandas in c:\\python\\python361\\lib\\site-packages (from vincent) (0.20.2)\nRequirement already satisfied: pytz >= 2011k in c:\\python\\python361\\lib\\site-packages (from pandas -> vincent) (2017.2)\nRequirement already satisfied: python-dateutil >= 2 in c:\\python\\python361\\lib\\site-packages (from pandas -> vincent) (2.6.0)\nRequirement already satisfied: numpy >= 1.7.0 in c:\\python\\python361\\lib\\site-packages (from pandas -> vincent) (1.16.0)\nRequirement already satisfied: six >= 1.5 in c:\\python\\python361\\lib\\site-packages (from python-dateutil >= 2 -> pandas -> vincent) (1.10.0)\nBuilding wheels for collected packages: vincent\nRunning setup.py bdist_wheel for vincent ... done\nStored in directory: C:\\Users\\rajesh\\AppData\\Local\\pip\\Cache\\wheels\\4c\\0d\\8a\\65f34c765c6094a71cce3e42a49a26533eef61695e9b505f03\nSuccessfully built vincent\nInstalling collected packages: vincent\nSuccessfully installed vincent-0.4.4" }, { "code": null, "e": 4571, "s": 4015, "text": "import folium\nfrom folium import features\nimport numpy as np\nimport json\nimport vincent\n\nN = 100\n\nmulti_iter2 = {\n 'x': np.random.uniform(size=(N,)),\n 'y': np.random.uniform(size=(N,)),\n}\n\nscatter = vincent.Scatter(multi_iter2, iter_idx='x', height=100, width=200)\ndata = json.loads(scatter.to_json())\n\nm = folium.Map([17.3616, 78.4747], zoom_start=10)\nmk = features.Marker([17.3616, 78.4747])\np = folium.Popup('Charminar')\nv = features.Vega(data, width='100%', height='100%')\n\nmk.add_child(p)\np.add_child(v)\nm.add_child(mk)\n\nm.save('Features_2.html')" } ]
Pandas DataFrame: A lightweight Intro | by Deepak K Gupta (DAKSH) | Towards Data Science
Pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. The Data Structures provided by Pandas are of two distinct types Pandas DataFrame &Pandas Series Pandas DataFrame & Pandas Series We’ll look in Pandas DataFrame in this post. The general trend in learning Pandas (including the official documentation) is to get into Pandas Series first followed by Pandas DataFrame. However, after using Pandas for considerable duration, I’m convinced that we should start with Pandas DataFrame. The concept and rationale behind Pandas Series becomes clear and easier to understand once we’re comfortable with Pandas DataFrame. Here is how the Technical Definition looks like Pandas DataFrame is a 2-D labeled data structure with columns of potentially different type. And here is how you should understand it Pandas DataFrame is nothing but an in-memory representation of an excel sheet via Python programming language So, Pandas DataFrame is similar to excel sheet and looks like this Just like excel, Pandas DataFrame provides various functionalities to analyze, change, and extract valuable information from the given dataset. In the real world, a Panda DataFrame will be created by loading the datasets from persistent storage, including but not limited to excel, csv and MySQL database. However, to help you understand it better, I’ll be using Python Data Structures (Dictionary and list) over here. As depicted in excel sheet above, if we consider column names as “Keys” and list of items under that column as “Values”, we can easily use a python dictionary to represent the same as my_dict = { 'name' : ["a", "b", "c", "d", "e","f", "g"], 'age' : [20,27, 35, 55, 18, 21, 35], 'designation': ["VP", "CEO", "CFO", "VP", "VP", "CEO", "MD"]} We can create a Pandas DataFrame out of this dictionary as import Pandas as pddf = pd.DataFrame(my_dict) The resultant DataFrame shall look similar to what we’ve seen in the excel sheet above as There are chances that the Columns are not in sequence as defined in the dictionary because python implements dictionary as hash and doesn’t guarantee to preserve the sequence. Since, we haven’t provided any Row Index values to the DataFrame, it automatically generates a sequence (0...6) as row index. To provide our own row index, we need to pass index parameter in the DataFrame(...) function as df = pd.DataFrame(my_dict, index=[1,2,3,4,5,6,7]) The index need not be numerical all the time, we can pass strings also as index. For example df = pd.DataFrame( my_dict, index=["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh"]) As you might have guessed that Index are homogeneous in nature which means we can also use NumPy arrays as Index. np_arr = np.array([10,20,30,40,50,60,70])df = pd.DataFrame(my_dict, index=np_arr) Unlike python lists or dictionaries and just like NumPy, a column of the DataFrame will always be of same type. We can check the data type of a column either using dictionary like syntax or by adding the column name using DataFrame . df['age'].dtype # Dict Like Syntaxdf.age.dtype # DataFrame.ColumnNamedf.name.dtype # DataFrame.ColumnName If we want to check the data types of all columns inside the DataFrame, we’ll use the dtypes function of the DataFrame as df.dtypes It will display the type of all columns as At any point of time, Pandas DataFrame will contain hundreds (if not thousands) of rows of data. We can only view them selectively at any point of time. To selectively view the rows, we can use head(...) and tail(...) functions, which by default give first or last five rows (if no input is provided), otherwise shows specific number of rows from top or bottom Here is how it displays the contents df.head() # Displays 1st Five Rows df.tail() # Displays last Five Rows df.head(2) # Displays 1st two Rows df.tail(7) # Displays last 7 Rows This was all about data, however, what if we want to see Row Indexes and Columns name. Pandas DataFrame provides specific functions for viewing them df.index # For Row Indexesdf.columns # For Columns The Pandas DataFrame provides various column helper functions which is extremely useful for extracting valuable information from the column. Some of these are unique → Provide unique elements from a column by removing duplicates. For example df.designation.unique() mean → Provided the mean value of all the items in the column. For example df.age.mean() Most of the time, the given datasets already contains a row index. In those cases, we don’t need Pandas DataFrame to generate a separate row index. Not only its just a redundant information but also takes unnecessary amount of memory. Pandas DataFrame allows setting any existing column or set of columns as Row Index. Here is how can use the columns of the Pandas DataFrame created earlier(using dictionary my_dict ) df = pd.DataFrame(my_dict)df.set_index("name") df.set_index("age") And we can set multiple columns as index by passing a list inside set_index(...) as df.set_index(["name","age"]) Any data analytics activity requires data cleanup and its quite possible that we come to a conclusion to exclude some columns from the datasets that needs to be analyzed. This not only saves memory but also help to analyze the data which is of interest We’ll use the same dictionary for loading Pandas DataFrame, but this time we will specify the columns which will be part of DataFrame df = pd.DataFrame(my_dict, columns=["name", "age"]) Pandas DataFrame provides multiple ways of deleting the rows and columns. There is no functional penalty for choosing one over another. You may use whatever syntax you’re comfortable with. Using Dictionary Syntax → To remove a Column, we’ll use del as del df['name'] Using Drop function → Allows us to delete Columns as well as Rows Whether we’re going to delete Rows or Columns is decided by the second argument in the drop function. The second argument “1” in function drop(...) denotes deletion of the “Column”, whereas “0” means deletion of the “Row # Delete Column "age"df.drop('age',1)# Delete the Row with Index "3"df.drop(3,0) We can also delete multiple Rows and Columns by passing the list in drop(...) function # Delete Columns "name" & "age"df.drop(['name','age'],1)# Delete Rows with index "2","3", & "4"df.drop([2,3,4],0) Note: The Row index are not index numbers, but the row(s) containing that value What if we get a dataset without any columns? Well, Pandas DataFrame don’t mind that and generates the DataFrame by implicitly adding Row Index as well as Column headers for us. For example, if we create a DataFrame from the list below my_list = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], [17,18,19,20]]df = pd.DataFrame(my_list) It will look like this If we don’t want Pandas DataFrame to auto generate the Row Indexes and Column names, we can pass those in DataFrame function as df = pd.DataFrame(my_list, index = ["1->", "2->", "3->", "4->", "5->"], columns = ["A", "B", "C", "D"]) And here is how it will look like It should be noted that we can also create a Pandas DataFrame from NumPy arrays as np_arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,15,16,16], [17,18,19,20]])df = pd.DataFrame(np_arr) Just like Excel Sheets, Pandas DataFrame is at ease with doing mathematical operations on complete DataFrame. It’s possible to do these operations in a Single Column and this is where Pandas Series come into picture. We’ll look into Pandas Series in next post, let’s first see how mathematical operations work on complete DataFrame Multiplications → We can multiply DataFrame with a scalar value of with another DataFrame df * df df * 10 Addition / Subtraction → Similar to Multiplication above, a DataFrame can be added / subtracted with a scalar value or with another DataFrame df + 100 BitWise Operation → It’s possible to do BitWise operations ( AND(&), OR (|)) etc to complete DataFrame df & 0 A series in nothing but a single column of a Pandas DataFrame. Whenever, we have more than one series to work with, we have DataFrames. Alternatively A Pandas DataFrame is a collection of Pandas Series I’ll talk about Panda Series in next post(s) Thanks for Reading ...!!!!
[ { "code": null, "e": 210, "s": 46, "text": "Pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language." }, { "code": null, "e": 275, "s": 210, "text": "The Data Structures provided by Pandas are of two distinct types" }, { "code": null, "e": 307, "s": 275, "text": "Pandas DataFrame &Pandas Series" }, { "code": null, "e": 326, "s": 307, "text": "Pandas DataFrame &" }, { "code": null, "e": 340, "s": 326, "text": "Pandas Series" }, { "code": null, "e": 385, "s": 340, "text": "We’ll look in Pandas DataFrame in this post." }, { "code": null, "e": 771, "s": 385, "text": "The general trend in learning Pandas (including the official documentation) is to get into Pandas Series first followed by Pandas DataFrame. However, after using Pandas for considerable duration, I’m convinced that we should start with Pandas DataFrame. The concept and rationale behind Pandas Series becomes clear and easier to understand once we’re comfortable with Pandas DataFrame." }, { "code": null, "e": 819, "s": 771, "text": "Here is how the Technical Definition looks like" }, { "code": null, "e": 912, "s": 819, "text": "Pandas DataFrame is a 2-D labeled data structure with columns of potentially different type." }, { "code": null, "e": 953, "s": 912, "text": "And here is how you should understand it" }, { "code": null, "e": 1063, "s": 953, "text": "Pandas DataFrame is nothing but an in-memory representation of an excel sheet via Python programming language" }, { "code": null, "e": 1130, "s": 1063, "text": "So, Pandas DataFrame is similar to excel sheet and looks like this" }, { "code": null, "e": 1274, "s": 1130, "text": "Just like excel, Pandas DataFrame provides various functionalities to analyze, change, and extract valuable information from the given dataset." }, { "code": null, "e": 1436, "s": 1274, "text": "In the real world, a Panda DataFrame will be created by loading the datasets from persistent storage, including but not limited to excel, csv and MySQL database." }, { "code": null, "e": 1549, "s": 1436, "text": "However, to help you understand it better, I’ll be using Python Data Structures (Dictionary and list) over here." }, { "code": null, "e": 1733, "s": 1549, "text": "As depicted in excel sheet above, if we consider column names as “Keys” and list of items under that column as “Values”, we can easily use a python dictionary to represent the same as" }, { "code": null, "e": 1902, "s": 1733, "text": "my_dict = { 'name' : [\"a\", \"b\", \"c\", \"d\", \"e\",\"f\", \"g\"], 'age' : [20,27, 35, 55, 18, 21, 35], 'designation': [\"VP\", \"CEO\", \"CFO\", \"VP\", \"VP\", \"CEO\", \"MD\"]}" }, { "code": null, "e": 1961, "s": 1902, "text": "We can create a Pandas DataFrame out of this dictionary as" }, { "code": null, "e": 2007, "s": 1961, "text": "import Pandas as pddf = pd.DataFrame(my_dict)" }, { "code": null, "e": 2097, "s": 2007, "text": "The resultant DataFrame shall look similar to what we’ve seen in the excel sheet above as" }, { "code": null, "e": 2274, "s": 2097, "text": "There are chances that the Columns are not in sequence as defined in the dictionary because python implements dictionary as hash and doesn’t guarantee to preserve the sequence." }, { "code": null, "e": 2400, "s": 2274, "text": "Since, we haven’t provided any Row Index values to the DataFrame, it automatically generates a sequence (0...6) as row index." }, { "code": null, "e": 2496, "s": 2400, "text": "To provide our own row index, we need to pass index parameter in the DataFrame(...) function as" }, { "code": null, "e": 2546, "s": 2496, "text": "df = pd.DataFrame(my_dict, index=[1,2,3,4,5,6,7])" }, { "code": null, "e": 2639, "s": 2546, "text": "The index need not be numerical all the time, we can pass strings also as index. For example" }, { "code": null, "e": 2751, "s": 2639, "text": "df = pd.DataFrame( my_dict, index=[\"First\", \"Second\", \"Third\", \"Fourth\", \"Fifth\", \"Sixth\", \"Seventh\"])" }, { "code": null, "e": 2865, "s": 2751, "text": "As you might have guessed that Index are homogeneous in nature which means we can also use NumPy arrays as Index." }, { "code": null, "e": 2947, "s": 2865, "text": "np_arr = np.array([10,20,30,40,50,60,70])df = pd.DataFrame(my_dict, index=np_arr)" }, { "code": null, "e": 3059, "s": 2947, "text": "Unlike python lists or dictionaries and just like NumPy, a column of the DataFrame will always be of same type." }, { "code": null, "e": 3181, "s": 3059, "text": "We can check the data type of a column either using dictionary like syntax or by adding the column name using DataFrame ." }, { "code": null, "e": 3301, "s": 3181, "text": "df['age'].dtype # Dict Like Syntaxdf.age.dtype # DataFrame.ColumnNamedf.name.dtype # DataFrame.ColumnName" }, { "code": null, "e": 3423, "s": 3301, "text": "If we want to check the data types of all columns inside the DataFrame, we’ll use the dtypes function of the DataFrame as" }, { "code": null, "e": 3439, "s": 3423, "text": "df.dtypes " }, { "code": null, "e": 3482, "s": 3439, "text": "It will display the type of all columns as" }, { "code": null, "e": 3635, "s": 3482, "text": "At any point of time, Pandas DataFrame will contain hundreds (if not thousands) of rows of data. We can only view them selectively at any point of time." }, { "code": null, "e": 3843, "s": 3635, "text": "To selectively view the rows, we can use head(...) and tail(...) functions, which by default give first or last five rows (if no input is provided), otherwise shows specific number of rows from top or bottom" }, { "code": null, "e": 3880, "s": 3843, "text": "Here is how it displays the contents" }, { "code": null, "e": 3917, "s": 3880, "text": "df.head() # Displays 1st Five Rows" }, { "code": null, "e": 3956, "s": 3917, "text": "df.tail() # Displays last Five Rows" }, { "code": null, "e": 3993, "s": 3956, "text": "df.head(2) # Displays 1st two Rows" }, { "code": null, "e": 4031, "s": 3993, "text": "df.tail(7) # Displays last 7 Rows" }, { "code": null, "e": 4180, "s": 4031, "text": "This was all about data, however, what if we want to see Row Indexes and Columns name. Pandas DataFrame provides specific functions for viewing them" }, { "code": null, "e": 4237, "s": 4180, "text": "df.index # For Row Indexesdf.columns # For Columns" }, { "code": null, "e": 4396, "s": 4237, "text": "The Pandas DataFrame provides various column helper functions which is extremely useful for extracting valuable information from the column. Some of these are" }, { "code": null, "e": 4479, "s": 4396, "text": "unique → Provide unique elements from a column by removing duplicates. For example" }, { "code": null, "e": 4503, "s": 4479, "text": "df.designation.unique()" }, { "code": null, "e": 4578, "s": 4503, "text": "mean → Provided the mean value of all the items in the column. For example" }, { "code": null, "e": 4592, "s": 4578, "text": "df.age.mean()" }, { "code": null, "e": 4740, "s": 4592, "text": "Most of the time, the given datasets already contains a row index. In those cases, we don’t need Pandas DataFrame to generate a separate row index." }, { "code": null, "e": 4827, "s": 4740, "text": "Not only its just a redundant information but also takes unnecessary amount of memory." }, { "code": null, "e": 5010, "s": 4827, "text": "Pandas DataFrame allows setting any existing column or set of columns as Row Index. Here is how can use the columns of the Pandas DataFrame created earlier(using dictionary my_dict )" }, { "code": null, "e": 5057, "s": 5010, "text": "df = pd.DataFrame(my_dict)df.set_index(\"name\")" }, { "code": null, "e": 5077, "s": 5057, "text": "df.set_index(\"age\")" }, { "code": null, "e": 5161, "s": 5077, "text": "And we can set multiple columns as index by passing a list inside set_index(...) as" }, { "code": null, "e": 5190, "s": 5161, "text": "df.set_index([\"name\",\"age\"])" }, { "code": null, "e": 5361, "s": 5190, "text": "Any data analytics activity requires data cleanup and its quite possible that we come to a conclusion to exclude some columns from the datasets that needs to be analyzed." }, { "code": null, "e": 5443, "s": 5361, "text": "This not only saves memory but also help to analyze the data which is of interest" }, { "code": null, "e": 5577, "s": 5443, "text": "We’ll use the same dictionary for loading Pandas DataFrame, but this time we will specify the columns which will be part of DataFrame" }, { "code": null, "e": 5629, "s": 5577, "text": "df = pd.DataFrame(my_dict, columns=[\"name\", \"age\"])" }, { "code": null, "e": 5818, "s": 5629, "text": "Pandas DataFrame provides multiple ways of deleting the rows and columns. There is no functional penalty for choosing one over another. You may use whatever syntax you’re comfortable with." }, { "code": null, "e": 5881, "s": 5818, "text": "Using Dictionary Syntax → To remove a Column, we’ll use del as" }, { "code": null, "e": 5896, "s": 5881, "text": "del df['name']" }, { "code": null, "e": 5962, "s": 5896, "text": "Using Drop function → Allows us to delete Columns as well as Rows" }, { "code": null, "e": 6064, "s": 5962, "text": "Whether we’re going to delete Rows or Columns is decided by the second argument in the drop function." }, { "code": null, "e": 6183, "s": 6064, "text": "The second argument “1” in function drop(...) denotes deletion of the “Column”, whereas “0” means deletion of the “Row" }, { "code": null, "e": 6264, "s": 6183, "text": "# Delete Column \"age\"df.drop('age',1)# Delete the Row with Index \"3\"df.drop(3,0)" }, { "code": null, "e": 6351, "s": 6264, "text": "We can also delete multiple Rows and Columns by passing the list in drop(...) function" }, { "code": null, "e": 6465, "s": 6351, "text": "# Delete Columns \"name\" & \"age\"df.drop(['name','age'],1)# Delete Rows with index \"2\",\"3\", & \"4\"df.drop([2,3,4],0)" }, { "code": null, "e": 6545, "s": 6465, "text": "Note: The Row index are not index numbers, but the row(s) containing that value" }, { "code": null, "e": 6591, "s": 6545, "text": "What if we get a dataset without any columns?" }, { "code": null, "e": 6723, "s": 6591, "text": "Well, Pandas DataFrame don’t mind that and generates the DataFrame by implicitly adding Row Index as well as Column headers for us." }, { "code": null, "e": 6781, "s": 6723, "text": "For example, if we create a DataFrame from the list below" }, { "code": null, "e": 6924, "s": 6781, "text": "my_list = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], [17,18,19,20]]df = pd.DataFrame(my_list)" }, { "code": null, "e": 6947, "s": 6924, "text": "It will look like this" }, { "code": null, "e": 7075, "s": 6947, "text": "If we don’t want Pandas DataFrame to auto generate the Row Indexes and Column names, we can pass those in DataFrame function as" }, { "code": null, "e": 7179, "s": 7075, "text": "df = pd.DataFrame(my_list, index = [\"1->\", \"2->\", \"3->\", \"4->\", \"5->\"], columns = [\"A\", \"B\", \"C\", \"D\"])" }, { "code": null, "e": 7213, "s": 7179, "text": "And here is how it will look like" }, { "code": null, "e": 7296, "s": 7213, "text": "It should be noted that we can also create a Pandas DataFrame from NumPy arrays as" }, { "code": null, "e": 7479, "s": 7296, "text": "np_arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,15,16,16], [17,18,19,20]])df = pd.DataFrame(np_arr)" }, { "code": null, "e": 7589, "s": 7479, "text": "Just like Excel Sheets, Pandas DataFrame is at ease with doing mathematical operations on complete DataFrame." }, { "code": null, "e": 7696, "s": 7589, "text": "It’s possible to do these operations in a Single Column and this is where Pandas Series come into picture." }, { "code": null, "e": 7811, "s": 7696, "text": "We’ll look into Pandas Series in next post, let’s first see how mathematical operations work on complete DataFrame" }, { "code": null, "e": 7901, "s": 7811, "text": "Multiplications → We can multiply DataFrame with a scalar value of with another DataFrame" }, { "code": null, "e": 7909, "s": 7901, "text": "df * df" }, { "code": null, "e": 7917, "s": 7909, "text": "df * 10" }, { "code": null, "e": 8059, "s": 7917, "text": "Addition / Subtraction → Similar to Multiplication above, a DataFrame can be added / subtracted with a scalar value or with another DataFrame" }, { "code": null, "e": 8068, "s": 8059, "text": "df + 100" }, { "code": null, "e": 8171, "s": 8068, "text": "BitWise Operation → It’s possible to do BitWise operations ( AND(&), OR (|)) etc to complete DataFrame" }, { "code": null, "e": 8178, "s": 8171, "text": "df & 0" }, { "code": null, "e": 8241, "s": 8178, "text": "A series in nothing but a single column of a Pandas DataFrame." }, { "code": null, "e": 8314, "s": 8241, "text": "Whenever, we have more than one series to work with, we have DataFrames." }, { "code": null, "e": 8328, "s": 8314, "text": "Alternatively" }, { "code": null, "e": 8380, "s": 8328, "text": "A Pandas DataFrame is a collection of Pandas Series" }, { "code": null, "e": 8425, "s": 8380, "text": "I’ll talk about Panda Series in next post(s)" } ]
Complement of Base 10 Integer in Python
Suppose we have a number in decimal number system. We have to get the complement of the number in binary form, then again change it to decimal and return the result. So if the number is 20, then the binary form will be 10100, the complement will be 01011, this is 11 in decimal To solve this, we will follow these steps − s := binary string of the number n sum := 0 and num := 1 for each element i in s in reverse directionif i = ‘b’, then return sumotherwise when i = ‘0’, then sum := sum + numnum := num * 2 if i = ‘b’, then return sum otherwise when i = ‘0’, then sum := sum + num num := num * 2 Let us see the following implementation to get better understanding − Live Demo class Solution(object): def bitwiseComplement(self, N): s = str(bin(N)) sum = 0 num = 1 for i in s[::-1]: if i == "b": return sum elif i =="0": sum+=num num*=2 ob1 = Solution() print(ob1.bitwiseComplement(20)) 20 11
[ { "code": null, "e": 1340, "s": 1062, "text": "Suppose we have a number in decimal number system. We have to get the complement of the number in binary form, then again change it to decimal and return the result. So if the number is 20, then the binary form will be 10100, the complement will be 01011, this is 11 in decimal" }, { "code": null, "e": 1384, "s": 1340, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1419, "s": 1384, "text": "s := binary string of the number n" }, { "code": null, "e": 1441, "s": 1419, "text": "sum := 0 and num := 1" }, { "code": null, "e": 1572, "s": 1441, "text": "for each element i in s in reverse directionif i = ‘b’, then return sumotherwise when i = ‘0’, then sum := sum + numnum := num * 2" }, { "code": null, "e": 1600, "s": 1572, "text": "if i = ‘b’, then return sum" }, { "code": null, "e": 1646, "s": 1600, "text": "otherwise when i = ‘0’, then sum := sum + num" }, { "code": null, "e": 1661, "s": 1646, "text": "num := num * 2" }, { "code": null, "e": 1731, "s": 1661, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1742, "s": 1731, "text": " Live Demo" }, { "code": null, "e": 2030, "s": 1742, "text": "class Solution(object):\n def bitwiseComplement(self, N):\n s = str(bin(N))\n sum = 0\n num = 1\n for i in s[::-1]:\n if i == \"b\":\n return sum\n elif i ==\"0\":\n sum+=num\n num*=2\nob1 = Solution()\nprint(ob1.bitwiseComplement(20))" }, { "code": null, "e": 2033, "s": 2030, "text": "20" }, { "code": null, "e": 2036, "s": 2033, "text": "11" } ]
How to dynamically update a ListView on Android
This example demonstrates How to dynamically update a ListView on Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <ListView android:id = "@+id/list" android:layout_width = "fill_parent" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken listview. Step 3 − Add the following code to src/MainActivity.java How to dynamically update a ListView on Android Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on any item it will update the value to 100 as shown below –
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrates How to dynamically update a ListView on Android" }, { "code": null, "e": 1265, "s": 1136, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1330, "s": 1265, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1749, "s": 1330, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"vertical\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <ListView\n android:id = \"@+id/list\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 1792, "s": 1749, "text": "In the above code, we have taken listview." }, { "code": null, "e": 1849, "s": 1792, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 1897, "s": 1849, "text": "How to dynamically update a ListView on Android" }, { "code": null, "e": 2244, "s": 1897, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 2315, "s": 2244, "text": "Now click on any item it will update the value to 100 as shown below –" } ]
Holiday calendars with Pandas. It’s very common to hear that a data... | by Francisco Gárate | Towards Data Science
It’s very common to hear that a data scientist is a statistician who works with Python on Mac. In part, that’s correct. However, anyone who has worked within the academic world knows that, for a statistician, cows are spherical and months have 365.25/12 days. Instead, in the real world, neither two cows are the same nor is one month equal to any other. I hope this post adds value to all that extra work and time spent by those who work with data avoiding statistical simplifications, whether they are data scientists or whatever they are called. Pandas is the de facto analysis tool for data management in Python. It allows you to work easily with numerical tables and time series. A useful feature in Pandas is to do date ranges easily with the pd.date_range() function, which includes the following parameters (exactly three must be specified): start: Start of range. Left limit for generating dates end: End of range. Right limit periods: Number of periods to generate freq: Frequency strings (e.g. D: calendar day frequency, M: month end frequency, Y: year end frequency) see list of Offset Aliases. A few lines are enough: Date0 2019-01-311 2019-02-282 2019-03-313 2019-04-304 2019-05-315 2019-06-306 2019-07-317 2019-08-318 2019-09-309 2019-10-3110 2019-11-3011 2019-12-31 In certain areas, mainly financial and actuarial, it’s especially useful to manage date ranges where the days in the series correspond to the first or last business day of the month (for example, when projecting coupon payments or annuities). To do this, the pd.date_range() function has different values for the frequency parameter. In the following example, ‘BM’ corresponds to BusinessMonthEnd (last working day of the month): Date0 2019-01-311 2019-02-282 2019-03-293 2019-04-304 2019-05-315 2019-06-286 2019-07-317 2019-08-308 2019-09-309 2019-10-3110 2019-11-2911 2019-12-31 However, if we want more accuracy, we must consider bank holidays (for example, if we calculate costs that depend on the exact days between coupon and coupon, 1 day off in 20 is a 5% error). Knowing the holidays within a period is especially useful when estimating human habits and behaviors (medical care, travels, etc.). In the insurance sector, these patterns can directly affect accounting reserves; for example, when calculating costs incurred but not reported (IBNR). In fact, in some insurance companies it’s common to slightly increase the claims ratio in leap years due to having one calendar day more than the rest. In the following example we introduce a list of two bank holidays (February 28 and May 31) just to see how it works. We then calculate the days between payments if it occurs on the last working day of the month: Date n_days0 2019-01-31 0.01 2019-02-27 27.02 2019-03-29 30.03 2019-04-30 32.04 2019-05-30 30.05 2019-06-28 29.06 2019-07-31 33.07 2019-08-30 30.08 2019-09-30 31.09 2019-10-31 31.010 2019-11-29 29.011 2019-12-31 32.0 As shown, 2019–02–28 and 2019–05–31 don’t appear in the payment calendar. Finally, there is the option of writing rules for calculating public holidays (as these are usually carried over to the next working day). In certain countries, such as the United States, there are laws (Uniform Monday Holiday Act of 1968), whose rules are included in Pandas, print(USFederalHolidayCalendar.rules) as an example for developing other calendars. However, in many other countries there are no rules to determine the holidays of the year (as occurs in Europe), where the holidays are set by regulations each year. For holidays that occur on fixed dates (e.g. US Memorial Day or July 4th) an observance rule determines when that holiday is observed if it falls on a weekend or some other non-observed day. Defined observance rules are: In that case, it’s possible to write the rules of the labor calendars using some common premises for calculating the bank holidays as days on Sunday are moved to the following Monday (observance=sunday_to_monday instruction). E.g.: 2018 Canada day (July 1st) fell on Sunday and got moved to July 2nd. These should be overwritten on the AbstractHolidayCalendar class to have the range apply to all calendar subclasses. Later, I show the labor days in July 2018 to check how it works: Date0 2018-07-031 2018-07-052 2018-07-063 2018-07-094 2018-07-105 2018-07-116 2018-07-127 2018-07-138 2018-07-169 2018-07-1710 2018-07-1811 2018-07-1912 2018-07-2013 2018-07-2314 2018-07-2415 2018-07-2516 2018-07-2617 2018-07-2718 2018-07-3019 2018-07-31 You can see how Sunday, July 1st is replaced by Monday, July 2nd Like this, once we have created our own national holidays calendar, we can use it to see the banks holidays in the coming years, for example 2020: DatetimeIndex(['2019-01-01', '2019-01-07', '2019-03-18', '2019-04-01', '2019-04-19', '2019-05-01', '2019-07-01', '2019-07-04', '2019-11-01', '2019-12-25'], dtype='datetime64[ns]', freq=None) Regional and local holidays can be included in the same way, although noted that in certain countries it’s usually the moveable fests (a religious holiday that is not on the same day every year). In that case, it becomes necessary to create a new function based on Easter() or sunday_to_monday() pandas function). For instance, Whit Monday is the 7th Monday after Easter in France. Our custom calendar can be also used in other libraries such as Prophet. Prophet is an advanced machine learning library created by Facebook, focused on non-linear over time data regression models, which requires a list of holidays provided by the user. For the creation of rules in the Jewish calendar, see these rules done by Ulrich and David Greve. (En español, aquí)
[ { "code": null, "e": 526, "s": 171, "text": "It’s very common to hear that a data scientist is a statistician who works with Python on Mac. In part, that’s correct. However, anyone who has worked within the academic world knows that, for a statistician, cows are spherical and months have 365.25/12 days. Instead, in the real world, neither two cows are the same nor is one month equal to any other." }, { "code": null, "e": 720, "s": 526, "text": "I hope this post adds value to all that extra work and time spent by those who work with data avoiding statistical simplifications, whether they are data scientists or whatever they are called." }, { "code": null, "e": 1021, "s": 720, "text": "Pandas is the de facto analysis tool for data management in Python. It allows you to work easily with numerical tables and time series. A useful feature in Pandas is to do date ranges easily with the pd.date_range() function, which includes the following parameters (exactly three must be specified):" }, { "code": null, "e": 1076, "s": 1021, "text": "start: Start of range. Left limit for generating dates" }, { "code": null, "e": 1107, "s": 1076, "text": "end: End of range. Right limit" }, { "code": null, "e": 1146, "s": 1107, "text": "periods: Number of periods to generate" }, { "code": null, "e": 1278, "s": 1146, "text": "freq: Frequency strings (e.g. D: calendar day frequency, M: month end frequency, Y: year end frequency) see list of Offset Aliases." }, { "code": null, "e": 1302, "s": 1278, "text": "A few lines are enough:" }, { "code": null, "e": 1472, "s": 1302, "text": " Date0 2019-01-311 2019-02-282 2019-03-313 2019-04-304 2019-05-315 2019-06-306 2019-07-317 2019-08-318 2019-09-309 2019-10-3110 2019-11-3011 2019-12-31" }, { "code": null, "e": 1715, "s": 1472, "text": "In certain areas, mainly financial and actuarial, it’s especially useful to manage date ranges where the days in the series correspond to the first or last business day of the month (for example, when projecting coupon payments or annuities)." }, { "code": null, "e": 1902, "s": 1715, "text": "To do this, the pd.date_range() function has different values for the frequency parameter. In the following example, ‘BM’ corresponds to BusinessMonthEnd (last working day of the month):" }, { "code": null, "e": 2072, "s": 1902, "text": " Date0 2019-01-311 2019-02-282 2019-03-293 2019-04-304 2019-05-315 2019-06-286 2019-07-317 2019-08-308 2019-09-309 2019-10-3110 2019-11-2911 2019-12-31" }, { "code": null, "e": 2698, "s": 2072, "text": "However, if we want more accuracy, we must consider bank holidays (for example, if we calculate costs that depend on the exact days between coupon and coupon, 1 day off in 20 is a 5% error). Knowing the holidays within a period is especially useful when estimating human habits and behaviors (medical care, travels, etc.). In the insurance sector, these patterns can directly affect accounting reserves; for example, when calculating costs incurred but not reported (IBNR). In fact, in some insurance companies it’s common to slightly increase the claims ratio in leap years due to having one calendar day more than the rest." }, { "code": null, "e": 2910, "s": 2698, "text": "In the following example we introduce a list of two bank holidays (February 28 and May 31) just to see how it works. We then calculate the days between payments if it occurs on the last working day of the month:" }, { "code": null, "e": 3184, "s": 2910, "text": " Date n_days0 2019-01-31 0.01 2019-02-27 27.02 2019-03-29 30.03 2019-04-30 32.04 2019-05-30 30.05 2019-06-28 29.06 2019-07-31 33.07 2019-08-30 30.08 2019-09-30 31.09 2019-10-31 31.010 2019-11-29 29.011 2019-12-31 32.0" }, { "code": null, "e": 3258, "s": 3184, "text": "As shown, 2019–02–28 and 2019–05–31 don’t appear in the payment calendar." }, { "code": null, "e": 3397, "s": 3258, "text": "Finally, there is the option of writing rules for calculating public holidays (as these are usually carried over to the next working day)." }, { "code": null, "e": 3619, "s": 3397, "text": "In certain countries, such as the United States, there are laws (Uniform Monday Holiday Act of 1968), whose rules are included in Pandas, print(USFederalHolidayCalendar.rules) as an example for developing other calendars." }, { "code": null, "e": 4006, "s": 3619, "text": "However, in many other countries there are no rules to determine the holidays of the year (as occurs in Europe), where the holidays are set by regulations each year. For holidays that occur on fixed dates (e.g. US Memorial Day or July 4th) an observance rule determines when that holiday is observed if it falls on a weekend or some other non-observed day. Defined observance rules are:" }, { "code": null, "e": 4424, "s": 4006, "text": "In that case, it’s possible to write the rules of the labor calendars using some common premises for calculating the bank holidays as days on Sunday are moved to the following Monday (observance=sunday_to_monday instruction). E.g.: 2018 Canada day (July 1st) fell on Sunday and got moved to July 2nd. These should be overwritten on the AbstractHolidayCalendar class to have the range apply to all calendar subclasses." }, { "code": null, "e": 4489, "s": 4424, "text": "Later, I show the labor days in July 2018 to check how it works:" }, { "code": null, "e": 4763, "s": 4489, "text": " Date0 2018-07-031 2018-07-052 2018-07-063 2018-07-094 2018-07-105 2018-07-116 2018-07-127 2018-07-138 2018-07-169 2018-07-1710 2018-07-1811 2018-07-1912 2018-07-2013 2018-07-2314 2018-07-2415 2018-07-2516 2018-07-2617 2018-07-2718 2018-07-3019 2018-07-31" }, { "code": null, "e": 4828, "s": 4763, "text": "You can see how Sunday, July 1st is replaced by Monday, July 2nd" }, { "code": null, "e": 4975, "s": 4828, "text": "Like this, once we have created our own national holidays calendar, we can use it to see the banks holidays in the coming years, for example 2020:" }, { "code": null, "e": 5224, "s": 4975, "text": "DatetimeIndex(['2019-01-01', '2019-01-07', '2019-03-18', '2019-04-01', '2019-04-19', '2019-05-01', '2019-07-01', '2019-07-04', '2019-11-01', '2019-12-25'], dtype='datetime64[ns]', freq=None)" }, { "code": null, "e": 5606, "s": 5224, "text": "Regional and local holidays can be included in the same way, although noted that in certain countries it’s usually the moveable fests (a religious holiday that is not on the same day every year). In that case, it becomes necessary to create a new function based on Easter() or sunday_to_monday() pandas function). For instance, Whit Monday is the 7th Monday after Easter in France." }, { "code": null, "e": 5860, "s": 5606, "text": "Our custom calendar can be also used in other libraries such as Prophet. Prophet is an advanced machine learning library created by Facebook, focused on non-linear over time data regression models, which requires a list of holidays provided by the user." }, { "code": null, "e": 5958, "s": 5860, "text": "For the creation of rules in the Jewish calendar, see these rules done by Ulrich and David Greve." } ]
How can we implement a rounded JTextField in Java?
A JTextField is a subclass of JTextComponent class and it is one of the most important components that allow the user to an input text value in a single-line format. A JTextField class will generate an ActionListener interface when we trying to enter some input inside it. The important methods of a JTextField class are setText(), getText(), setEnabled() and etc. By default, a JTextfield has a rectangle shape, we can also implement a round-shaped JTextField by using the RoundRectangle2D class and need to override the paintComponent() method. import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class RoundedJTextFieldTest extends JFrame { private JTextField tf; public RoundedJTextFieldTest() { setTitle("RoundedJTextField Test"); setLayout(new BorderLayout()); tf = new RoundedJTextField(15); add(tf, BorderLayout.NORTH); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new RoundedJTextFieldTest(); } } // implement a round-shaped JTextField class RoundedJTextField extends JTextField { private Shape shape; public RoundedJTextField(int size) { super(size); setOpaque(false); } protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); super.paintComponent(g); } protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); } public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15); } return shape.contains(x, y); } }
[ { "code": null, "e": 1609, "s": 1062, "text": "A JTextField is a subclass of JTextComponent class and it is one of the most important components that allow the user to an input text value in a single-line format. A JTextField class will generate an ActionListener interface when we trying to enter some input inside it. The important methods of a JTextField class are setText(), getText(),\nsetEnabled() and etc. By default, a JTextfield has a rectangle shape, we can also implement a round-shaped JTextField by using the RoundRectangle2D class and need to override the paintComponent() method." }, { "code": null, "e": 2898, "s": 1609, "text": "import java.awt.*;\nimport javax.swing.*;\nimport java.awt.geom.*;\npublic class RoundedJTextFieldTest extends JFrame {\n private JTextField tf;\n public RoundedJTextFieldTest() {\n setTitle(\"RoundedJTextField Test\");\n setLayout(new BorderLayout());\n tf = new RoundedJTextField(15);\n add(tf, BorderLayout.NORTH);\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String args[]) {\n new RoundedJTextFieldTest();\n }\n}\n// implement a round-shaped JTextField\nclass RoundedJTextField extends JTextField {\n private Shape shape;\n public RoundedJTextField(int size) {\n super(size);\n setOpaque(false);\n}\nprotected void paintComponent(Graphics g) {\n g.setColor(getBackground());\n g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);\n super.paintComponent(g);\n}\nprotected void paintBorder(Graphics g) {\n g.setColor(getForeground());\n g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);\n}\npublic boolean contains(int x, int y) {\n if (shape == null || !shape.getBounds().equals(getBounds())) {\n shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);\n }\n return shape.contains(x, y);\n }\n}" } ]
A Practical Introduction to Pandas Series | by B. Chen | Towards Data Science
DataFrame and Series are two core data structures in Pandas. DataFrame is a 2-dimensional labeled data with rows and columns. It is like a spreadsheet or SQL table. Series is a 1-dimensional labeled array. It is sort of like a more powerful version of the Python list. Understanding Series is very important, not only because it is one of the core data structures, but also because it is the building blocks of a DataFrame. In this article, you’ll learn the most commonly used data operations with Pandas Series and should help you get started with Pandas. The article is structured as follows: Creating a SeriesRetrieving elementsAttributes (commonly used)Methods (commonly used)Working with Python built-in functions Creating a Series Retrieving elements Attributes (commonly used) Methods (commonly used) Working with Python built-in functions Please check out Notebook for the source code. A Python list can be passed to the Pandas Series() function to create a Series. companies = ['Google', 'Microsoft', 'Facebook', 'Apple']pd.Series(companies)0 Google1 Microsoft2 Facebook3 Appledtype: object Notes: All values are represented in the exact same order as they appeared in the original Python list. The dtype says object (it is the internal Pandas lingo for the string). There is an additional column called Index. In this case, it resembles an index from a Python list. But one of the key advantages of a Pandas Series is that the index labels do not have to be numeric, they can be any data type. We can use the argument index to specify a custom index: # Pass numberpd.Series(companies,index=[100,101,102,103])100 Google101 Microsoft102 Facebook103 Appledtype: object# Pass stringpd.Series(companies,index=['GOOGL','MSFT','FB','AAPL'])GOOGL GoogleMSFT MicrosoftFB FacebookAAPL Appledtype: object A dictionary can be passed to the Pandas Series() function. If the index is not specified, the dictionary keys are taken in a sorted order to construct the index. companies = { 'a': 'Google', 'b': 'Microsoft', 'c': 'Facebook', 'd': 'Apple'}pd.Series(companies)a Googleb Microsoftc Facebookd Appledtype: object If the index is specified, then the values in data corresponding to the labels in the index will be pulled out. pd.Series( companies, index=['a', 'b', 'd'])a Googleb Microsoftd Appledtype: object If the input is a scalar value, then the argument index must be provided. The value will be repeated to match the length of the index: pd.Series(10, index=[100, 101, 102, 103])100 10101 10102 10103 10dtype: int64 By default, the Pandas read_csv() function will import data as a DataFrame. It loads the entire dataset into memory, and this could be a memory and performance issue when importing a huge CSV file. pd.read_csv('data.csv') If we want the data to be imported into a Series instead of a DataFrame, we can provide additional arguments usecols and squeeze. The squeeze=True will convert a DataFrame of one column into a Series. pd.read_csv('data.csv', usecols=['product'], squeeze=True)0 A1 B2 C3 DName: product, dtype: object Please check out the following article for Pandas read_csv() towardsdatascience.com Pass the index to retrieve an element, for example, the first element. s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])s[0]1 Retrieving the first n elements, for example, the first 3 elements s[:3]a 1b 2c 3dtype: int64 Retrieving the last n elements. s[-3:]c 3d 4e 5dtype: int64 Retrieving elements within a range s[2:4]c 3d 4dtype: int64 Retrieving elements by step s[::2]a 1c 3e 5dtype: int64 Pandas Series is a 1-dimensional labeled array that we can access elements by index label. Retrieving a single element using an index label. s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])s['a']1 Retrieving multiple elements using a list of index labels. s[['a','c','d']]a 1c 3d 4dtype: int64 Objects in Python have Attributes and Methods. Attributes are a way that we can use to find information without manipulating or destroying anything. Methods actually do something to the object. It may be manipulating it, or adding value, or do some calculation with the object’s values. A Pandas Series is just one type of Python objects. In this section, we will cover some of the commonly used attributes in the Pandas Series. Let’s first create a Pandas Series. companies = ['Google', 'Microsoft', 'Facebook', 'Apple']s = pd.Series(companies) The values attribute returns an array of all the values within the series. s.valuesarray(['Google', 'Microsoft', 'Facebook', 'Apple'], dtype=object) The index attribute returns a RangeIndex object. We can see it starts at 0 and stops at 4. The last part is called step and that’s telling us that it’s incrementing by 1 s.indexRangeIndex(start=0, stop=4, step=1) The is_unique attribute returns a boolean (True or False). It is a really convenient way to check if every series value is unique or not. s.is_uniqueTrue The dtype attribute returns the data type. It gives us 'O' which is short for object. s.dtypedtype('O') The size attribute returns the number of items in a Series. s.size4 The shape attribute returns the number of rows by the number of columns in a tuple s.shape(4,) We also have the ndim attribute which is short for the number of dimensions and a Series is always a 1-dimensional object s.ndim1 A method as mentioned actually does something to the object. It may be manipulating it, or adding value, or do some calculation with the object’s values. The head() and tail() methods return the top and last n rows respectively. n defaults to 5 if you don’t give any value. They are useful for quickly verify data, for example after sorting or appending rows. prices = [10, 5, 3, 2.5, 8, 11]s = pd.Series(prices)s.head()0 10.01 5.02 3.03 2.54 8.0dtype: float64s.head(2)0 10.01 5.0dtype: float64s.tail(2)4 8.05 11.0dtype: float64 We can perform aggregation on a Series, such as mean(), sum(), product(), max(), min(), and median() s.mean()s.sum()s.product() If we need multiple aggregations, we can pass them in a list to agg() method s.agg(['mean','sum','product'])mean 6.583333sum 39.500000product 33000.000000dtype: float64 The unique() and nunique() methods return the unique values and the number of unique values, respectively. s = pd.Series(['a','b','b','a','a'])s.unique()array(['a', 'b'], dtype=object)s.nunique()2 The value_counts() method returns the number of occurrences of each unique value in a Series. It is useful to get an overview of the distribution of values. s.value_counts()a 3b 2dtype: int64 The sort_values() method sorts a Series in ascending or descending order by some criterion. # ascending by defaults.sort_values()# To sort it in descenting orders.sort_values(ascending=False)# To modify the original seriess.sort_values(inplace=True) The sort_index() method sorts a Series by index label. It is similar to sort_value(). # ascending by defaults.sort_index()# To sort it in descenting orders.sort_index(ascending=False)# To modify the original seriess.sort_index(inplace=True) The isna() method returns a boolean same-sized object indicating if the values are missing. s = pd.Series([1, 2, 3, np.nan, np.nan])s.isna()0 False1 False2 False3 True4 Truedtype: bool We can count the number of missing values by chaining the result with the sum() method. s.isna().sum()2 The count() method returns the number of non-missing values in a Series. s.count()3 The nlargest() and nsmallest() methods return the largest and smallest values in a Series. By default, it is showing 5 results if you don’t give any value. s.nlargest()s.nlargest(2) There are logical operator methods: gt(): greater than ge(): greater than or equal eq(): equal le(): less than or equal lt(): less than ne(): not equal They are equivalent to >, >=, = , <= , < and != respectively, but with support to substitute a fill_value for missing values. s.le(5, fill_value=0)s <= 5 len() and type() are Python built-in functions for size and data type. len(s)6type(s)pandas.core.series.Series dir() short for the directory. If we pass a Series onto it, it is going to give us an output of all of the available attributes and methods. dir(s)['T', '_AXIS_LEN', '_AXIS_NAMES', '_AXIS_NUMBERS', '_AXIS_ORDERS', '_AXIS_REVERSED', '_AXIS_TO_AXIS_NUMBER', '_HANDLED_TYPES', '__abs__', ....] To condense a Series, we can use the built-in list() function. It’s kind of doing the exact opposite operation that we passed a list to Series(). list(s)[10.0, 5.0, 3.0, 2.5, 8.0, 11.0] Similarly, dict() is a reverse of the operations when we passed a dictionary to Series() dict(s){0: 10.0, 1: 5.0, 2: 3.0, 3: 2.5, 4: 8.0, 5: 11.0} Python in keyword returns a boolean value that compares the value you provide to the values in the list. It’s going to return True if it exists among those values and False if it does not. 2.5 in sFalse 2.5 in s returns False because by default Pandas is going to look among the index labels not the actual values within the Series. Just make sure to add the extra values attribute: 2.5 in s.valuesTrue Pandas Series is a core data structure in Pandas and the basic building blocks for a DataFrame. This article has covered the commonly used data operations with Pandas Series through 5 aspects. I hope this article will help you to save time in learning Pandas. There are, of course, more attributes and methods to be used with Pandas Series. I recommend you to check out the Series() API documentation and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. Using Pandas method chaining to improve code readability How to do a Custom Sort on Pandas DataFrame When to use Pandas transform() function Pandas concat() tricks you should know Difference between apply() and transform() in Pandas All the Pandas merge() you should know Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on my Github
[ { "code": null, "e": 595, "s": 171, "text": "DataFrame and Series are two core data structures in Pandas. DataFrame is a 2-dimensional labeled data with rows and columns. It is like a spreadsheet or SQL table. Series is a 1-dimensional labeled array. It is sort of like a more powerful version of the Python list. Understanding Series is very important, not only because it is one of the core data structures, but also because it is the building blocks of a DataFrame." }, { "code": null, "e": 766, "s": 595, "text": "In this article, you’ll learn the most commonly used data operations with Pandas Series and should help you get started with Pandas. The article is structured as follows:" }, { "code": null, "e": 890, "s": 766, "text": "Creating a SeriesRetrieving elementsAttributes (commonly used)Methods (commonly used)Working with Python built-in functions" }, { "code": null, "e": 908, "s": 890, "text": "Creating a Series" }, { "code": null, "e": 928, "s": 908, "text": "Retrieving elements" }, { "code": null, "e": 955, "s": 928, "text": "Attributes (commonly used)" }, { "code": null, "e": 979, "s": 955, "text": "Methods (commonly used)" }, { "code": null, "e": 1018, "s": 979, "text": "Working with Python built-in functions" }, { "code": null, "e": 1065, "s": 1018, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1145, "s": 1065, "text": "A Python list can be passed to the Pandas Series() function to create a Series." }, { "code": null, "e": 1291, "s": 1145, "text": "companies = ['Google', 'Microsoft', 'Facebook', 'Apple']pd.Series(companies)0 Google1 Microsoft2 Facebook3 Appledtype: object" }, { "code": null, "e": 1298, "s": 1291, "text": "Notes:" }, { "code": null, "e": 1395, "s": 1298, "text": "All values are represented in the exact same order as they appeared in the original Python list." }, { "code": null, "e": 1467, "s": 1395, "text": "The dtype says object (it is the internal Pandas lingo for the string)." }, { "code": null, "e": 1695, "s": 1467, "text": "There is an additional column called Index. In this case, it resembles an index from a Python list. But one of the key advantages of a Pandas Series is that the index labels do not have to be numeric, they can be any data type." }, { "code": null, "e": 1752, "s": 1695, "text": "We can use the argument index to specify a custom index:" }, { "code": null, "e": 2040, "s": 1752, "text": "# Pass numberpd.Series(companies,index=[100,101,102,103])100 Google101 Microsoft102 Facebook103 Appledtype: object# Pass stringpd.Series(companies,index=['GOOGL','MSFT','FB','AAPL'])GOOGL GoogleMSFT MicrosoftFB FacebookAAPL Appledtype: object" }, { "code": null, "e": 2203, "s": 2040, "text": "A dictionary can be passed to the Pandas Series() function. If the index is not specified, the dictionary keys are taken in a sorted order to construct the index." }, { "code": null, "e": 2382, "s": 2203, "text": "companies = { 'a': 'Google', 'b': 'Microsoft', 'c': 'Facebook', 'd': 'Apple'}pd.Series(companies)a Googleb Microsoftc Facebookd Appledtype: object" }, { "code": null, "e": 2494, "s": 2382, "text": "If the index is specified, then the values in data corresponding to the labels in the index will be pulled out." }, { "code": null, "e": 2601, "s": 2494, "text": "pd.Series( companies, index=['a', 'b', 'd'])a Googleb Microsoftd Appledtype: object" }, { "code": null, "e": 2736, "s": 2601, "text": "If the input is a scalar value, then the argument index must be provided. The value will be repeated to match the length of the index:" }, { "code": null, "e": 2826, "s": 2736, "text": "pd.Series(10, index=[100, 101, 102, 103])100 10101 10102 10103 10dtype: int64" }, { "code": null, "e": 3024, "s": 2826, "text": "By default, the Pandas read_csv() function will import data as a DataFrame. It loads the entire dataset into memory, and this could be a memory and performance issue when importing a huge CSV file." }, { "code": null, "e": 3048, "s": 3024, "text": "pd.read_csv('data.csv')" }, { "code": null, "e": 3249, "s": 3048, "text": "If we want the data to be imported into a Series instead of a DataFrame, we can provide additional arguments usecols and squeeze. The squeeze=True will convert a DataFrame of one column into a Series." }, { "code": null, "e": 3360, "s": 3249, "text": "pd.read_csv('data.csv', usecols=['product'], squeeze=True)0 A1 B2 C3 DName: product, dtype: object" }, { "code": null, "e": 3421, "s": 3360, "text": "Please check out the following article for Pandas read_csv()" }, { "code": null, "e": 3444, "s": 3421, "text": "towardsdatascience.com" }, { "code": null, "e": 3515, "s": 3444, "text": "Pass the index to retrieve an element, for example, the first element." }, { "code": null, "e": 3577, "s": 3515, "text": "s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])s[0]1" }, { "code": null, "e": 3644, "s": 3577, "text": "Retrieving the first n elements, for example, the first 3 elements" }, { "code": null, "e": 3680, "s": 3644, "text": "s[:3]a 1b 2c 3dtype: int64" }, { "code": null, "e": 3712, "s": 3680, "text": "Retrieving the last n elements." }, { "code": null, "e": 3749, "s": 3712, "text": "s[-3:]c 3d 4e 5dtype: int64" }, { "code": null, "e": 3784, "s": 3749, "text": "Retrieving elements within a range" }, { "code": null, "e": 3815, "s": 3784, "text": "s[2:4]c 3d 4dtype: int64" }, { "code": null, "e": 3843, "s": 3815, "text": "Retrieving elements by step" }, { "code": null, "e": 3880, "s": 3843, "text": "s[::2]a 1c 3e 5dtype: int64" }, { "code": null, "e": 3971, "s": 3880, "text": "Pandas Series is a 1-dimensional labeled array that we can access elements by index label." }, { "code": null, "e": 4021, "s": 3971, "text": "Retrieving a single element using an index label." }, { "code": null, "e": 4085, "s": 4021, "text": "s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])s['a']1" }, { "code": null, "e": 4144, "s": 4085, "text": "Retrieving multiple elements using a list of index labels." }, { "code": null, "e": 4191, "s": 4144, "text": "s[['a','c','d']]a 1c 3d 4dtype: int64" }, { "code": null, "e": 4478, "s": 4191, "text": "Objects in Python have Attributes and Methods. Attributes are a way that we can use to find information without manipulating or destroying anything. Methods actually do something to the object. It may be manipulating it, or adding value, or do some calculation with the object’s values." }, { "code": null, "e": 4620, "s": 4478, "text": "A Pandas Series is just one type of Python objects. In this section, we will cover some of the commonly used attributes in the Pandas Series." }, { "code": null, "e": 4656, "s": 4620, "text": "Let’s first create a Pandas Series." }, { "code": null, "e": 4737, "s": 4656, "text": "companies = ['Google', 'Microsoft', 'Facebook', 'Apple']s = pd.Series(companies)" }, { "code": null, "e": 4812, "s": 4737, "text": "The values attribute returns an array of all the values within the series." }, { "code": null, "e": 4886, "s": 4812, "text": "s.valuesarray(['Google', 'Microsoft', 'Facebook', 'Apple'], dtype=object)" }, { "code": null, "e": 5056, "s": 4886, "text": "The index attribute returns a RangeIndex object. We can see it starts at 0 and stops at 4. The last part is called step and that’s telling us that it’s incrementing by 1" }, { "code": null, "e": 5099, "s": 5056, "text": "s.indexRangeIndex(start=0, stop=4, step=1)" }, { "code": null, "e": 5237, "s": 5099, "text": "The is_unique attribute returns a boolean (True or False). It is a really convenient way to check if every series value is unique or not." }, { "code": null, "e": 5253, "s": 5237, "text": "s.is_uniqueTrue" }, { "code": null, "e": 5339, "s": 5253, "text": "The dtype attribute returns the data type. It gives us 'O' which is short for object." }, { "code": null, "e": 5357, "s": 5339, "text": "s.dtypedtype('O')" }, { "code": null, "e": 5417, "s": 5357, "text": "The size attribute returns the number of items in a Series." }, { "code": null, "e": 5425, "s": 5417, "text": "s.size4" }, { "code": null, "e": 5508, "s": 5425, "text": "The shape attribute returns the number of rows by the number of columns in a tuple" }, { "code": null, "e": 5520, "s": 5508, "text": "s.shape(4,)" }, { "code": null, "e": 5642, "s": 5520, "text": "We also have the ndim attribute which is short for the number of dimensions and a Series is always a 1-dimensional object" }, { "code": null, "e": 5650, "s": 5642, "text": "s.ndim1" }, { "code": null, "e": 5804, "s": 5650, "text": "A method as mentioned actually does something to the object. It may be manipulating it, or adding value, or do some calculation with the object’s values." }, { "code": null, "e": 6010, "s": 5804, "text": "The head() and tail() methods return the top and last n rows respectively. n defaults to 5 if you don’t give any value. They are useful for quickly verify data, for example after sorting or appending rows." }, { "code": null, "e": 6212, "s": 6010, "text": "prices = [10, 5, 3, 2.5, 8, 11]s = pd.Series(prices)s.head()0 10.01 5.02 3.03 2.54 8.0dtype: float64s.head(2)0 10.01 5.0dtype: float64s.tail(2)4 8.05 11.0dtype: float64" }, { "code": null, "e": 6313, "s": 6212, "text": "We can perform aggregation on a Series, such as mean(), sum(), product(), max(), min(), and median()" }, { "code": null, "e": 6340, "s": 6313, "text": "s.mean()s.sum()s.product()" }, { "code": null, "e": 6417, "s": 6340, "text": "If we need multiple aggregations, we can pass them in a list to agg() method" }, { "code": null, "e": 6532, "s": 6417, "text": "s.agg(['mean','sum','product'])mean 6.583333sum 39.500000product 33000.000000dtype: float64" }, { "code": null, "e": 6639, "s": 6532, "text": "The unique() and nunique() methods return the unique values and the number of unique values, respectively." }, { "code": null, "e": 6729, "s": 6639, "text": "s = pd.Series(['a','b','b','a','a'])s.unique()array(['a', 'b'], dtype=object)s.nunique()2" }, { "code": null, "e": 6886, "s": 6729, "text": "The value_counts() method returns the number of occurrences of each unique value in a Series. It is useful to get an overview of the distribution of values." }, { "code": null, "e": 6927, "s": 6886, "text": "s.value_counts()a 3b 2dtype: int64" }, { "code": null, "e": 7019, "s": 6927, "text": "The sort_values() method sorts a Series in ascending or descending order by some criterion." }, { "code": null, "e": 7177, "s": 7019, "text": "# ascending by defaults.sort_values()# To sort it in descenting orders.sort_values(ascending=False)# To modify the original seriess.sort_values(inplace=True)" }, { "code": null, "e": 7263, "s": 7177, "text": "The sort_index() method sorts a Series by index label. It is similar to sort_value()." }, { "code": null, "e": 7418, "s": 7263, "text": "# ascending by defaults.sort_index()# To sort it in descenting orders.sort_index(ascending=False)# To modify the original seriess.sort_index(inplace=True)" }, { "code": null, "e": 7510, "s": 7418, "text": "The isna() method returns a boolean same-sized object indicating if the values are missing." }, { "code": null, "e": 7620, "s": 7510, "text": "s = pd.Series([1, 2, 3, np.nan, np.nan])s.isna()0 False1 False2 False3 True4 Truedtype: bool" }, { "code": null, "e": 7708, "s": 7620, "text": "We can count the number of missing values by chaining the result with the sum() method." }, { "code": null, "e": 7724, "s": 7708, "text": "s.isna().sum()2" }, { "code": null, "e": 7797, "s": 7724, "text": "The count() method returns the number of non-missing values in a Series." }, { "code": null, "e": 7808, "s": 7797, "text": "s.count()3" }, { "code": null, "e": 7964, "s": 7808, "text": "The nlargest() and nsmallest() methods return the largest and smallest values in a Series. By default, it is showing 5 results if you don’t give any value." }, { "code": null, "e": 7990, "s": 7964, "text": "s.nlargest()s.nlargest(2)" }, { "code": null, "e": 8026, "s": 7990, "text": "There are logical operator methods:" }, { "code": null, "e": 8045, "s": 8026, "text": "gt(): greater than" }, { "code": null, "e": 8073, "s": 8045, "text": "ge(): greater than or equal" }, { "code": null, "e": 8085, "s": 8073, "text": "eq(): equal" }, { "code": null, "e": 8110, "s": 8085, "text": "le(): less than or equal" }, { "code": null, "e": 8126, "s": 8110, "text": "lt(): less than" }, { "code": null, "e": 8142, "s": 8126, "text": "ne(): not equal" }, { "code": null, "e": 8268, "s": 8142, "text": "They are equivalent to >, >=, = , <= , < and != respectively, but with support to substitute a fill_value for missing values." }, { "code": null, "e": 8296, "s": 8268, "text": "s.le(5, fill_value=0)s <= 5" }, { "code": null, "e": 8367, "s": 8296, "text": "len() and type() are Python built-in functions for size and data type." }, { "code": null, "e": 8407, "s": 8367, "text": "len(s)6type(s)pandas.core.series.Series" }, { "code": null, "e": 8548, "s": 8407, "text": "dir() short for the directory. If we pass a Series onto it, it is going to give us an output of all of the available attributes and methods." }, { "code": null, "e": 8698, "s": 8548, "text": "dir(s)['T', '_AXIS_LEN', '_AXIS_NAMES', '_AXIS_NUMBERS', '_AXIS_ORDERS', '_AXIS_REVERSED', '_AXIS_TO_AXIS_NUMBER', '_HANDLED_TYPES', '__abs__', ....]" }, { "code": null, "e": 8844, "s": 8698, "text": "To condense a Series, we can use the built-in list() function. It’s kind of doing the exact opposite operation that we passed a list to Series()." }, { "code": null, "e": 8884, "s": 8844, "text": "list(s)[10.0, 5.0, 3.0, 2.5, 8.0, 11.0]" }, { "code": null, "e": 8973, "s": 8884, "text": "Similarly, dict() is a reverse of the operations when we passed a dictionary to Series()" }, { "code": null, "e": 9031, "s": 8973, "text": "dict(s){0: 10.0, 1: 5.0, 2: 3.0, 3: 2.5, 4: 8.0, 5: 11.0}" }, { "code": null, "e": 9220, "s": 9031, "text": "Python in keyword returns a boolean value that compares the value you provide to the values in the list. It’s going to return True if it exists among those values and False if it does not." }, { "code": null, "e": 9234, "s": 9220, "text": "2.5 in sFalse" }, { "code": null, "e": 9414, "s": 9234, "text": "2.5 in s returns False because by default Pandas is going to look among the index labels not the actual values within the Series. Just make sure to add the extra values attribute:" }, { "code": null, "e": 9434, "s": 9414, "text": "2.5 in s.valuesTrue" }, { "code": null, "e": 9627, "s": 9434, "text": "Pandas Series is a core data structure in Pandas and the basic building blocks for a DataFrame. This article has covered the commonly used data operations with Pandas Series through 5 aspects." }, { "code": null, "e": 9878, "s": 9627, "text": "I hope this article will help you to save time in learning Pandas. There are, of course, more attributes and methods to be used with Pandas Series. I recommend you to check out the Series() API documentation and to know about other things you can do." }, { "code": null, "e": 10030, "s": 9878, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 10087, "s": 10030, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 10131, "s": 10087, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 10171, "s": 10131, "text": "When to use Pandas transform() function" }, { "code": null, "e": 10210, "s": 10171, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 10263, "s": 10210, "text": "Difference between apply() and transform() in Pandas" }, { "code": null, "e": 10302, "s": 10263, "text": "All the Pandas merge() you should know" }, { "code": null, "e": 10344, "s": 10302, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 10385, "s": 10344, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 10455, "s": 10385, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
Find the last element of a list in scala
Suppose we have a list in Scala, this list is defined under scala.collection.immutable package. As we know, a list is a collection of same type elements which contains immutable (cannot be changed) data. We generally apply last function to show last element of a list. The following Scala code is showing how to print the last element stored in a list of Scala. import scala.collection.immutable._ object HelloWorld { def main(args: Array[String]) { val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome") println("Elements of temp_list: " + temp_list.last) } } $scala HelloWorld Elements of temp_list: awesome The following Scala code is showing how to print the last element stored in a list of Scala using for loop. import scala.collection.immutable._ object HelloWorld { def main(args: Array[String]) { val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome") for(element<-temp_list.last) { print(element) } } } $scala HelloWorld awesome The following Scala code is showing how to print the elements using for-each loop and display the last element. import scala.collection.immutable._ object HelloWorld { def main(args: Array[String]) { val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome") temp_list.foreach{x:String => print(x + ", ") } println("\nLast element is: " + temp_list.last) } } $scala HelloWorld Hello, World, SCALA, is, awesome, Last element is: awesome
[ { "code": null, "e": 1331, "s": 1062, "text": "Suppose we have a list in Scala, this list is defined under scala.collection.immutable package. As we know, a list is a collection of same type elements which contains immutable (cannot be changed) data. We generally apply last function to show last element of a list." }, { "code": null, "e": 1424, "s": 1331, "text": "The following Scala code is showing how to print the last element stored in a list of Scala." }, { "code": null, "e": 1665, "s": 1424, "text": "import scala.collection.immutable._\nobject HelloWorld {\n def main(args: Array[String]) {\n val temp_list: List[String] = List(\"Hello\", \"World\", \"SCALA\", \"is\", \"awesome\")\n println(\"Elements of temp_list: \" + temp_list.last)\n }\n}" }, { "code": null, "e": 1714, "s": 1665, "text": "$scala HelloWorld\nElements of temp_list: awesome" }, { "code": null, "e": 1822, "s": 1714, "text": "The following Scala code is showing how to print the last element stored in a list of Scala using for loop." }, { "code": null, "e": 2074, "s": 1822, "text": "import scala.collection.immutable._\nobject HelloWorld {\n def main(args: Array[String]) {\n val temp_list: List[String] = List(\"Hello\", \"World\", \"SCALA\", \"is\", \"awesome\")\n for(element<-temp_list.last) {\n print(element)\n }\n }\n}" }, { "code": null, "e": 2100, "s": 2074, "text": "$scala HelloWorld\nawesome" }, { "code": null, "e": 2212, "s": 2100, "text": "The following Scala code is showing how to print the elements using for-each loop and display the last element." }, { "code": null, "e": 2503, "s": 2212, "text": "import scala.collection.immutable._\nobject HelloWorld {\n def main(args: Array[String]) {\n val temp_list: List[String] = List(\"Hello\", \"World\", \"SCALA\", \"is\", \"awesome\")\n temp_list.foreach{x:String => print(x + \", \") }\n println(\"\\nLast element is: \" + temp_list.last)\n }\n}" }, { "code": null, "e": 2580, "s": 2503, "text": "$scala HelloWorld\nHello, World, SCALA, is, awesome,\nLast element is: awesome" } ]
Bootstrap 4 | Spinners - GeeksforGeeks
23 Jul, 2021 Bootstrap provides various classes for creating different styles of “spinner” to display the loading state of projects. These classes are inbuilt with HTML and CSS so no need to write any JavaScript to create them. We can also modify the appearance, size, and placement of the spinners with the classes provided by Bootstrap.Types of Spinner: Border spinner: We can create lightweight bordered spinner using the .spinner-border class as given below.Syntax: <div class="spinner-border" role="status"> <span class="sr-only">Loading</span> </div> Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- spinner-border --> <div class="spinner-border" role="status"> <span class="sr-only">Loading</span> </div> </center></body> </html> Output: Note: We have used the class .spinner-border inside <div> element. We have used the role=”status” attribute-value pair inside the <div> for accessibility purposes and a <span> tag with class=”sr-only”, which is a Bootstrap class which makes the container and it’s content visible only on screen-readers. Colored Spinners: We can change the color of the border spinner using text color utility classes of Bootstrap along with the .spinner-border class as given below.Syntax: <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading</span> </div> Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- spinner-border, #1 --> <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #2 --> <div class="spinner-border text-secondary" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #3 --> <div class="spinner-border text-success" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #4 --> <div class="spinner-border text-danger" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #5 --> <div class="spinner-border text-warning" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #6 --> <div class="spinner-border text-info" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #7 --> <div class="spinner-border text-light" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-border, #8 --> <div class="spinner-border text-dark" role="status"> <span class="sr-only">Loading</span> </div> </div></center></body> </html> Output: Note: We have used the text color utility instead of border-color utilities because each border spinner specifies a transparent border for at least one side and the border-{color} utilities override that. Growing spinner: We can create growing spinner by using .spinner-grow class of Bootstrap. It displays as repeatedly grow.Syntax: <div class="spinner-grow" role="status"> <span class="sr-only">Loading</span> </div> Example: html <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body><center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- spinner-grow --> <div class="spinner-grow" role="status"> <span class="sr-only">Loading</span> </div> </div> <center></body> </html> Output: Note: We have used the class .spinner-grow inside <div>. We have used the role=”status” attribute-value pair inside the <div> for accessibility purposes and a <span> tag with class=”sr-only”, which is a Bootstrap class which make the container and its content visible only on screen-readers. Colored growing spinner: We can change the color of growing spinner by using text color utility classes of Bootstrap along with the .spinner-grow class as given below.Syntax: <div class="spinner-grow text-primary" role="status"> <span class="sr-only">Loading</span> </div> Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- spinner-grow, #1 --> <div class="spinner-grow text-primary" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #2 --> <div class="spinner-grow text-secondary" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #3 --> <div class="spinner-grow text-success" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #4 --> <div class="spinner-grow text-danger" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #5 --> <div class="spinner-grow text-warning" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #6 --> <div class="spinner-grow text-info" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #7 --> <div class="spinner-grow text-light" role="status"> <span class="sr-only">Loading</span> </div> <!-- spinner-grow, #8 --> <div class="spinner-grow text-dark" role="status"> <span class="sr-only">Loading</span> </div></center></body> </html> Output: Note: The spinner is built with currentColor which is easily change its appearance with text color utilities. Buttons with border spinner: We can place the border spinner within the button with text or without text by using the .spinner-border class within a <span> tag.Syntax: <button type="button" class="btn btn-primary" disabled> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"> </span> Text </button> Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <button type="button" class="btn btn-secondary" disabled> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"> </span> <span class="sr-only">Loading</span> </button> <button type="button" class="btn btn-primary" disabled> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"> </span> Processing... </button> </div></center></body> </html> Output: Note: We have placed “disabled” attribute within the <button> tag to deactivate it and used “role” and “aria-hidden” attributes within <span> tag for accessibility purposes. Buttons with growing spinner: We can place the growing spinner within the button with text or without text by using the .spinner-grow class within a <span> tag.Syntax: <button type="button" class="btn btn-primary" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> text </button> Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <button type="button" class="btn btn-secondary" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"> </span> <span class="sr-only">Loading</span> </button> <button type="button" class="btn btn-primary" disable> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"> </span> Processing... </button> </div></center></body> </html> Output: Note: We have placed “disabled” attribute within the <button> tag to deactivate it and used “role” and “aria-hidden” attributes within <span> tag for accessibility purposes. Changing the size: Using class: We can change the size using the classes .spinner-border-sm and .spinner-grow-sm along with the .spinner-border and .spinner-grow classes. The list of size classes are given below: smmdlg sm md lg Using CSS: We can also change the size of spinner using CSS styling as given below.Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <div class="container"> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="spinner-border text-primary" role="status" style="height:5rem; width:5rem;"> <span class="sr-only">Loading</span> </div> <div class="spinner-grow text-primary" role="status" style="height:5rem; width:5rem;"> <span class="sr-only">Loading</span> </div> </div></center></body> </html> Output: Changing the alignment: Using text alignment utilities: We can change the alignment of the spinner by placing it inside <div> tag which uses text alignment utility class to control the alignment of children elements as given below.Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class="text-center"> <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading</span> </div> </div> </body> </html> Output: Using float utilities: We can change the alignment of spinner by placing it inside the <div> tag which uses float utilities class to control the alignment of children elements or use the float utilities class directly within the <div> tag through which spinner is created as given below.Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class="clearfix float-right"> <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading</span> </div> </div> </div> </body> </html> Output: Using flexbox utilities: We can change the alignment of the spinner by placing it inside <div> element which uses flexbox utility class to control the alignment of children elements as given below.Example: html <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Spinners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class="d-flex justify-content-center"> <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading</span> </div> </div> </div> </body> </html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 Bootstrap-4 Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Form validation using jQuery How to change navigation bar color in Bootstrap ? How to align navbar items to the right in Bootstrap 4 ? How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28360, "s": 28332, "text": "\n23 Jul, 2021" }, { "code": null, "e": 28705, "s": 28360, "text": "Bootstrap provides various classes for creating different styles of “spinner” to display the loading state of projects. These classes are inbuilt with HTML and CSS so no need to write any JavaScript to create them. We can also modify the appearance, size, and placement of the spinners with the classes provided by Bootstrap.Types of Spinner: " }, { "code": null, "e": 28821, "s": 28705, "text": "Border spinner: We can create lightweight bordered spinner using the .spinner-border class as given below.Syntax: " }, { "code": null, "e": 28914, "s": 28821, "text": "<div class=\"spinner-border\" role=\"status\"> \n <span class=\"sr-only\">Loading</span>\n</div> " }, { "code": null, "e": 28925, "s": 28914, "text": "Example: " }, { "code": null, "e": 28930, "s": 28925, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- spinner-border --> <div class=\"spinner-border\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </center></body> </html>", "e": 29790, "s": 28930, "text": null }, { "code": null, "e": 29800, "s": 29790, "text": "Output: " }, { "code": null, "e": 30106, "s": 29800, "text": "Note: We have used the class .spinner-border inside <div> element. We have used the role=”status” attribute-value pair inside the <div> for accessibility purposes and a <span> tag with class=”sr-only”, which is a Bootstrap class which makes the container and it’s content visible only on screen-readers. " }, { "code": null, "e": 30278, "s": 30106, "text": "Colored Spinners: We can change the color of the border spinner using text color utility classes of Bootstrap along with the .spinner-border class as given below.Syntax: " }, { "code": null, "e": 30383, "s": 30278, "text": "<div class=\"spinner-border text-primary\" role=\"status\">\n <span class=\"sr-only\">Loading</span>\n</div> " }, { "code": null, "e": 30394, "s": 30383, "text": "Example: " }, { "code": null, "e": 30399, "s": 30394, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- spinner-border, #1 --> <div class=\"spinner-border text-primary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #2 --> <div class=\"spinner-border text-secondary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #3 --> <div class=\"spinner-border text-success\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #4 --> <div class=\"spinner-border text-danger\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #5 --> <div class=\"spinner-border text-warning\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #6 --> <div class=\"spinner-border text-info\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #7 --> <div class=\"spinner-border text-light\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-border, #8 --> <div class=\"spinner-border text-dark\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </div></center></body> </html> ", "e": 32440, "s": 30399, "text": null }, { "code": null, "e": 32450, "s": 32440, "text": "Output: " }, { "code": null, "e": 32657, "s": 32450, "text": "Note: We have used the text color utility instead of border-color utilities because each border spinner specifies a transparent border for at least one side and the border-{color} utilities override that. " }, { "code": null, "e": 32788, "s": 32657, "text": "Growing spinner: We can create growing spinner by using .spinner-grow class of Bootstrap. It displays as repeatedly grow.Syntax: " }, { "code": null, "e": 32889, "s": 32788, "text": " \n<div class=\"spinner-grow\" role=\"status\"> \n <span class=\"sr-only\">Loading</span>\n</div> " }, { "code": null, "e": 32900, "s": 32889, "text": "Example: " }, { "code": null, "e": 32905, "s": 32900, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body><center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- spinner-grow --> <div class=\"spinner-grow\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </div> <center></body> </html> ", "e": 33803, "s": 32905, "text": null }, { "code": null, "e": 33813, "s": 33803, "text": "Output: " }, { "code": null, "e": 34107, "s": 33813, "text": "Note: We have used the class .spinner-grow inside <div>. We have used the role=”status” attribute-value pair inside the <div> for accessibility purposes and a <span> tag with class=”sr-only”, which is a Bootstrap class which make the container and its content visible only on screen-readers. " }, { "code": null, "e": 34284, "s": 34107, "text": "Colored growing spinner: We can change the color of growing spinner by using text color utility classes of Bootstrap along with the .spinner-grow class as given below.Syntax: " }, { "code": null, "e": 34388, "s": 34284, "text": "<div class=\"spinner-grow text-primary\" role=\"status\"> \n <span class=\"sr-only\">Loading</span>\n</div> " }, { "code": null, "e": 34399, "s": 34388, "text": "Example: " }, { "code": null, "e": 34404, "s": 34399, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- spinner-grow, #1 --> <div class=\"spinner-grow text-primary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #2 --> <div class=\"spinner-grow text-secondary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #3 --> <div class=\"spinner-grow text-success\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #4 --> <div class=\"spinner-grow text-danger\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #5 --> <div class=\"spinner-grow text-warning\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #6 --> <div class=\"spinner-grow text-info\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #7 --> <div class=\"spinner-grow text-light\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> <!-- spinner-grow, #8 --> <div class=\"spinner-grow text-dark\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div></center></body> </html> ", "e": 36400, "s": 34404, "text": null }, { "code": null, "e": 36410, "s": 36400, "text": "Output: " }, { "code": null, "e": 36522, "s": 36410, "text": "Note: The spinner is built with currentColor which is easily change its appearance with text color utilities. " }, { "code": null, "e": 36692, "s": 36522, "text": "Buttons with border spinner: We can place the border spinner within the button with text or without text by using the .spinner-border class within a <span> tag.Syntax: " }, { "code": null, "e": 36868, "s": 36692, "text": "<button type=\"button\" class=\"btn btn-primary\" disabled> \n <span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"> \n </span> \n Text \n</button>" }, { "code": null, "e": 36879, "s": 36868, "text": "Example: " }, { "code": null, "e": 36884, "s": 36879, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <button type=\"button\" class=\"btn btn-secondary\" disabled> <span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Loading</span> </button> <button type=\"button\" class=\"btn btn-primary\" disabled> <span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"> </span> Processing... </button> </div></center></body> </html> ", "e": 38184, "s": 36884, "text": null }, { "code": null, "e": 38194, "s": 38184, "text": "Output: " }, { "code": null, "e": 38370, "s": 38194, "text": "Note: We have placed “disabled” attribute within the <button> tag to deactivate it and used “role” and “aria-hidden” attributes within <span> tag for accessibility purposes. " }, { "code": null, "e": 38540, "s": 38370, "text": "Buttons with growing spinner: We can place the growing spinner within the button with text or without text by using the .spinner-grow class within a <span> tag.Syntax: " }, { "code": null, "e": 38707, "s": 38540, "text": "<button type=\"button\" class=\"btn btn-primary\" disabled> \n <span class=\"spinner-grow spinner-grow-sm\" role=\"status\" aria-hidden=\"true\"></span> \n text\n</button> " }, { "code": null, "e": 38718, "s": 38707, "text": "Example: " }, { "code": null, "e": 38723, "s": 38718, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <button type=\"button\" class=\"btn btn-secondary\" disabled> <span class=\"spinner-grow spinner-grow-sm\" role=\"status\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Loading</span> </button> <button type=\"button\" class=\"btn btn-primary\" disable> <span class=\"spinner-grow spinner-grow-sm\" role=\"status\" aria-hidden=\"true\"> </span> Processing... </button> </div></center></body> </html> ", "e": 40014, "s": 38723, "text": null }, { "code": null, "e": 40024, "s": 40014, "text": "Output: " }, { "code": null, "e": 40200, "s": 40024, "text": "Note: We have placed “disabled” attribute within the <button> tag to deactivate it and used “role” and “aria-hidden” attributes within <span> tag for accessibility purposes. " }, { "code": null, "e": 40221, "s": 40200, "text": "Changing the size: " }, { "code": null, "e": 40422, "s": 40221, "text": "Using class: We can change the size using the classes .spinner-border-sm and .spinner-grow-sm along with the .spinner-border and .spinner-grow classes. The list of size classes are given below: smmdlg" }, { "code": null, "e": 40425, "s": 40422, "text": "sm" }, { "code": null, "e": 40428, "s": 40425, "text": "md" }, { "code": null, "e": 40431, "s": 40428, "text": "lg" }, { "code": null, "e": 40525, "s": 40431, "text": "Using CSS: We can also change the size of spinner using CSS styling as given below.Example: " }, { "code": null, "e": 40530, "s": 40525, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <div class=\"container\"> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"spinner-border text-primary\" role=\"status\" style=\"height:5rem; width:5rem;\"> <span class=\"sr-only\">Loading</span> </div> <div class=\"spinner-grow text-primary\" role=\"status\" style=\"height:5rem; width:5rem;\"> <span class=\"sr-only\">Loading</span> </div> </div></center></body> </html> ", "e": 41669, "s": 40530, "text": null }, { "code": null, "e": 41679, "s": 41669, "text": "Output: " }, { "code": null, "e": 41707, "s": 41681, "text": "Changing the alignment: " }, { "code": null, "e": 41925, "s": 41707, "text": "Using text alignment utilities: We can change the alignment of the spinner by placing it inside <div> tag which uses text alignment utility class to control the alignment of children elements as given below.Example: " }, { "code": null, "e": 41930, "s": 41925, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class=\"text-center\"> <div class=\"spinner-border text-primary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </div> </body> </html> ", "e": 42899, "s": 41930, "text": null }, { "code": null, "e": 42909, "s": 42899, "text": "Output: " }, { "code": null, "e": 43209, "s": 42911, "text": "Using float utilities: We can change the alignment of spinner by placing it inside the <div> tag which uses float utilities class to control the alignment of children elements or use the float utilities class directly within the <div> tag through which spinner is created as given below.Example: " }, { "code": null, "e": 43214, "s": 43209, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class=\"clearfix float-right\"> <div class=\"spinner-border text-primary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </div> </div> </body> </html> ", "e": 44226, "s": 43214, "text": null }, { "code": null, "e": 44236, "s": 44226, "text": "Output: " }, { "code": null, "e": 44446, "s": 44238, "text": "Using flexbox utilities: We can change the alignment of the spinner by placing it inside <div> element which uses flexbox utility class to control the alignment of children elements as given below.Example: " }, { "code": null, "e": 44451, "s": 44446, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Spinners</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <!-- Changing alignment using text utilities class --> <div class=\"d-flex justify-content-center\"> <div class=\"spinner-border text-primary\" role=\"status\"> <span class=\"sr-only\">Loading</span> </div> </div> </div> </body> </html> ", "e": 45473, "s": 44451, "text": null }, { "code": null, "e": 45483, "s": 45473, "text": "Output: " }, { "code": null, "e": 45502, "s": 45483, "text": "Supported Browser:" }, { "code": null, "e": 45516, "s": 45502, "text": "Google Chrome" }, { "code": null, "e": 45534, "s": 45516, "text": "Internet Explorer" }, { "code": null, "e": 45542, "s": 45534, "text": "Firefox" }, { "code": null, "e": 45548, "s": 45542, "text": "Opera" }, { "code": null, "e": 45556, "s": 45548, "text": "Safari " }, { "code": null, "e": 45570, "s": 45558, "text": "ysachin2314" }, { "code": null, "e": 45582, "s": 45570, "text": "Bootstrap-4" }, { "code": null, "e": 45592, "s": 45582, "text": "Bootstrap" }, { "code": null, "e": 45609, "s": 45592, "text": "Web Technologies" }, { "code": null, "e": 45707, "s": 45609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45716, "s": 45707, "text": "Comments" }, { "code": null, "e": 45729, "s": 45716, "text": "Old Comments" }, { "code": null, "e": 45758, "s": 45729, "text": "Form validation using jQuery" }, { "code": null, "e": 45808, "s": 45758, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 45864, "s": 45808, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 45927, "s": 45864, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 45968, "s": 45927, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 46010, "s": 45968, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 46043, "s": 46010, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46086, "s": 46043, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 46148, "s": 46086, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to list temporary table columns in MySQL?
To list temporary table columns in MySQL, let us first create a temporary table. Here’s an example. We have created a temporary table with some columns that includes the details of a student − mysql> CREATE TEMPORARY TABLE DemoTable745 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(100), StudentAge int, StudentAddress varchar(100), StudentCountryName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Following is the query to list temporary table columns in MySQL− mysql> show columns from DemoTable745; This will produce the following output - +--------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | NULL | | StudentAge | int(11) | YES | | NULL | NULL | | StudentAddress | varchar(100) | YES | | NULL | NULL | | StudentCountryName | varchar(20) | YES | | NULL | NULL | +--------------------+--------------+------+-----+---------+----------------+ 5 rows in set (0.05 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "To list temporary table columns in MySQL, let us first create a temporary table." }, { "code": null, "e": 1255, "s": 1143, "text": "Here’s an example. We have created a temporary table with some columns that includes the details of a student −" }, { "code": null, "e": 1508, "s": 1255, "text": "mysql> CREATE TEMPORARY TABLE DemoTable745 (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(100),\n StudentAge int,\n StudentAddress varchar(100),\n StudentCountryName varchar(20)\n);\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1573, "s": 1508, "text": "Following is the query to list temporary table columns in MySQL−" }, { "code": null, "e": 1612, "s": 1573, "text": "mysql> show columns from DemoTable745;" }, { "code": null, "e": 1653, "s": 1612, "text": "This will produce the following output -" }, { "code": null, "e": 2380, "s": 1653, "text": "+--------------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | NULL |\n| StudentAge | int(11) | YES | | NULL | NULL |\n| StudentAddress | varchar(100) | YES | | NULL | NULL |\n| StudentCountryName | varchar(20) | YES | | NULL | NULL |\n+--------------------+--------------+------+-----+---------+----------------+\n5 rows in set (0.05 sec)" } ]
Getting Started with NLP with spaCy 3.0 | by Lars Nielsen | Towards Data Science
This article is part of the supporting material for the story — ‘Understanding NLP — from TF-IDF to transformers’ This article goes in detail on how to get started with spaCy. We will be focusing on the internals and not just writing some code and executing it. It means — we will be trying to delve a little deeper on what is happening when you execute each code snippet. Every code snippet is broken down and explained in detail. If you just want to see the code in action, you might want to skip the detailed explanation in between and run the codes directly on your IDE. Whom is it for ? If you are just getting started with NLP, it would be advisable to read some articles on the basic concepts of NLP. Some of the concepts you might want to refresh / understand before going ahead — Tokens Parts-of-Speech (POS) tagging Named Entity Recognition (NER) Lemmatization / Stemming This article is for any one just starting out to experiment with spaCy as your choice of package. We will be using spaCy v3.0 in our examples. spaCy is an industrial grade NLP package. It’s fast ( written in C, with language bindings for Python ) It’s production grade Supported by an active community Has lots of active standalone projects built around it Step 1 ) Install spaCy just like any other package > pip install spaCy Step 2 ) Download at least one of the pre-trained pipeline models (for English language), from the command prompt > spacy download en_core_web_sm This downloads a small language model pipeline for English, trained on a huge sample of text found on the web. It has the weights, vocabularies etc (we don’t have to worry about these terms as yet) for the language we have downloaded. Now we are ready to try some examples. There are 4 of these pre-trained pipelines you can download — en_core_web_sm — A small model (13 MB) en_core_web_md — Medium sized pre-trained model(44 MB) en_core_web_lg — A large pre-trained model (742 MB) en_core_web_trf ( — Transformer based pre-trained model 438 MB) The accuracy and efficiency (speed of execution) of your output will depend on which pre-trained model you chose. import spacynlp = spacy.load("en_core_web_md")doc = nlp("On October 23, Apple CEO Tim Cook unveiled the new iPad Mini, fourth generation iPad with Retina display, new iMac, and the 13-inch MacBook Pro with Retina display.") We imported a pre-trained spacy.lang object ( as mentioned earlier, this pre-trained model is based on a sample of English language text from the internet).Run through this nlp() pipeline ( takes a string as parameter and returns a Doc).Returns a spaCy Doc object on which we can work on We imported a pre-trained spacy.lang object ( as mentioned earlier, this pre-trained model is based on a sample of English language text from the internet). Run through this nlp() pipeline ( takes a string as parameter and returns a Doc). Returns a spaCy Doc object on which we can work on When you wrap a text around nlp() a lot of things happen. Just to know what is happening, call the pipeline attribute and you will see what is happening. >> nlp.pipeline Gives the list of components included in the pipeline in the right order. [('tok2vec', <spacy.pipeline.tok2vec.Tok2Vec at 0x24c8>), ('tagger', <spacy.pipeline.tagger.Tagger at 0x24c47c8>), ('parser', <spacy.pipeline.dep_parser.DependencyParser at 0x24c9ba8>), ('ner', <spacy.pipeline.ner.EntityRecognizer at 0x24c66508>), ('attribute_ruler', <spacy.pipeline.attributeruler.AttributeRuler at 0x24c67e08>), ('lemmatizer', <spacy.lang.en.lemmatizer.EnglishLemmatizer at 0x2403a88>)] It means that when you invoke nlp() you are running a series of steps — Tokenizer — Converts the text into small segments comprising of words and the punctuations — these segments are called tokens. Tagger — This component tags each words as a corresponding parts of speech based on the language model that is used. Parser — Component for dependency parsing ( in other words, find the structure and relation between words in a sentence — not that important to understand in the context of this article). NER ( Named Entity Recognizer). Attribute Ruler — When you assign your own rules ( eg : word/phrase token matching), this component can set attributes to individual tokens. Lemmatizer — This component creates lemmas for each of the words/tokens in the doc. (Lemmas are also called the base forms of the word.) WoW ! — As you see, a lot gets done here. And if you have a very large text, it might take a little while. At this point we are ready to do some operations on the doc object. #if you want to show the named entities in the text doc.ents# if you want to display the labels associated with it for tkn in doc.ents : print(tkn.text ," - " ,tkn.label_) Output of the above code would look like this — or if you want a visual display from spacy import displacydisplacy.render(doc, style='ent') will give you the following output. 1.Sentences — You can get the sentences separated into an iterator object using the sents attribute in the doc object creates an iterator which holds each of the sentences. #working with sentences txt = “Hello my dear fellow scholars ! This is Tomas from the German republic. Iam very happy to join you. How are you all feeling ?”doc = nlp(txt)for sentences in doc.sents : print(sentences)# or you can store it as a listlist_sentences = list(doc.sents) the output of the above code looks like this 👉Note : The sentences extracted from the doc object is a statistical prediction and may not be the most accurate one. It does not do a simple rule based splitting — eg: based on a ‘full stop’ / ‘period’ character ) spaCy lets you search custom search patterns . Here’s a simple pattern applied to the earlier example . txt_apl = "On October 23, Apple CEO Tim Cook unveiled the new iPad Mini, fourth generation iPad with Retina display, new iMac, and the 13-inch MacBook Pro with Retina display."doc = nlp(txt_apl) Now, create and add the custom search patterns: from spacy.matcher import Matchermat = Matcher(nlp.vocab,validate = True)#create patterns for matchingpatrn_mac = [ {'LOWER': 'ipad'}]patrn_Appl = [ {'LOWER': {'IN': ['apple', 'appl']}}]mat.add('patrn_mac', [patrn_mac])mat.add('patrn_Appl', [patrn_Appl])for match_id, start, end in mat(doc): print(doc[start: end], “found at “,[start,end]) output of the above code looks like this — Apple found at [4, 5]iPad found at [11, 12]iPad found at [16, 17] Import the relevant package ( here Matcher ).Create a Matcher object mat, by including the spacy.vocab.Vocab object.Define your pattern — here we want to search for any string, convert into lower case and check if it matches ‘ipad’ and name the pattern as patrn_mac. Similarly we create another pattern called patrn_Appl .Add these patterns to the Matcher object (mat) we created.Run / check this Matcher object to the doc that we cretaed from the text. The mat(doc) method returns a list comprising of the matchID , start and end location of the match in the doc — something like this: Import the relevant package ( here Matcher ). Create a Matcher object mat, by including the spacy.vocab.Vocab object. Define your pattern — here we want to search for any string, convert into lower case and check if it matches ‘ipad’ and name the pattern as patrn_mac. Similarly we create another pattern called patrn_Appl . Add these patterns to the Matcher object (mat) we created. Run / check this Matcher object to the doc that we cretaed from the text. The mat(doc) method returns a list comprising of the matchID , start and end location of the match in the doc — something like this: [ (4260053945752191717, 4, 5), (4964878671255706859, 11, 12), (4964878671255706859, 16, 17)] When you run nlp(), it runs a pipeline of components — tok2vec, tagger, parser, ner, attribute_ruler and lemmatizer. doc.ents lists the entities that are recognized by the pre-trained model. You can use displacy to visually see the NER outputs. doc.sents lists your sentences in the doc. You can create custom string matching patterns using Matchermodule. This was a brief introduction on getting started with spaCy . This article, however, does not do justice on the capabilities and power of spaCy as an highly extensible NLP package. More article to follow showcasing the power of spaCy as the production-ready choice of NLP package. If you would like to read some related articles on NLP — here is one — 10 Use-Cases in everyday business operations using NLP
[ { "code": null, "e": 285, "s": 171, "text": "This article is part of the supporting material for the story — ‘Understanding NLP — from TF-IDF to transformers’" }, { "code": null, "e": 544, "s": 285, "text": "This article goes in detail on how to get started with spaCy. We will be focusing on the internals and not just writing some code and executing it. It means — we will be trying to delve a little deeper on what is happening when you execute each code snippet." }, { "code": null, "e": 746, "s": 544, "text": "Every code snippet is broken down and explained in detail. If you just want to see the code in action, you might want to skip the detailed explanation in between and run the codes directly on your IDE." }, { "code": null, "e": 763, "s": 746, "text": "Whom is it for ?" }, { "code": null, "e": 879, "s": 763, "text": "If you are just getting started with NLP, it would be advisable to read some articles on the basic concepts of NLP." }, { "code": null, "e": 960, "s": 879, "text": "Some of the concepts you might want to refresh / understand before going ahead —" }, { "code": null, "e": 967, "s": 960, "text": "Tokens" }, { "code": null, "e": 997, "s": 967, "text": "Parts-of-Speech (POS) tagging" }, { "code": null, "e": 1028, "s": 997, "text": "Named Entity Recognition (NER)" }, { "code": null, "e": 1053, "s": 1028, "text": "Lemmatization / Stemming" }, { "code": null, "e": 1196, "s": 1053, "text": "This article is for any one just starting out to experiment with spaCy as your choice of package. We will be using spaCy v3.0 in our examples." }, { "code": null, "e": 1238, "s": 1196, "text": "spaCy is an industrial grade NLP package." }, { "code": null, "e": 1300, "s": 1238, "text": "It’s fast ( written in C, with language bindings for Python )" }, { "code": null, "e": 1322, "s": 1300, "text": "It’s production grade" }, { "code": null, "e": 1355, "s": 1322, "text": "Supported by an active community" }, { "code": null, "e": 1410, "s": 1355, "text": "Has lots of active standalone projects built around it" }, { "code": null, "e": 1461, "s": 1410, "text": "Step 1 ) Install spaCy just like any other package" }, { "code": null, "e": 1481, "s": 1461, "text": "> pip install spaCy" }, { "code": null, "e": 1595, "s": 1481, "text": "Step 2 ) Download at least one of the pre-trained pipeline models (for English language), from the command prompt" }, { "code": null, "e": 1627, "s": 1595, "text": "> spacy download en_core_web_sm" }, { "code": null, "e": 1901, "s": 1627, "text": "This downloads a small language model pipeline for English, trained on a huge sample of text found on the web. It has the weights, vocabularies etc (we don’t have to worry about these terms as yet) for the language we have downloaded. Now we are ready to try some examples." }, { "code": null, "e": 1963, "s": 1901, "text": "There are 4 of these pre-trained pipelines you can download —" }, { "code": null, "e": 2002, "s": 1963, "text": "en_core_web_sm — A small model (13 MB)" }, { "code": null, "e": 2057, "s": 2002, "text": "en_core_web_md — Medium sized pre-trained model(44 MB)" }, { "code": null, "e": 2109, "s": 2057, "text": "en_core_web_lg — A large pre-trained model (742 MB)" }, { "code": null, "e": 2173, "s": 2109, "text": "en_core_web_trf ( — Transformer based pre-trained model 438 MB)" }, { "code": null, "e": 2287, "s": 2173, "text": "The accuracy and efficiency (speed of execution) of your output will depend on which pre-trained model you chose." }, { "code": null, "e": 2511, "s": 2287, "text": "import spacynlp = spacy.load(\"en_core_web_md\")doc = nlp(\"On October 23, Apple CEO Tim Cook unveiled the new iPad Mini, fourth generation iPad with Retina display, new iMac, and the 13-inch MacBook Pro with Retina display.\")" }, { "code": null, "e": 2799, "s": 2511, "text": "We imported a pre-trained spacy.lang object ( as mentioned earlier, this pre-trained model is based on a sample of English language text from the internet).Run through this nlp() pipeline ( takes a string as parameter and returns a Doc).Returns a spaCy Doc object on which we can work on" }, { "code": null, "e": 2956, "s": 2799, "text": "We imported a pre-trained spacy.lang object ( as mentioned earlier, this pre-trained model is based on a sample of English language text from the internet)." }, { "code": null, "e": 3038, "s": 2956, "text": "Run through this nlp() pipeline ( takes a string as parameter and returns a Doc)." }, { "code": null, "e": 3089, "s": 3038, "text": "Returns a spaCy Doc object on which we can work on" }, { "code": null, "e": 3243, "s": 3089, "text": "When you wrap a text around nlp() a lot of things happen. Just to know what is happening, call the pipeline attribute and you will see what is happening." }, { "code": null, "e": 3259, "s": 3243, "text": ">> nlp.pipeline" }, { "code": null, "e": 3333, "s": 3259, "text": "Gives the list of components included in the pipeline in the right order." }, { "code": null, "e": 3740, "s": 3333, "text": "[('tok2vec', <spacy.pipeline.tok2vec.Tok2Vec at 0x24c8>), ('tagger', <spacy.pipeline.tagger.Tagger at 0x24c47c8>), ('parser', <spacy.pipeline.dep_parser.DependencyParser at 0x24c9ba8>), ('ner', <spacy.pipeline.ner.EntityRecognizer at 0x24c66508>), ('attribute_ruler', <spacy.pipeline.attributeruler.AttributeRuler at 0x24c67e08>), ('lemmatizer', <spacy.lang.en.lemmatizer.EnglishLemmatizer at 0x2403a88>)]" }, { "code": null, "e": 3812, "s": 3740, "text": "It means that when you invoke nlp() you are running a series of steps —" }, { "code": null, "e": 3939, "s": 3812, "text": "Tokenizer — Converts the text into small segments comprising of words and the punctuations — these segments are called tokens." }, { "code": null, "e": 4056, "s": 3939, "text": "Tagger — This component tags each words as a corresponding parts of speech based on the language model that is used." }, { "code": null, "e": 4244, "s": 4056, "text": "Parser — Component for dependency parsing ( in other words, find the structure and relation between words in a sentence — not that important to understand in the context of this article)." }, { "code": null, "e": 4276, "s": 4244, "text": "NER ( Named Entity Recognizer)." }, { "code": null, "e": 4417, "s": 4276, "text": "Attribute Ruler — When you assign your own rules ( eg : word/phrase token matching), this component can set attributes to individual tokens." }, { "code": null, "e": 4554, "s": 4417, "text": "Lemmatizer — This component creates lemmas for each of the words/tokens in the doc. (Lemmas are also called the base forms of the word.)" }, { "code": null, "e": 4661, "s": 4554, "text": "WoW ! — As you see, a lot gets done here. And if you have a very large text, it might take a little while." }, { "code": null, "e": 4729, "s": 4661, "text": "At this point we are ready to do some operations on the doc object." }, { "code": null, "e": 4905, "s": 4729, "text": "#if you want to show the named entities in the text doc.ents# if you want to display the labels associated with it for tkn in doc.ents : print(tkn.text ,\" - \" ,tkn.label_)" }, { "code": null, "e": 4953, "s": 4905, "text": "Output of the above code would look like this —" }, { "code": null, "e": 4985, "s": 4953, "text": "or if you want a visual display" }, { "code": null, "e": 5045, "s": 4985, "text": "from spacy import displacydisplacy.render(doc, style='ent')" }, { "code": null, "e": 5081, "s": 5045, "text": "will give you the following output." }, { "code": null, "e": 5254, "s": 5081, "text": "1.Sentences — You can get the sentences separated into an iterator object using the sents attribute in the doc object creates an iterator which holds each of the sentences." }, { "code": null, "e": 5538, "s": 5254, "text": "#working with sentences txt = “Hello my dear fellow scholars ! This is Tomas from the German republic. Iam very happy to join you. How are you all feeling ?”doc = nlp(txt)for sentences in doc.sents : print(sentences)# or you can store it as a listlist_sentences = list(doc.sents)" }, { "code": null, "e": 5583, "s": 5538, "text": "the output of the above code looks like this" }, { "code": null, "e": 5798, "s": 5583, "text": "👉Note : The sentences extracted from the doc object is a statistical prediction and may not be the most accurate one. It does not do a simple rule based splitting — eg: based on a ‘full stop’ / ‘period’ character )" }, { "code": null, "e": 5902, "s": 5798, "text": "spaCy lets you search custom search patterns . Here’s a simple pattern applied to the earlier example ." }, { "code": null, "e": 6097, "s": 5902, "text": "txt_apl = \"On October 23, Apple CEO Tim Cook unveiled the new iPad Mini, fourth generation iPad with Retina display, new iMac, and the 13-inch MacBook Pro with Retina display.\"doc = nlp(txt_apl)" }, { "code": null, "e": 6145, "s": 6097, "text": "Now, create and add the custom search patterns:" }, { "code": null, "e": 6488, "s": 6145, "text": "from spacy.matcher import Matchermat = Matcher(nlp.vocab,validate = True)#create patterns for matchingpatrn_mac = [ {'LOWER': 'ipad'}]patrn_Appl = [ {'LOWER': {'IN': ['apple', 'appl']}}]mat.add('patrn_mac', [patrn_mac])mat.add('patrn_Appl', [patrn_Appl])for match_id, start, end in mat(doc): print(doc[start: end], “found at “,[start,end])" }, { "code": null, "e": 6531, "s": 6488, "text": "output of the above code looks like this —" }, { "code": null, "e": 6600, "s": 6531, "text": "Apple found at [4, 5]iPad found at [11, 12]iPad found at [16, 17]" }, { "code": null, "e": 7187, "s": 6600, "text": "Import the relevant package ( here Matcher ).Create a Matcher object mat, by including the spacy.vocab.Vocab object.Define your pattern — here we want to search for any string, convert into lower case and check if it matches ‘ipad’ and name the pattern as patrn_mac. Similarly we create another pattern called patrn_Appl .Add these patterns to the Matcher object (mat) we created.Run / check this Matcher object to the doc that we cretaed from the text. The mat(doc) method returns a list comprising of the matchID , start and end location of the match in the doc — something like this:" }, { "code": null, "e": 7233, "s": 7187, "text": "Import the relevant package ( here Matcher )." }, { "code": null, "e": 7305, "s": 7233, "text": "Create a Matcher object mat, by including the spacy.vocab.Vocab object." }, { "code": null, "e": 7512, "s": 7305, "text": "Define your pattern — here we want to search for any string, convert into lower case and check if it matches ‘ipad’ and name the pattern as patrn_mac. Similarly we create another pattern called patrn_Appl ." }, { "code": null, "e": 7571, "s": 7512, "text": "Add these patterns to the Matcher object (mat) we created." }, { "code": null, "e": 7778, "s": 7571, "text": "Run / check this Matcher object to the doc that we cretaed from the text. The mat(doc) method returns a list comprising of the matchID , start and end location of the match in the doc — something like this:" }, { "code": null, "e": 7871, "s": 7778, "text": "[ (4260053945752191717, 4, 5), (4964878671255706859, 11, 12), (4964878671255706859, 16, 17)]" }, { "code": null, "e": 7988, "s": 7871, "text": "When you run nlp(), it runs a pipeline of components — tok2vec, tagger, parser, ner, attribute_ruler and lemmatizer." }, { "code": null, "e": 8062, "s": 7988, "text": "doc.ents lists the entities that are recognized by the pre-trained model." }, { "code": null, "e": 8116, "s": 8062, "text": "You can use displacy to visually see the NER outputs." }, { "code": null, "e": 8159, "s": 8116, "text": "doc.sents lists your sentences in the doc." }, { "code": null, "e": 8227, "s": 8159, "text": "You can create custom string matching patterns using Matchermodule." }, { "code": null, "e": 8508, "s": 8227, "text": "This was a brief introduction on getting started with spaCy . This article, however, does not do justice on the capabilities and power of spaCy as an highly extensible NLP package. More article to follow showcasing the power of spaCy as the production-ready choice of NLP package." }, { "code": null, "e": 8579, "s": 8508, "text": "If you would like to read some related articles on NLP — here is one —" } ]
Print all odd numbers and their sum from 1 to n in PL/SQL - GeeksforGeeks
02 Jul, 2018 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a number N, the task is to display all the odd numbers from 1 to N and their sum. Examples: Input: 3 Output: 1, 3 Input: 5 Output: 1, 3, 5 Approach is to initialize a num with 1 and sum with 0 and keep incrementing num by 2 and sum by num until num <= N. -- display all odd number from 1 to nDECLARE -- declare variable num num NUMBER(3) := 1; sum1 NUMBER(4) := 0;BEGIN WHILE num <= 5 LOOP -- display odd number dbms_output.Put_line(num); -- the sum of all odd numbers sum1 := sum1 + num; --next odd number num := num + 2; -- end loop END LOOP;dbms_output.Put_line('Sum of all odd numbers is '|| sum1);END; Output: 1 3 5 Sum of all odd numbers is 9 SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY SQL | Subquery
[ { "code": null, "e": 25209, "s": 25181, "text": "\n02 Jul, 2018" }, { "code": null, "e": 25453, "s": 25209, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 25541, "s": 25453, "text": "Given a number N, the task is to display all the odd numbers from 1 to N and their sum." }, { "code": null, "e": 25551, "s": 25541, "text": "Examples:" }, { "code": null, "e": 25600, "s": 25551, "text": "Input: 3\nOutput: 1, 3\n\nInput: 5\nOutput: 1, 3, 5\n" }, { "code": null, "e": 25716, "s": 25600, "text": "Approach is to initialize a num with 1 and sum with 0 and keep incrementing num by 2 and sum by num until num <= N." }, { "code": "-- display all odd number from 1 to nDECLARE -- declare variable num num NUMBER(3) := 1; sum1 NUMBER(4) := 0;BEGIN WHILE num <= 5 LOOP -- display odd number dbms_output.Put_line(num); -- the sum of all odd numbers sum1 := sum1 + num; --next odd number num := num + 2; -- end loop END LOOP;dbms_output.Put_line('Sum of all odd numbers is '|| sum1);END; ", "e": 26138, "s": 25716, "text": null }, { "code": null, "e": 26146, "s": 26138, "text": "Output:" }, { "code": null, "e": 26181, "s": 26146, "text": "1\n3\n5\nSum of all odd numbers is 9\n" }, { "code": null, "e": 26192, "s": 26181, "text": "SQL-PL/SQL" }, { "code": null, "e": 26196, "s": 26192, "text": "SQL" }, { "code": null, "e": 26200, "s": 26196, "text": "SQL" }, { "code": null, "e": 26298, "s": 26200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26322, "s": 26298, "text": "SQL Interview Questions" }, { "code": null, "e": 26333, "s": 26322, "text": "CTE in SQL" }, { "code": null, "e": 26399, "s": 26333, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26438, "s": 26399, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 26450, "s": 26438, "text": "SQL | Views" }, { "code": null, "e": 26495, "s": 26450, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26527, "s": 26495, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26566, "s": 26527, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 26581, "s": 26566, "text": "SQL - ORDER BY" } ]
Draw Plot with two Y-Axes in R - GeeksforGeeks
29 Jun, 2021 In this article, we are going to discuss how to create y-axes of both sides of a plot in R programming language. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. To do that in R language we use the following steps. First, we create a sample data, such that the sample data consists of three numeric vectors: x, y1, and y2. The x data will determine X-axis information whereas y1 and y2 will be used for two Y-Axis simultaneously. Now, we will create a scatter plot with two different colors and y-axis values on the left and right sides of the plot. To do so, firstly we will create white space around the plot. This leave space for second y-axis. This can be done using par() method. Now, create the first plot (i.e. the red cross dots) around the first Y-Axis that takes into account data y1. Syntax: plot(x, y1, pch , col ) Next, set new to TRUE in par() method. This needs to be called again after the first plot has been created. This tells the plot that a new plot will be drawn over the first one. Syntax: par(new = TRUE) Next, plot the second plot now with taking y2 data in account. Syntax: plot(x, y2, pch = 15, col = 3, axes = FALSE, xlab = “”, ylab = “”) Next set axis or any additional attribute if required. Example: R # Create sample dataset.seed(2585) x <- rnorm(45)y1 <- x + rnorm(45)y2 <- x + rnorm(45, 7) # Draw first plot using axis y1par(mar = c(7, 3, 5, 4) + 0.3) plot(x, y1, pch = 13, col = 2) # set parameter new=True for a new axispar(new = TRUE) # Draw second plot using axis y2plot(x, y2, pch = 15, col = 3, axes = FALSE, xlab = "", ylab = "") axis(side = 4, at = pretty(range(y2))) mtext("y2", side = 4, line = 3) Output: Output Example 2: R # Create sample data x <- c(1,2,3,4,5,6,7,8,9,10)y1 <-c(2,5,2,8,6,8,3,4,2,4)y2 <-c(2,5,3,7,5,9,7,9,4,1) # Draw first plot using axis y1par(mar = c(7, 3, 5, 4) + 0.3) plot(x, y1, type="l", col = 2) # set parameter new=True for a new axispar(new = TRUE) # Draw second plot using axis y2plot(x, y2, type="l", col = 3, axes = FALSE, xlab = "", ylab = "") axis(side = 4, at = pretty(range(y2))) mtext("y2", side = 4, line = 3) Output: Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26513, "s": 26485, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26626, "s": 26513, "text": "In this article, we are going to discuss how to create y-axes of both sides of a plot in R programming language." }, { "code": null, "e": 26803, "s": 26626, "text": "Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. To do that in R language we use the following steps." }, { "code": null, "e": 27018, "s": 26803, "text": "First, we create a sample data, such that the sample data consists of three numeric vectors: x, y1, and y2. The x data will determine X-axis information whereas y1 and y2 will be used for two Y-Axis simultaneously." }, { "code": null, "e": 27383, "s": 27018, "text": "Now, we will create a scatter plot with two different colors and y-axis values on the left and right sides of the plot. To do so, firstly we will create white space around the plot. This leave space for second y-axis. This can be done using par() method. Now, create the first plot (i.e. the red cross dots) around the first Y-Axis that takes into account data y1." }, { "code": null, "e": 27391, "s": 27383, "text": "Syntax:" }, { "code": null, "e": 27415, "s": 27391, "text": "plot(x, y1, pch , col )" }, { "code": null, "e": 27594, "s": 27415, "text": " Next, set new to TRUE in par() method. This needs to be called again after the first plot has been created. This tells the plot that a new plot will be drawn over the first one." }, { "code": null, "e": 27602, "s": 27594, "text": "Syntax:" }, { "code": null, "e": 27618, "s": 27602, "text": "par(new = TRUE)" }, { "code": null, "e": 27682, "s": 27618, "text": " Next, plot the second plot now with taking y2 data in account." }, { "code": null, "e": 27690, "s": 27682, "text": "Syntax:" }, { "code": null, "e": 27758, "s": 27690, "text": "plot(x, y2, pch = 15, col = 3, axes = FALSE, xlab = “”, ylab = “”) " }, { "code": null, "e": 27813, "s": 27758, "text": "Next set axis or any additional attribute if required." }, { "code": null, "e": 27822, "s": 27813, "text": "Example:" }, { "code": null, "e": 27824, "s": 27822, "text": "R" }, { "code": "# Create sample dataset.seed(2585) x <- rnorm(45)y1 <- x + rnorm(45)y2 <- x + rnorm(45, 7) # Draw first plot using axis y1par(mar = c(7, 3, 5, 4) + 0.3) plot(x, y1, pch = 13, col = 2) # set parameter new=True for a new axispar(new = TRUE) # Draw second plot using axis y2plot(x, y2, pch = 15, col = 3, axes = FALSE, xlab = \"\", ylab = \"\") axis(side = 4, at = pretty(range(y2))) mtext(\"y2\", side = 4, line = 3)", "e": 28294, "s": 27824, "text": null }, { "code": null, "e": 28302, "s": 28294, "text": "Output:" }, { "code": null, "e": 28309, "s": 28302, "text": "Output" }, { "code": null, "e": 28320, "s": 28309, "text": "Example 2:" }, { "code": null, "e": 28322, "s": 28320, "text": "R" }, { "code": "# Create sample data x <- c(1,2,3,4,5,6,7,8,9,10)y1 <-c(2,5,2,8,6,8,3,4,2,4)y2 <-c(2,5,3,7,5,9,7,9,4,1) # Draw first plot using axis y1par(mar = c(7, 3, 5, 4) + 0.3) plot(x, y1, type=\"l\", col = 2) # set parameter new=True for a new axispar(new = TRUE) # Draw second plot using axis y2plot(x, y2, type=\"l\", col = 3, axes = FALSE, xlab = \"\", ylab = \"\") axis(side = 4, at = pretty(range(y2))) mtext(\"y2\", side = 4, line = 3)", "e": 28804, "s": 28322, "text": null }, { "code": null, "e": 28812, "s": 28804, "text": "Output:" }, { "code": null, "e": 28819, "s": 28812, "text": "Picked" }, { "code": null, "e": 28828, "s": 28819, "text": "R-Charts" }, { "code": null, "e": 28837, "s": 28828, "text": "R-Graphs" }, { "code": null, "e": 28845, "s": 28837, "text": "R-plots" }, { "code": null, "e": 28856, "s": 28845, "text": "R Language" }, { "code": null, "e": 28954, "s": 28856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29006, "s": 28954, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29041, "s": 29006, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29079, "s": 29041, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29137, "s": 29079, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29180, "s": 29137, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29217, "s": 29180, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29266, "s": 29217, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29292, "s": 29266, "text": "Time Series Analysis in R" }, { "code": null, "e": 29309, "s": 29292, "text": "R - if statement" } ]
How to make PUT request using XMLHttpRequest by making Custom HTTP library ? - GeeksforGeeks
06 Sep, 2021 The task is to show how the XMLHttpRequest can be used to PUT/Update data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to PUT data by XMLHttpRequest method by making a custom HTTP library.Used API: https://jsonplaceholder.typicode.com/posts/5What is Ajax? Asynchronous JavaScript and XML, is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. To read more about Ajax click on https://www.geeksforgeeks.org/ajax-introduction/.Prerequisites: Only the basic knowledge of HTML, CSS, and JavaScript is required.Note: First make a HTML file and add the HTML markup according to the requirement. In the bottom of the body tag attach two scripts file as library.js and app.js in the same order.Steps required to make library.js File: library.js file make a function easyHTTP to initialize a new XMLHttpRequest() method.Set easyHTTP.prototype.put to a function which contains three parameters ‘url’, data and callback.Now open an object using this.http.open function. It takes three parameters, the first one is request type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call).Now we will use onload function to display the data. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text.Last step is to send the request using the send() function. It should be noted here that send() function needs to send data after converting object data to string using JSON.stringify(data). library.js file make a function easyHTTP to initialize a new XMLHttpRequest() method. Set easyHTTP.prototype.put to a function which contains three parameters ‘url’, data and callback. Now open an object using this.http.open function. It takes three parameters, the first one is request type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call). Now we will use onload function to display the data. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text. Last step is to send the request using the send() function. It should be noted here that send() function needs to send data after converting object data to string using JSON.stringify(data). Steps required to make app.js File: First of all instantiate easyHTTP with new keyword.Create a custom data (object) to put/update data.Pass URL, data and a callback function in put prototype function.The callback function contains two arguments error to print if any error occurs and response to get the actual response. First of all instantiate easyHTTP with new keyword. Create a custom data (object) to put/update data. Pass URL, data and a callback function in put prototype function. The callback function contains two arguments error to print if any error occurs and response to get the actual response. Filename: index.html html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Put request</title></head><body> <h1> Put request using xmlhttpRequest/Ajax by making custom HTTP library. </h1> <div class="result"></div> <!-- Including library.js and app.js files --> <script src="library.js"></script> <script src="app.js"></script></body> </html> Filename: library.js javascript function easyHTTP() { // Initializing new XMLHttpRequest method. this.http = new XMLHttpRequest();} // Make an HTTP PUT RequesteasyHTTP.prototype.put = function(url, data, callback) { // Open an object (POST, PATH, ASYNC-TRUE/FALSE) this.http.open('PUT', url, true); // Set content-type this.http.setRequestHeader( 'Content-type', 'application/json'); // Assigning this to self to have // scope of this into the function onload let self = this; // When response is ready this.http.onload = function() { // Callback function (Error, response text) callback(null, self.http.responseText); } // Since the data is an object so // we need to stringify it this.http.send(JSON.stringify(data));} Filename: app.js javascript // Instantiating easyHTTPconst http = new easyHTTP; // Data that that we need to updateconst data = { title: 'Custom Putt', body: 'This is a custom put'}; // Put prototype method(url, data,// response text)http.put('https://jsonplaceholder.typicode.com/posts/5', data, function(err, post){ if(err) { console.log(err); } else { console.log(post); }}); Output: Open your index.html file in any browser and open its console by right click->Inspect element->console. Hence you will see the below result. sooda367 sagartomar9927 JavaScript-Misc Node.js-Misc HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26401, "s": 26373, "text": "\n06 Sep, 2021" }, { "code": null, "e": 27316, "s": 26401, "text": "The task is to show how the XMLHttpRequest can be used to PUT/Update data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to PUT data by XMLHttpRequest method by making a custom HTTP library.Used API: https://jsonplaceholder.typicode.com/posts/5What is Ajax? Asynchronous JavaScript and XML, is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. To read more about Ajax click on https://www.geeksforgeeks.org/ajax-introduction/.Prerequisites: Only the basic knowledge of HTML, CSS, and JavaScript is required.Note: First make a HTML file and add the HTML markup according to the requirement. In the bottom of the body tag attach two scripts file as library.js and app.js in the same order.Steps required to make library.js File: " }, { "code": null, "e": 28340, "s": 27316, "text": "library.js file make a function easyHTTP to initialize a new XMLHttpRequest() method.Set easyHTTP.prototype.put to a function which contains three parameters ‘url’, data and callback.Now open an object using this.http.open function. It takes three parameters, the first one is request type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call).Now we will use onload function to display the data. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text.Last step is to send the request using the send() function. It should be noted here that send() function needs to send data after converting object data to string using JSON.stringify(data)." }, { "code": null, "e": 28426, "s": 28340, "text": "library.js file make a function easyHTTP to initialize a new XMLHttpRequest() method." }, { "code": null, "e": 28525, "s": 28426, "text": "Set easyHTTP.prototype.put to a function which contains three parameters ‘url’, data and callback." }, { "code": null, "e": 28791, "s": 28525, "text": "Now open an object using this.http.open function. It takes three parameters, the first one is request type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call)." }, { "code": null, "e": 29177, "s": 28791, "text": "Now we will use onload function to display the data. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text." }, { "code": null, "e": 29368, "s": 29177, "text": "Last step is to send the request using the send() function. It should be noted here that send() function needs to send data after converting object data to string using JSON.stringify(data)." }, { "code": null, "e": 29406, "s": 29368, "text": "Steps required to make app.js File: " }, { "code": null, "e": 29693, "s": 29406, "text": "First of all instantiate easyHTTP with new keyword.Create a custom data (object) to put/update data.Pass URL, data and a callback function in put prototype function.The callback function contains two arguments error to print if any error occurs and response to get the actual response." }, { "code": null, "e": 29745, "s": 29693, "text": "First of all instantiate easyHTTP with new keyword." }, { "code": null, "e": 29796, "s": 29745, "text": "Create a custom data (object) to put/update data." }, { "code": null, "e": 29862, "s": 29796, "text": "Pass URL, data and a callback function in put prototype function." }, { "code": null, "e": 29983, "s": 29862, "text": "The callback function contains two arguments error to print if any error occurs and response to get the actual response." }, { "code": null, "e": 30006, "s": 29983, "text": "Filename: index.html " }, { "code": null, "e": 30011, "s": 30006, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Put request</title></head><body> <h1> Put request using xmlhttpRequest/Ajax by making custom HTTP library. </h1> <div class=\"result\"></div> <!-- Including library.js and app.js files --> <script src=\"library.js\"></script> <script src=\"app.js\"></script></body> </html>", "e": 30472, "s": 30011, "text": null }, { "code": null, "e": 30495, "s": 30472, "text": "Filename: library.js " }, { "code": null, "e": 30506, "s": 30495, "text": "javascript" }, { "code": "function easyHTTP() { // Initializing new XMLHttpRequest method. this.http = new XMLHttpRequest();} // Make an HTTP PUT RequesteasyHTTP.prototype.put = function(url, data, callback) { // Open an object (POST, PATH, ASYNC-TRUE/FALSE) this.http.open('PUT', url, true); // Set content-type this.http.setRequestHeader( 'Content-type', 'application/json'); // Assigning this to self to have // scope of this into the function onload let self = this; // When response is ready this.http.onload = function() { // Callback function (Error, response text) callback(null, self.http.responseText); } // Since the data is an object so // we need to stringify it this.http.send(JSON.stringify(data));}", "e": 31229, "s": 30506, "text": null }, { "code": null, "e": 31248, "s": 31229, "text": "Filename: app.js " }, { "code": null, "e": 31259, "s": 31248, "text": "javascript" }, { "code": "// Instantiating easyHTTPconst http = new easyHTTP; // Data that that we need to updateconst data = { title: 'Custom Putt', body: 'This is a custom put'}; // Put prototype method(url, data,// response text)http.put('https://jsonplaceholder.typicode.com/posts/5', data, function(err, post){ if(err) { console.log(err); } else { console.log(post); }});", "e": 31623, "s": 31259, "text": null }, { "code": null, "e": 31774, "s": 31623, "text": "Output: Open your index.html file in any browser and open its console by right click->Inspect element->console. Hence you will see the below result. " }, { "code": null, "e": 31785, "s": 31776, "text": "sooda367" }, { "code": null, "e": 31800, "s": 31785, "text": "sagartomar9927" }, { "code": null, "e": 31816, "s": 31800, "text": "JavaScript-Misc" }, { "code": null, "e": 31829, "s": 31816, "text": "Node.js-Misc" }, { "code": null, "e": 31834, "s": 31829, "text": "HTML" }, { "code": null, "e": 31845, "s": 31834, "text": "JavaScript" }, { "code": null, "e": 31853, "s": 31845, "text": "Node.js" }, { "code": null, "e": 31870, "s": 31853, "text": "Web Technologies" }, { "code": null, "e": 31875, "s": 31870, "text": "HTML" }, { "code": null, "e": 31973, "s": 31875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31997, "s": 31973, "text": "REST API (Introduction)" }, { "code": null, "e": 32038, "s": 31997, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 32075, "s": 32038, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32104, "s": 32075, "text": "Form validation using jQuery" }, { "code": null, "e": 32124, "s": 32104, "text": "Angular File Upload" }, { "code": null, "e": 32164, "s": 32124, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32209, "s": 32164, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32270, "s": 32209, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32342, "s": 32270, "text": "Differences between Functional Components and Class Components in React" } ]
isblank() in C/C++ - GeeksforGeeks
26 Apr, 2018 The isblank()function returns non-zero if ch is a character for which isspace() returns true and is used to separate words. Thus for English, the blank characters are space and horizontal tab. Header File : ctype.h Declaration : int isblank(int ch) difference between isblank() and isspace()The isspace() simply return true if the character is a space. In other words blank character is a space character used to separate words within a line of text and isblank() is used to identify it. isblank() considers blank characters the tab character (‘\t’) and the space character (‘ ‘).isspace() considers space characters : (‘ ‘) – Space, (‘\t’) – Horizontal tab, (‘\n’) – Newline, (‘\v’) – Vertical tab, (‘\f’) – Feed, (‘\r’) – Carriage return Examples: Input: Geeks for Geeks Output: Geeks for Geeks Explanation: Since there are 2 spaces for Geeks for Geeks marked by an underscore( _ ) :Geeks_for_Geekswe replace the space with a newline character. isblank() C++ Program:This code prints out the string character by character, replacing any blank character by a newline. // CPP program to demonstrate working// of isblank()#include <ctype.h>#include <iostream>using namespace std; int main(){ string str = "Geeks for Geeks"; int i = 0; // to store count of blanks int count = 0; while (str[i]) { // to get ith character // from string char ch = str[i++]; // mark a new line when space // or horizontal tab is found if (isblank(ch)) { cout << endl; count++; } else cout << ch; } cout << "\nTotal blanks are : " << count << endl; return 0;} Output: Geeks for Geeks Total blanks are : 2 C-String C Language C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25479, "s": 25451, "text": "\n26 Apr, 2018" }, { "code": null, "e": 25672, "s": 25479, "text": "The isblank()function returns non-zero if ch is a character for which isspace() returns true and is used to separate words. Thus for English, the blank characters are space and horizontal tab." }, { "code": null, "e": 25732, "s": 25672, "text": "Header File : \nctype.h\n\nDeclaration : \nint isblank(int ch)\n" }, { "code": null, "e": 25971, "s": 25732, "text": "difference between isblank() and isspace()The isspace() simply return true if the character is a space. In other words blank character is a space character used to separate words within a line of text and isblank() is used to identify it." }, { "code": null, "e": 26223, "s": 25971, "text": "isblank() considers blank characters the tab character (‘\\t’) and the space character (‘ ‘).isspace() considers space characters : (‘ ‘) – Space, (‘\\t’) – Horizontal tab, (‘\\n’) – Newline, (‘\\v’) – Vertical tab, (‘\\f’) – Feed, (‘\\r’) – Carriage return" }, { "code": null, "e": 26233, "s": 26223, "text": "Examples:" }, { "code": null, "e": 26299, "s": 26233, "text": "Input: Geeks for Geeks\nOutput: Geeks\n for \n Geeks\n" }, { "code": null, "e": 26449, "s": 26299, "text": "Explanation: Since there are 2 spaces for Geeks for Geeks marked by an underscore( _ ) :Geeks_for_Geekswe replace the space with a newline character." }, { "code": null, "e": 26571, "s": 26449, "text": "isblank() C++ Program:This code prints out the string character by character, replacing any blank character by a newline." }, { "code": "// CPP program to demonstrate working// of isblank()#include <ctype.h>#include <iostream>using namespace std; int main(){ string str = \"Geeks for Geeks\"; int i = 0; // to store count of blanks int count = 0; while (str[i]) { // to get ith character // from string char ch = str[i++]; // mark a new line when space // or horizontal tab is found if (isblank(ch)) { cout << endl; count++; } else cout << ch; } cout << \"\\nTotal blanks are : \" << count << endl; return 0;}", "e": 27175, "s": 26571, "text": null }, { "code": null, "e": 27183, "s": 27175, "text": "Output:" }, { "code": null, "e": 27221, "s": 27183, "text": "Geeks\nfor\nGeeks\nTotal blanks are : 2\n" }, { "code": null, "e": 27230, "s": 27221, "text": "C-String" }, { "code": null, "e": 27241, "s": 27230, "text": "C Language" }, { "code": null, "e": 27245, "s": 27241, "text": "C++" }, { "code": null, "e": 27264, "s": 27245, "text": "Technical Scripter" }, { "code": null, "e": 27268, "s": 27264, "text": "CPP" }, { "code": null, "e": 27366, "s": 27268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27404, "s": 27366, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27430, "s": 27404, "text": "Exception Handling in C++" }, { "code": null, "e": 27450, "s": 27430, "text": "Multithreading in C" }, { "code": null, "e": 27472, "s": 27450, "text": "'this' pointer in C++" }, { "code": null, "e": 27513, "s": 27472, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27531, "s": 27513, "text": "Vector in C++ STL" }, { "code": null, "e": 27577, "s": 27531, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27596, "s": 27577, "text": "Inheritance in C++" }, { "code": null, "e": 27639, "s": 27596, "text": "Map in C++ Standard Template Library (STL)" } ]
Differences Between Scala and Golang - GeeksforGeeks
21 Apr, 2022 Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM (Java Virtual Machine). Scala stands for Scalable language. It also provides Javascript runtimes. Example: Scala // Scala program to print Hello GFG! // Creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, GFG! println("Hello, GFG!")}} Output: Hello GFG! Golang is a procedural and statically typed programming language having syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google’s production systems. Example: Go // Golang programpackage main import "fmt" // Main functionfunc main() { fmt.Println("Hello Geeks")} Output: Hello Geeks Golang Scala mayank007rawa Difference Between Go Language Scala 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang strings.Replace() Function in Golang With Examples
[ { "code": null, "e": 26103, "s": 26075, "text": "\n21 Apr, 2022" }, { "code": null, "e": 26459, "s": 26103, "text": "Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM (Java Virtual Machine). Scala stands for Scalable language. It also provides Javascript runtimes. " }, { "code": null, "e": 26468, "s": 26459, "text": "Example:" }, { "code": null, "e": 26474, "s": 26468, "text": "Scala" }, { "code": "// Scala program to print Hello GFG! // Creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, GFG! println(\"Hello, GFG!\")}}", "e": 26647, "s": 26474, "text": null }, { "code": null, "e": 26655, "s": 26647, "text": "Output:" }, { "code": null, "e": 26666, "s": 26655, "text": "Hello GFG!" }, { "code": null, "e": 27022, "s": 26666, "text": "Golang is a procedural and statically typed programming language having syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google’s production systems." }, { "code": null, "e": 27031, "s": 27022, "text": "Example:" }, { "code": null, "e": 27034, "s": 27031, "text": "Go" }, { "code": "// Golang programpackage main import \"fmt\" // Main functionfunc main() { fmt.Println(\"Hello Geeks\")}", "e": 27145, "s": 27034, "text": null }, { "code": null, "e": 27153, "s": 27145, "text": "Output:" }, { "code": null, "e": 27165, "s": 27153, "text": "Hello Geeks" }, { "code": null, "e": 27172, "s": 27165, "text": "Golang" }, { "code": null, "e": 27178, "s": 27172, "text": "Scala" }, { "code": null, "e": 27192, "s": 27178, "text": "mayank007rawa" }, { "code": null, "e": 27211, "s": 27192, "text": "Difference Between" }, { "code": null, "e": 27223, "s": 27211, "text": "Go Language" }, { "code": null, "e": 27229, "s": 27223, "text": "Scala" }, { "code": null, "e": 27327, "s": 27229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27388, "s": 27327, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27456, "s": 27388, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27514, "s": 27456, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27569, "s": 27514, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27635, "s": 27569, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 27687, "s": 27635, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 27733, "s": 27687, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 27783, "s": 27733, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 27809, "s": 27783, "text": "Time Formatting in Golang" } ]
Python | Convert a nested list into a flat list - GeeksforGeeks
10 Sep, 2018 The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. Examples: Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]]Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”] We use recursion because the levels of nesting cannot be predetermined. # Python code to flat a nested list with# multiple levels of nesting allowed. # input listl = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] # output listoutput = [] # function used for removing nested # lists in python. def reemovNestings(l): for i in l: if type(i) == list: reemovNestings(i) else: output.append(i) # Driver codeprint ('The original list: ', l)reemovNestings(l)print ('The list after removing nesting: ', output) The original list: [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] The list after removing nesting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] python-list Python Recursion python-list Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 25519, "s": 25491, "text": "\n10 Sep, 2018" }, { "code": null, "e": 25825, "s": 25519, "text": "The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside." }, { "code": null, "e": 25835, "s": 25825, "text": "Examples:" }, { "code": null, "e": 25934, "s": 25835, "text": "Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }, { "code": null, "e": 26038, "s": 25934, "text": "Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]]Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”]" }, { "code": null, "e": 26110, "s": 26038, "text": "We use recursion because the levels of nesting cannot be predetermined." }, { "code": "# Python code to flat a nested list with# multiple levels of nesting allowed. # input listl = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] # output listoutput = [] # function used for removing nested # lists in python. def reemovNestings(l): for i in l: if type(i) == list: reemovNestings(i) else: output.append(i) # Driver codeprint ('The original list: ', l)reemovNestings(l)print ('The list after removing nesting: ', output)", "e": 26577, "s": 26110, "text": null }, { "code": null, "e": 26704, "s": 26577, "text": "The original list: [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]\nThe list after removing nesting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" }, { "code": null, "e": 26716, "s": 26704, "text": "python-list" }, { "code": null, "e": 26723, "s": 26716, "text": "Python" }, { "code": null, "e": 26733, "s": 26723, "text": "Recursion" }, { "code": null, "e": 26745, "s": 26733, "text": "python-list" }, { "code": null, "e": 26755, "s": 26745, "text": "Recursion" }, { "code": null, "e": 26853, "s": 26755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26888, "s": 26853, "text": "Read a file line by line in Python" }, { "code": null, "e": 26920, "s": 26888, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26942, "s": 26920, "text": "Enumerate() in Python" }, { "code": null, "e": 26984, "s": 26942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27014, "s": 26984, "text": "Iterate over a list in Python" }, { "code": null, "e": 27074, "s": 27014, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27159, "s": 27074, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 27169, "s": 27159, "text": "Recursion" }, { "code": null, "e": 27196, "s": 27169, "text": "Program for Tower of Hanoi" } ]
C | Functions | Question 9 - GeeksforGeeks
28 Jun, 2021 What is the meaning of using static before function declaration? For example following function sum is made static static int sum(int x, int y, int z) { return (x + y + z); } (A) Static means nothing, sum() is same without static keyword.(B) Function need not to be declared before its use(C) Access to static functions is restricted to the file where they are declared(D) Static functions are made inlineAnswer: (C)Explanation: In C, functions are global by default. Unlike global functions, access to static functions is restricted to the file where they are declared. We can have file level encapsulation using static variables/functions in C because when we make a global variable static, access to the variable becomes limited to the file in which it is declared.Quiz of this Question C-Functions Functions C Language C Quiz Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Arrays | Question 7 C | Misc | Question 7
[ { "code": null, "e": 25694, "s": 25666, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25759, "s": 25694, "text": "What is the meaning of using static before function declaration?" }, { "code": null, "e": 25809, "s": 25759, "text": "For example following function sum is made static" }, { "code": null, "e": 25873, "s": 25809, "text": "static int sum(int x, int y, int z)\n{\n return (x + y + z);\n}" }, { "code": null, "e": 26488, "s": 25873, "text": "(A) Static means nothing, sum() is same without static keyword.(B) Function need not to be declared before its use(C) Access to static functions is restricted to the file where they are declared(D) Static functions are made inlineAnswer: (C)Explanation: In C, functions are global by default. Unlike global functions, access to static functions is restricted to the file where they are declared. We can have file level encapsulation using static variables/functions in C because when we make a global variable static, access to the variable becomes limited to the file in which it is declared.Quiz of this Question" }, { "code": null, "e": 26500, "s": 26488, "text": "C-Functions" }, { "code": null, "e": 26510, "s": 26500, "text": "Functions" }, { "code": null, "e": 26521, "s": 26510, "text": "C Language" }, { "code": null, "e": 26528, "s": 26521, "text": "C Quiz" }, { "code": null, "e": 26538, "s": 26528, "text": "Functions" }, { "code": null, "e": 26636, "s": 26538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26658, "s": 26636, "text": "Function Pointer in C" }, { "code": null, "e": 26670, "s": 26658, "text": "fork() in C" }, { "code": null, "e": 26695, "s": 26670, "text": "std::string class in C++" }, { "code": null, "e": 26722, "s": 26695, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 26754, "s": 26722, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26796, "s": 26754, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 26839, "s": 26796, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 26870, "s": 26839, "text": "C | File Handling | Question 1" }, { "code": null, "e": 26894, "s": 26870, "text": "C | Arrays | Question 7" } ]
Kali Linux - Cisco-Torch Tool - GeeksforGeeks
01 Feb, 2021 Cisco-Torch is one of the best penetration testing and scanning tool. It is a mass scanning and exploitation tool. Which was written while working on the edition of “Hacking Exposed Cisco Networks”. Installation: It comes pre-installed in Kali-Linux but if not then just type the given command in the terminal box. sudo apt-get install cisco-torch To get the summary of parameters and attributes of the command use the following command: cisco-torch -h 1. Using cisco-torch to run all fingerprint and scan types against the desired host: cisco-torch -A 192.168.43.184 2. We can also use cisco-torch to scan an entire network or subnet: cisco-torch -A 10.1.1.0/24 3. Using cisco-torch to run a dictionary attack against the host: cisco-torch -t -b 10.1.1.54 Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n01 Feb, 2021" }, { "code": null, "e": 25850, "s": 25651, "text": "Cisco-Torch is one of the best penetration testing and scanning tool. It is a mass scanning and exploitation tool. Which was written while working on the edition of “Hacking Exposed Cisco Networks”." }, { "code": null, "e": 25966, "s": 25850, "text": "Installation: It comes pre-installed in Kali-Linux but if not then just type the given command in the terminal box." }, { "code": null, "e": 25999, "s": 25966, "text": "sudo apt-get install cisco-torch" }, { "code": null, "e": 26089, "s": 25999, "text": "To get the summary of parameters and attributes of the command use the following command:" }, { "code": null, "e": 26104, "s": 26089, "text": "cisco-torch -h" }, { "code": null, "e": 26189, "s": 26104, "text": "1. Using cisco-torch to run all fingerprint and scan types against the desired host:" }, { "code": null, "e": 26219, "s": 26189, "text": "cisco-torch -A 192.168.43.184" }, { "code": null, "e": 26287, "s": 26219, "text": "2. We can also use cisco-torch to scan an entire network or subnet:" }, { "code": null, "e": 26314, "s": 26287, "text": "cisco-torch -A 10.1.1.0/24" }, { "code": null, "e": 26380, "s": 26314, "text": "3. Using cisco-torch to run a dictionary attack against the host:" }, { "code": null, "e": 26408, "s": 26380, "text": "cisco-torch -t -b 10.1.1.54" }, { "code": null, "e": 26419, "s": 26408, "text": "Kali-Linux" }, { "code": null, "e": 26431, "s": 26419, "text": "Linux-Tools" }, { "code": null, "e": 26442, "s": 26431, "text": "Linux-Unix" }, { "code": null, "e": 26540, "s": 26442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26575, "s": 26540, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26609, "s": 26575, "text": "mv command in Linux with examples" }, { "code": null, "e": 26635, "s": 26609, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26664, "s": 26635, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26701, "s": 26664, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26738, "s": 26701, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26780, "s": 26738, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 26806, "s": 26780, "text": "Thread functions in C/C++" }, { "code": null, "e": 26842, "s": 26806, "text": "uniq Command in LINUX with examples" } ]
Bubble Sort | Practice | GeeksforGeeks
Given an Integer N and a list arr. Sort the array using bubble sort algorithm. Example 1: Input: N = 5 arr[] = {4, 1, 3, 9, 7} Output: 1 3 4 7 9 Example 2: Input: N = 10 arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} Output: 1 2 3 4 5 6 7 8 9 10 Constraints: 1 <= N <= 103 1 <= arr[i] <= 103 0 akasksingh08016 hours ago JAVA: class Solution { //Function to sort the array using bubble sort algorithm. public static void bubbleSort(int arr[], int n) { //code here for(int i=0;i<n;i++) { boolean swapped =false; for(int j=0;j<n-i-1;j++) { if(arr[j]>arr[j+1]) { // swapping int temp = arr[j]; arr[j] =arr[j+1]; arr[j+1]= temp; swapped = true; } } if(swapped == false) break; } } } +1 billasaketh20 hours ago Here we sort the array using bubble sort First we declare a int variable flag to break the loop if the array is already sorted. Then we traverse through the array comparing and swapping if the first element is bigger than next element. The Time Complexity: 1+2+3+....+n-1 i.e. n(n-1)/2 i.e O(n^2) void bubbleSort(int arr[], int n){ // Your code here int flag=0; for(int i=0;i<n-1;i++){ for(int j=0;j<n-1-i;j++){ if(arr[j]>arr[j+1]){ int temp= arr[j]; arr[j] = arr[j+1]; arr[j+1]=temp; flag=1; } } if(flag==0){ break; } }} 0 ronisarkar22441 week ago int count=1,f,temp; while(count<n){ f=0; for(int i=0; i<n-count;i++){ if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; f=1; } } count++; if(f==0){ break; } } 0 rakeshsinghbanjara8811 week ago void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(arr[j]>arr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } } 0 ravi119033852 weeks ago //Java Solution class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for( int i = 0; i < n-1; i++){ boolean swapped = false; for( int j = 0; j < n-i-1; j++){ if(arr[j] > arr[j + 1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; swapped = true; } } if(swapped == false) break; } }} 0 visionsameer393 weeks ago python class Solution: def bubbleSort(self,arr, n): return arr.sort() 0 harshilrpanchal19983 weeks ago class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for(int i= 0 ; i < n -1 ; i++){ for(int j=0 ; j < n-i-1 ; j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }} 0 mitrasouvik1233 weeks ago class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { int temp=0; n=arr.length; for(int i = 0; i<n; i++) { boolean isSwapped = false; for(int j=1; j<(n-i); j++) { if(arr[j-1]>arr[j]) { temp = arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; isSwapped = true; } } if(!isSwapped) { break; } } }} +1 sangrambachu3 weeks ago Some cases it'll have O(n) Time complexity because of isSwapped flag. class Solution { //Function to sort the array using bubble sort algorithm. public static void bubbleSort(int arr[], int n) { //code here for(int i=0; i<n; i++) { boolean isSwapped = false; for(int j=0; j<n-i-1; j++) { if(arr[j+1] < arr[j]) { int temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; isSwapped = true; } } if(!isSwapped) { break; } } } } 0 rohankundu8593 weeks ago //C++ Solution void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } //Function to sort the array using bubble sort algorithm. void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n;i++) { for(int j=0;j<(n-i-1);j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } } } } 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.
[ { "code": null, "e": 328, "s": 238, "text": "Given an Integer N and a list arr. Sort the array using bubble sort algorithm.\nExample 1:" }, { "code": null, "e": 386, "s": 328, "text": "Input: \nN = 5\narr[] = {4, 1, 3, 9, 7}\nOutput: \n1 3 4 7 9\n" }, { "code": null, "e": 397, "s": 386, "text": "Example 2:" }, { "code": null, "e": 483, "s": 397, "text": "Input:\nN = 10 \narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput: \n1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 530, "s": 483, "text": "\nConstraints:\n1 <= N <= 103\n1 <= arr[i] <= 103" }, { "code": null, "e": 532, "s": 530, "text": "0" }, { "code": null, "e": 558, "s": 532, "text": "akasksingh08016 hours ago" }, { "code": null, "e": 1182, "s": 558, "text": "JAVA:\n\nclass Solution\n{\n //Function to sort the array using bubble sort algorithm.\n\tpublic static void bubbleSort(int arr[], int n)\n {\n //code here\n for(int i=0;i<n;i++)\n {\n boolean swapped =false;\n for(int j=0;j<n-i-1;j++)\n {\n if(arr[j]>arr[j+1])\n {\n // swapping\n int temp = arr[j];\n arr[j] =arr[j+1];\n arr[j+1]= temp;\n swapped = true;\n }\n }\n if(swapped == false)\n break;\n }\n }\n}\n" }, { "code": null, "e": 1185, "s": 1182, "text": "+1" }, { "code": null, "e": 1209, "s": 1185, "text": "billasaketh20 hours ago" }, { "code": null, "e": 1250, "s": 1209, "text": "Here we sort the array using bubble sort" }, { "code": null, "e": 1338, "s": 1250, "text": "First we declare a int variable flag to break the loop if the array is already sorted." }, { "code": null, "e": 1446, "s": 1338, "text": "Then we traverse through the array comparing and swapping if the first element is bigger than next element." }, { "code": null, "e": 1507, "s": 1446, "text": "The Time Complexity: 1+2+3+....+n-1 i.e. n(n-1)/2 i.e O(n^2)" }, { "code": null, "e": 1856, "s": 1511, "text": "void bubbleSort(int arr[], int n){ // Your code here int flag=0; for(int i=0;i<n-1;i++){ for(int j=0;j<n-1-i;j++){ if(arr[j]>arr[j+1]){ int temp= arr[j]; arr[j] = arr[j+1]; arr[j+1]=temp; flag=1; } } if(flag==0){ break; } }}" }, { "code": null, "e": 1858, "s": 1856, "text": "0" }, { "code": null, "e": 1883, "s": 1858, "text": "ronisarkar22441 week ago" }, { "code": null, "e": 2184, "s": 1883, "text": "int count=1,f,temp; while(count<n){ f=0; for(int i=0; i<n-count;i++){ if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; f=1; } } count++; if(f==0){ break; } }" }, { "code": null, "e": 2186, "s": 2184, "text": "0" }, { "code": null, "e": 2218, "s": 2186, "text": "rakeshsinghbanjara8811 week ago" }, { "code": null, "e": 2564, "s": 2218, "text": "void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(arr[j]>arr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } }" }, { "code": null, "e": 2566, "s": 2564, "text": "0" }, { "code": null, "e": 2590, "s": 2566, "text": "ravi119033852 weeks ago" }, { "code": null, "e": 2607, "s": 2590, "text": "//Java Solution " }, { "code": null, "e": 3229, "s": 2609, "text": "class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for( int i = 0; i < n-1; i++){ boolean swapped = false; for( int j = 0; j < n-i-1; j++){ if(arr[j] > arr[j + 1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; swapped = true; } } if(swapped == false) break; } }}" }, { "code": null, "e": 3231, "s": 3229, "text": "0" }, { "code": null, "e": 3257, "s": 3231, "text": "visionsameer393 weeks ago" }, { "code": null, "e": 3264, "s": 3257, "text": "python" }, { "code": null, "e": 3341, "s": 3266, "text": "class Solution: def bubbleSort(self,arr, n): return arr.sort() " }, { "code": null, "e": 3343, "s": 3341, "text": "0" }, { "code": null, "e": 3374, "s": 3343, "text": "harshilrpanchal19983 weeks ago" }, { "code": null, "e": 3786, "s": 3374, "text": "class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { //code here for(int i= 0 ; i < n -1 ; i++){ for(int j=0 ; j < n-i-1 ; j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }}" }, { "code": null, "e": 3788, "s": 3786, "text": "0" }, { "code": null, "e": 3814, "s": 3788, "text": "mitrasouvik1233 weeks ago" }, { "code": null, "e": 4398, "s": 3814, "text": "class Solution{ //Function to sort the array using bubble sort algorithm.public static void bubbleSort(int arr[], int n) { int temp=0; n=arr.length; for(int i = 0; i<n; i++) { boolean isSwapped = false; for(int j=1; j<(n-i); j++) { if(arr[j-1]>arr[j]) { temp = arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; isSwapped = true; } } if(!isSwapped) { break; } } }}" }, { "code": null, "e": 4401, "s": 4398, "text": "+1" }, { "code": null, "e": 4425, "s": 4401, "text": "sangrambachu3 weeks ago" }, { "code": null, "e": 4495, "s": 4425, "text": "Some cases it'll have O(n) Time complexity because of isSwapped flag." }, { "code": null, "e": 5086, "s": 4497, "text": "class Solution\n{\n //Function to sort the array using bubble sort algorithm.\n\tpublic static void bubbleSort(int arr[], int n)\n {\n //code here\n for(int i=0; i<n; i++) {\n boolean isSwapped = false;\n for(int j=0; j<n-i-1; j++) {\n if(arr[j+1] < arr[j]) {\n int temp = arr[j+1];\n arr[j+1] = arr[j];\n arr[j] = temp;\n isSwapped = true;\n }\n }\n \n if(!isSwapped) {\n break;\n }\n }\n }\n}" }, { "code": null, "e": 5088, "s": 5086, "text": "0" }, { "code": null, "e": 5113, "s": 5088, "text": "rohankundu8593 weeks ago" }, { "code": null, "e": 5128, "s": 5113, "text": "//C++ Solution" }, { "code": null, "e": 5555, "s": 5130, "text": " void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } //Function to sort the array using bubble sort algorithm. void bubbleSort(int arr[], int n) { // Your code here for(int i=0;i<n;i++) { for(int j=0;j<(n-i-1);j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } } } }" }, { "code": null, "e": 5701, "s": 5555, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5737, "s": 5701, "text": " Login to access your submissions. " }, { "code": null, "e": 5747, "s": 5737, "text": "\nProblem\n" }, { "code": null, "e": 5757, "s": 5747, "text": "\nContest\n" }, { "code": null, "e": 5820, "s": 5757, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5968, "s": 5820, "text": "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." }, { "code": null, "e": 6176, "s": 5968, "text": "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." }, { "code": null, "e": 6282, "s": 6176, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Replace every array element by multiplication of previous and next - GeeksforGeeks
08 Mar, 2022 Given an array of integers, update every element with multiplication of previous and next elements with following exceptions. a) First element is replaced by multiplication of first and second. b) Last element is replaced by multiplication of last and second last. Example: Input: arr[] = {2, 3, 4, 5, 6} Output: arr[] = {6, 8, 15, 24, 30} // We get the above output using following // arr[] = {2*3, 2*4, 3*5, 4*6, 5*6} Source: Top 25 Interview QuestionsA Simple Solution is to create an auxiliary array, copy contents of given array to auxiliary array. Finally traverse the auxiliary array and update given array using copied values. Time complexity of this solution is O(n), but it requires O(n) extra space.An efficient solution can solve the problem in O(n) time and O(1) space. The idea is to keep track of previous element in loop. Below is the implementation of this idea. C++ Java Python3 C# PHP Javascript // C++ program to update every array element with// multiplication of previous and next numbers in array#include<iostream>using namespace std; void modify(int arr[], int n){ // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1];} // Driver programint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); modify(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;} // Java program to update every array element with// multiplication of previous and next numbers in arrayimport java.io.*;import java.util.*;import java.lang.Math; class Multiply{ static void modify(int arr[], int n) { // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1]; } // Driver program to test above function public static void main(String[] args) { int arr[] = {2, 3, 4, 5, 6}; int n = arr.length; modify(arr, n); for (int i=0; i<n; i++) System.out.print(arr[i]+" "); }}/* This code is contributed by Devesh Agrawal */ # Python program to update every array element with# multiplication of previous and next numbers in array def modify(arr, n): # Nothing to do when array size is 1 if n <= 1: return # store current value of arr[0] and update it prev = arr[0] arr[0] = arr[0] * arr[1] # Update rest of the array elements for i in range(1, n-1): # Store current value of next interaction curr = arr[i]; # Update current value using previous value arr[i] = prev * arr[i+1] # Update previous value prev = curr # Update last array element arr[n-1] = prev * arr[n-1] # Driver programarr = [2, 3, 4, 5, 6]n = len(arr)modify(arr, n)for i in range (0, n): print(arr[i],end=" ") # This code is contributed by# Smitha Dinesh Semwal // C# program to update every array// element with multiplication of// previous and next numbers in arrayusing System; class GFG{ static void modify(int []arr, int n) { // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1]; } // Driver program to test above function public static void Main() { int []arr = {2, 3, 4, 5, 6}; int n = arr.Length; modify(arr, n); for (int i=0; i<n; i++) Console.Write(arr[i]+" "); }} // This code is contributed by Sam007 <?php// PHP program to update every array// element with multiplication of previous// and next numbers in array function modify(&$arr, $n){ // Nothing to do when array size is 1 if ($n <= 1) return; // store current value of arr[0] // and update it $prev = $arr[0]; $arr[0] = $arr[0] * $arr[1]; // Update rest of the array elements for ($i = 1; $i < $n - 1; $i++) { // Store current value of // next interaction $curr = $arr[$i]; // Update current value using // previous value $arr[$i] = $prev * $arr[$i + 1]; // Update previous value $prev = $curr; } // Update last array element $arr[$n-1] = $prev * $arr[$n - 1];} // Driver Code$arr = array (2, 3, 4, 5, 6);$n = sizeof($arr);modify($arr, $n);for ($i = 0; $i < $n; $i++)echo $arr[$i] ." "; // This code is contributed// by ChitraNayal?> <script>// Javascript program to update every array element with// multiplication of previous and next numbers in array function modify(arr, n){ // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it let prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (let i = 1; i < n - 1; i++) { // Store current value of next interaction let curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1];} // Driver programlet arr = [2, 3, 4, 5, 6];let n = arr.length;modify(arr, n);for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by subham348.</script> Output: 6 8 15 24 30 This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 ukasp subham348 simmytarika5 varshagumber28 germanshephered48 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Program for array rotation Largest Sum Contiguous Subarray Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 42519, "s": 42491, "text": "\n08 Mar, 2022" }, { "code": null, "e": 42784, "s": 42519, "text": "Given an array of integers, update every element with multiplication of previous and next elements with following exceptions. a) First element is replaced by multiplication of first and second. b) Last element is replaced by multiplication of last and second last." }, { "code": null, "e": 42795, "s": 42784, "text": "Example: " }, { "code": null, "e": 42943, "s": 42795, "text": "Input: arr[] = {2, 3, 4, 5, 6}\nOutput: arr[] = {6, 8, 15, 24, 30}\n\n// We get the above output using following\n// arr[] = {2*3, 2*4, 3*5, 4*6, 5*6} " }, { "code": null, "e": 43362, "s": 42943, "text": "Source: Top 25 Interview QuestionsA Simple Solution is to create an auxiliary array, copy contents of given array to auxiliary array. Finally traverse the auxiliary array and update given array using copied values. Time complexity of this solution is O(n), but it requires O(n) extra space.An efficient solution can solve the problem in O(n) time and O(1) space. The idea is to keep track of previous element in loop. " }, { "code": null, "e": 43405, "s": 43362, "text": "Below is the implementation of this idea. " }, { "code": null, "e": 43409, "s": 43405, "text": "C++" }, { "code": null, "e": 43414, "s": 43409, "text": "Java" }, { "code": null, "e": 43422, "s": 43414, "text": "Python3" }, { "code": null, "e": 43425, "s": 43422, "text": "C#" }, { "code": null, "e": 43429, "s": 43425, "text": "PHP" }, { "code": null, "e": 43440, "s": 43429, "text": "Javascript" }, { "code": "// C++ program to update every array element with// multiplication of previous and next numbers in array#include<iostream>using namespace std; void modify(int arr[], int n){ // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1];} // Driver programint main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); modify(arr, n); for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 44333, "s": 43440, "text": null }, { "code": "// Java program to update every array element with// multiplication of previous and next numbers in arrayimport java.io.*;import java.util.*;import java.lang.Math; class Multiply{ static void modify(int arr[], int n) { // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1]; } // Driver program to test above function public static void main(String[] args) { int arr[] = {2, 3, 4, 5, 6}; int n = arr.length; modify(arr, n); for (int i=0; i<n; i++) System.out.print(arr[i]+\" \"); }}/* This code is contributed by Devesh Agrawal */", "e": 45467, "s": 44333, "text": null }, { "code": "# Python program to update every array element with# multiplication of previous and next numbers in array def modify(arr, n): # Nothing to do when array size is 1 if n <= 1: return # store current value of arr[0] and update it prev = arr[0] arr[0] = arr[0] * arr[1] # Update rest of the array elements for i in range(1, n-1): # Store current value of next interaction curr = arr[i]; # Update current value using previous value arr[i] = prev * arr[i+1] # Update previous value prev = curr # Update last array element arr[n-1] = prev * arr[n-1] # Driver programarr = [2, 3, 4, 5, 6]n = len(arr)modify(arr, n)for i in range (0, n): print(arr[i],end=\" \") # This code is contributed by# Smitha Dinesh Semwal", "e": 46266, "s": 45467, "text": null }, { "code": "// C# program to update every array// element with multiplication of// previous and next numbers in arrayusing System; class GFG{ static void modify(int []arr, int n) { // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i<n-1; i++) { // Store current value of next interaction int curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1]; } // Driver program to test above function public static void Main() { int []arr = {2, 3, 4, 5, 6}; int n = arr.Length; modify(arr, n); for (int i=0; i<n; i++) Console.Write(arr[i]+\" \"); }} // This code is contributed by Sam007", "e": 47324, "s": 46266, "text": null }, { "code": "<?php// PHP program to update every array// element with multiplication of previous// and next numbers in array function modify(&$arr, $n){ // Nothing to do when array size is 1 if ($n <= 1) return; // store current value of arr[0] // and update it $prev = $arr[0]; $arr[0] = $arr[0] * $arr[1]; // Update rest of the array elements for ($i = 1; $i < $n - 1; $i++) { // Store current value of // next interaction $curr = $arr[$i]; // Update current value using // previous value $arr[$i] = $prev * $arr[$i + 1]; // Update previous value $prev = $curr; } // Update last array element $arr[$n-1] = $prev * $arr[$n - 1];} // Driver Code$arr = array (2, 3, 4, 5, 6);$n = sizeof($arr);modify($arr, $n);for ($i = 0; $i < $n; $i++)echo $arr[$i] .\" \"; // This code is contributed// by ChitraNayal?>", "e": 48214, "s": 47324, "text": null }, { "code": "<script>// Javascript program to update every array element with// multiplication of previous and next numbers in array function modify(arr, n){ // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it let prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (let i = 1; i < n - 1; i++) { // Store current value of next interaction let curr = arr[i]; // Update current value using previous value arr[i] = prev * arr[i+1]; // Update previous value prev = curr; } // Update last array element arr[n-1] = prev * arr[n-1];} // Driver programlet arr = [2, 3, 4, 5, 6];let n = arr.length;modify(arr, n);for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by subham348.</script>", "e": 49089, "s": 48214, "text": null }, { "code": null, "e": 49098, "s": 49089, "text": "Output: " }, { "code": null, "e": 49111, "s": 49098, "text": "6 8 15 24 30" }, { "code": null, "e": 49273, "s": 49111, "text": "This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 49280, "s": 49273, "text": "Sam007" }, { "code": null, "e": 49286, "s": 49280, "text": "ukasp" }, { "code": null, "e": 49296, "s": 49286, "text": "subham348" }, { "code": null, "e": 49309, "s": 49296, "text": "simmytarika5" }, { "code": null, "e": 49324, "s": 49309, "text": "varshagumber28" }, { "code": null, "e": 49342, "s": 49324, "text": "germanshephered48" }, { "code": null, "e": 49349, "s": 49342, "text": "Arrays" }, { "code": null, "e": 49356, "s": 49349, "text": "Arrays" }, { "code": null, "e": 49454, "s": 49356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49469, "s": 49454, "text": "Arrays in Java" }, { "code": null, "e": 49485, "s": 49469, "text": "Arrays in C/C++" }, { "code": null, "e": 49531, "s": 49485, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 49558, "s": 49531, "text": "Program for array rotation" }, { "code": null, "e": 49590, "s": 49558, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 49634, "s": 49590, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 49682, "s": 49634, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 49705, "s": 49682, "text": "Introduction to Arrays" } ]
Map Values() Method in Java With Examples - GeeksforGeeks
10 Sep, 2020 Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. Syntax: map.values() Parameter: This method does not take any parameter. Return value: It returns a collection view of all the values present in the map. Example 1: Java // Java program to illustrate the// use of Map.Values() Methodimport java.util.*; public class GfG { // Main Method public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<Integer, String>(); map.put(12345, "student 1"); map.put(22345, "student 2"); map.put(323456, "student 3"); map.put(32496, "student 4"); map.put(32446, "student 5"); map.put(32456, "student 6"); System.out.println(map.values()); }} Output: [student 4, student 3, student 6, student 1, student 2, student 5] As you can see, the output of the above example is returning a collection view of values. So any change in the map will be reflected in the collection view automatically. So always take the generic of collection same as the generic of the values of the map otherwise it will give an error. Example 2: Java // Java program to illustrate the// use of Map.Values() Methodimport java.util.*; public class GfG { // Main Method public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<Integer, String>(); map.put(12345, "student 1"); map.put(22345, "student 2"); map.put(323456, "student 3"); map.put(32496, "student 4"); map.put(32446, "student 5"); map.put(32456, "student 6"); Collection<String> collectionValues = map.values(); System.out.println("<------OutPut before modification------>\n"); for(String s: collectionValues){ System.out.println(s); } map.put(3245596, "student 7"); System.out.println("\n<------OutPut after modification------>\n"); for(String s: collectionValues){ System.out.println(s); } }} Output: <------OutPut before modification------> student 4 student 3 student 6 student 1 student 2 student 5 <------OutPut after modification------> student 4 student 3 student 6 student 1 student 2 student 7 student 5 Java-Collections Java-Functions java-map Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Initializing a List in Java Overriding in Java
[ { "code": null, "e": 25449, "s": 25421, "text": "\n10 Sep, 2020" }, { "code": null, "e": 25643, "s": 25449, "text": "Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. " }, { "code": null, "e": 25651, "s": 25643, "text": "Syntax:" }, { "code": null, "e": 25664, "s": 25651, "text": "map.values()" }, { "code": null, "e": 25716, "s": 25664, "text": "Parameter: This method does not take any parameter." }, { "code": null, "e": 25797, "s": 25716, "text": "Return value: It returns a collection view of all the values present in the map." }, { "code": null, "e": 25808, "s": 25797, "text": "Example 1:" }, { "code": null, "e": 25813, "s": 25808, "text": "Java" }, { "code": "// Java program to illustrate the// use of Map.Values() Methodimport java.util.*; public class GfG { // Main Method public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<Integer, String>(); map.put(12345, \"student 1\"); map.put(22345, \"student 2\"); map.put(323456, \"student 3\"); map.put(32496, \"student 4\"); map.put(32446, \"student 5\"); map.put(32456, \"student 6\"); System.out.println(map.values()); }}", "e": 26375, "s": 25813, "text": null }, { "code": null, "e": 26385, "s": 26377, "text": "Output:" }, { "code": null, "e": 26452, "s": 26385, "text": "[student 4, student 3, student 6, student 1, student 2, student 5]" }, { "code": null, "e": 26742, "s": 26452, "text": "As you can see, the output of the above example is returning a collection view of values. So any change in the map will be reflected in the collection view automatically. So always take the generic of collection same as the generic of the values of the map otherwise it will give an error." }, { "code": null, "e": 26753, "s": 26742, "text": "Example 2:" }, { "code": null, "e": 26758, "s": 26753, "text": "Java" }, { "code": "// Java program to illustrate the// use of Map.Values() Methodimport java.util.*; public class GfG { // Main Method public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<Integer, String>(); map.put(12345, \"student 1\"); map.put(22345, \"student 2\"); map.put(323456, \"student 3\"); map.put(32496, \"student 4\"); map.put(32446, \"student 5\"); map.put(32456, \"student 6\"); Collection<String> collectionValues = map.values(); System.out.println(\"<------OutPut before modification------>\\n\"); for(String s: collectionValues){ System.out.println(s); } map.put(3245596, \"student 7\"); System.out.println(\"\\n<------OutPut after modification------>\\n\"); for(String s: collectionValues){ System.out.println(s); } }}", "e": 27716, "s": 26758, "text": null }, { "code": null, "e": 27724, "s": 27716, "text": "Output:" }, { "code": null, "e": 27938, "s": 27724, "text": "<------OutPut before modification------>\n\nstudent 4\nstudent 3\nstudent 6\nstudent 1\nstudent 2\nstudent 5\n\n<------OutPut after modification------>\n\nstudent 4\nstudent 3\nstudent 6\nstudent 1\nstudent 2\nstudent 7\nstudent 5" }, { "code": null, "e": 27955, "s": 27938, "text": "Java-Collections" }, { "code": null, "e": 27970, "s": 27955, "text": "Java-Functions" }, { "code": null, "e": 27979, "s": 27970, "text": "java-map" }, { "code": null, "e": 27984, "s": 27979, "text": "Java" }, { "code": null, "e": 27989, "s": 27984, "text": "Java" }, { "code": null, "e": 28006, "s": 27989, "text": "Java-Collections" }, { "code": null, "e": 28104, "s": 28006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28119, "s": 28104, "text": "Stream In Java" }, { "code": null, "e": 28138, "s": 28119, "text": "Interfaces in Java" }, { "code": null, "e": 28156, "s": 28138, "text": "ArrayList in Java" }, { "code": null, "e": 28176, "s": 28156, "text": "Stack Class in Java" }, { "code": null, "e": 28200, "s": 28176, "text": "Singleton Class in Java" }, { "code": null, "e": 28232, "s": 28200, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28255, "s": 28232, "text": "Multithreading in Java" }, { "code": null, "e": 28275, "s": 28255, "text": "Collections in Java" }, { "code": null, "e": 28303, "s": 28275, "text": "Initializing a List in Java" } ]
Java Program to convert LocalDateTime to LocalDate and LocalTime
At first set a LocalDateTime: LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.of(date, time); Now, convert the LocalDateTime to LocalDate and LocalTime: LocalDate localDate = LocalDateTime.now().toLocalDate(); LocalTime localTime = LocalDateTime.now().toLocalTime(); import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class Demo { public static void main(String[] args) { LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.of(date, time); System.out.println("DateTime = "+dateTime); LocalDate localDate = LocalDateTime.now().toLocalDate(); LocalTime localTime = LocalDateTime.now().toLocalTime(); System.out.println("Date = "+localDate); System.out.println("Time = "+localTime); } } DateTime = 2019-04-18T13:57:22.591327100 Date = 2019-04-18 Time = 13:57:22.591327100
[ { "code": null, "e": 1092, "s": 1062, "text": "At first set a LocalDateTime:" }, { "code": null, "e": 1215, "s": 1092, "text": "LocalDate date = LocalDate.now();\nLocalTime time = LocalTime.now();\nLocalDateTime dateTime = LocalDateTime.of(date, time);" }, { "code": null, "e": 1274, "s": 1215, "text": "Now, convert the LocalDateTime to LocalDate and LocalTime:" }, { "code": null, "e": 1388, "s": 1274, "text": "LocalDate localDate = LocalDateTime.now().toLocalDate();\nLocalTime localTime = LocalDateTime.now().toLocalTime();" }, { "code": null, "e": 1958, "s": 1388, "text": "import java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate date = LocalDate.now();\n LocalTime time = LocalTime.now();\n LocalDateTime dateTime = LocalDateTime.of(date, time);\n System.out.println(\"DateTime = \"+dateTime);\n LocalDate localDate = LocalDateTime.now().toLocalDate();\n LocalTime localTime = LocalDateTime.now().toLocalTime();\n System.out.println(\"Date = \"+localDate);\n System.out.println(\"Time = \"+localTime);\n }\n}" }, { "code": null, "e": 2043, "s": 1958, "text": "DateTime = 2019-04-18T13:57:22.591327100\nDate = 2019-04-18\nTime = 13:57:22.591327100" } ]
Apex - Security
Apex security refers to the process of applying security settings and enforcing the sharing rules on running code. Apex classes have security setting that can be controlled via two keywords. Apex generally runs in system context, that is, the current user's permissions. Field-level security, and sharing rules are not taken into account during code execution. Only the anonymous block code executes with the permission of the user who is executing the code. Our Apex code should not expose the sensitive data to User which is hidden via security and sharing settings. Hence, Apex security and enforcing the sharing rule is most important. If you use this keyword, then the Apex code will enforce the Sharing settings of current user to Apex code. This does not enforce the Profile permission, only the data level sharing settings. Let us consider an example wherein, our User has access to 5 records, but the total number of records is 10. So when the Apex class will be declared with the "With Sharing" Keyword, it will return only 5 records on which the user has access to. Example First, make sure that you have created at least 10 records in the Customer object with 'Name' of 5 records as 'ABC Customer' and rest 5 records as 'XYZ Customer'. Then, create a sharing rule which will share the 'ABC Customer' with all Users. We also need to make sure that we have set the OWD of Customer object as Private. Paste the code given below to Anonymous block in the Developer Console. // Class With Sharing public with sharing class MyClassWithSharing { // Query To fetch 10 records List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10]; public Integer executeQuery () { System.debug('List will have only 5 records and the actual records are' + CustomerList.size()+' as user has access to'+CustomerList); Integer ListSize = CustomerList.size(); return ListSize; } } // Save the above class and then execute as below // Execute class using the object of class MyClassWithSharing obj = new MyClassWithSharing(); Integer ListSize = obj.executeQuery(); As the name suggests, class declared with this keyword executes in System mode, i.e., irrespective of the User's access to the record, query will fetch all the records. // Class Without Sharing public without sharing class MyClassWithoutSharing { List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10]; // Query To fetch 10 records, this will return all the records public Integer executeQuery () { System.debug('List will have only 5 records and the actula records are' + CustomerList.size()+' as user has access to'+CustomerList); Integer ListSize = CustomerList.size(); return ListSize; } } // Output will be 10 records. You can enable or disable an Apex class for particular profile. The steps for the same are given below. You can determine which profile should have access to which class. Step 1 − From Setup, click Develop → Apex Classes. Step 2 − Click the name of the class that you want to restrict. We have clicked on CustomerOperationClass. Step 3 − Click on Security. Step 4 − Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click on Remove. Step 5 − Click on Save. Step 1 − From Setup, click Manage Users → Permission Sets. Step 2 − Select a permission set. Step 3 − Click on Apex Class Access. Step 4 − Click on Edit. Step 5 − Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click remove. Step 6 − Click the Save button. 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2243, "s": 2052, "text": "Apex security refers to the process of applying security settings and enforcing the sharing rules on running code. Apex classes have security setting that can be controlled via two keywords." }, { "code": null, "e": 2511, "s": 2243, "text": "Apex generally runs in system context, that is, the current user's permissions. Field-level security, and sharing rules are not taken into account during code execution. Only the anonymous block code executes with the permission of the user who is executing the code." }, { "code": null, "e": 2692, "s": 2511, "text": "Our Apex code should not expose the sensitive data to User which is hidden via security and sharing settings. Hence, Apex security and enforcing the sharing rule is most important." }, { "code": null, "e": 2884, "s": 2692, "text": "If you use this keyword, then the Apex code will enforce the Sharing settings of current user to Apex code. This does not enforce the Profile permission, only the data level sharing settings." }, { "code": null, "e": 3129, "s": 2884, "text": "Let us consider an example wherein, our User has access to 5 records, but the total number of records is 10. So when the Apex class will be declared with the \"With Sharing\" Keyword, it will return only 5 records on which the user has access to." }, { "code": null, "e": 3137, "s": 3129, "text": "Example" }, { "code": null, "e": 3462, "s": 3137, "text": "First, make sure that you have created at least 10 records in the Customer object with 'Name' of 5 records as 'ABC Customer' and rest 5 records as 'XYZ Customer'. Then, create a sharing rule which will share the 'ABC Customer' with all Users. We also need to make sure that we have set the OWD of Customer object as Private." }, { "code": null, "e": 3534, "s": 3462, "text": "Paste the code given below to Anonymous block in the Developer Console." }, { "code": null, "e": 4176, "s": 3534, "text": "// Class With Sharing\npublic with sharing class MyClassWithSharing {\n // Query To fetch 10 records\n List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];\n \n public Integer executeQuery () {\n System.debug('List will have only 5 records and the actual records are' \n + CustomerList.size()+' as user has access to'+CustomerList);\n Integer ListSize = CustomerList.size();\n return ListSize;\n }\n}\n\n// Save the above class and then execute as below\n// Execute class using the object of class\nMyClassWithSharing obj = new MyClassWithSharing();\nInteger ListSize = obj.executeQuery();" }, { "code": null, "e": 4345, "s": 4176, "text": "As the name suggests, class declared with this keyword executes in System mode, i.e., irrespective of the User's access to the record, query will fetch all the records." }, { "code": null, "e": 4875, "s": 4345, "text": "// Class Without Sharing\npublic without sharing class MyClassWithoutSharing {\n List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];\n \n // Query To fetch 10 records, this will return all the records\n public Integer executeQuery () {\n System.debug('List will have only 5 records and the actula records are'\n + CustomerList.size()+' as user has access to'+CustomerList);\n Integer ListSize = CustomerList.size();\n return ListSize;\n }\n}\n// Output will be 10 records." }, { "code": null, "e": 5046, "s": 4875, "text": "You can enable or disable an Apex class for particular profile. The steps for the same are given below. You can determine which profile should have access to which class." }, { "code": null, "e": 5097, "s": 5046, "text": "Step 1 − From Setup, click Develop → Apex Classes." }, { "code": null, "e": 5204, "s": 5097, "text": "Step 2 − Click the name of the class that you want to restrict. We have clicked on CustomerOperationClass." }, { "code": null, "e": 5232, "s": 5204, "text": "Step 3 − Click on Security." }, { "code": null, "e": 5433, "s": 5232, "text": "Step 4 − Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click on Remove." }, { "code": null, "e": 5457, "s": 5433, "text": "Step 5 − Click on Save." }, { "code": null, "e": 5516, "s": 5457, "text": "Step 1 − From Setup, click Manage Users → Permission Sets." }, { "code": null, "e": 5550, "s": 5516, "text": "Step 2 − Select a permission set." }, { "code": null, "e": 5587, "s": 5550, "text": "Step 3 − Click on Apex Class Access." }, { "code": null, "e": 5611, "s": 5587, "text": "Step 4 − Click on Edit." }, { "code": null, "e": 5825, "s": 5611, "text": "Step 5 − Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click remove." }, { "code": null, "e": 5857, "s": 5825, "text": "Step 6 − Click the Save button." }, { "code": null, "e": 5890, "s": 5857, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5903, "s": 5890, "text": " Vijay Thapa" }, { "code": null, "e": 5935, "s": 5903, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 5943, "s": 5935, "text": " Uplatz" }, { "code": null, "e": 5976, "s": 5943, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 6001, "s": 5976, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 6034, "s": 6001, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 6049, "s": 6034, "text": " Ali Saleh Ali" }, { "code": null, "e": 6082, "s": 6049, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 6095, "s": 6082, "text": " Soham Ghosh" }, { "code": null, "e": 6130, "s": 6095, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6142, "s": 6130, "text": " GUHARAJANM" }, { "code": null, "e": 6149, "s": 6142, "text": " Print" }, { "code": null, "e": 6160, "s": 6149, "text": " Add Notes" } ]
A guide to Face Detection in Python (With Code) | by Maël Fabien | Towards Data Science
In this tutorial, we’ll see how to create and launch a face detection algorithm in Python using OpenCV and Dlib. We’ll also add some features to detect eyes and mouth on multiple faces at the same time. This article will go through the most basic implementations of face detection including Cascade Classifiers, HOG windows and Deep Learning CNNs. We’ll cover face detection using : Haar Cascade Classifiers using OpenCV Histogram of Oriented Gradients using Dlib Convolutional Neural Networks using Dlib This article was originally published on my personal blog : https://maelfabien.github.io/tutorials/face-detection/# The Github repository of this article (and all the others from my blog) can be found here : github.com We’ll be using OpenCV, an open source library for computer vision, written in C/C++, that has interfaces in C++, Python and Java. It supports Windows, Linux, MacOS, iOS and Android. Some of our work will also require using Dlib, a modern C++ toolkit containing machine learning algorithms and tools for creating complex software. The first step is to install OpenCV, and Dlib. Run the following command : pip install opencv-pythonpip install dlib Depending on your version, the file will be installed here : /usr/local/lib/python3.7/site-packages/cv2 If you encounter some issues with Dlib, check this article. We’ll create a new Jupyter notebook / python file and start off with : import cv2import matplotlib.pyplot as pltimport dlibfrom imutils import face_utilsfont = cv2.FONT_HERSHEY_SIMPLEX We’ll explore Cascade Classifiers at first. Cascade classifier, or namely cascade of boosted classifiers working with haar-like features, is a special case of ensemble learning, called boosting. It typically relies on Adaboost classifiers (and other models such as Real Adaboost, Gentle Adaboost or Logitboost). Cascade classifiers are trained on a few hundred sample images of image that contain the object we want to detect, and other images that do not contain those images. How can we detect if a face is there or not ? There is an algorithm, called Viola–Jones object detection framework, that includes all the steps required for live face detection : Haar Feature Selection, features derived from Haar wavelets Create integral image Adaboost Training Cascading Classifiers The original paper was published in 2001. There are some common features that we find on most common human faces : a dark eye region compared to upper-cheeks a bright nose bridge region compared to the eyes some specific location of eyes, mouth, nose... The characteristics are called Haar Features. The feature extraction process will look like this : In this example, the first feature measures the difference in intensity between the region of the eyes and a region across the upper cheeks. The feature value is simply computed by summing the pixels in the black area and subtracting the pixels in the white area. Then, we apply this rectangle as a convolutional kernel, over our whole image. In order to be exhaustive, we should apply all possible dimensions and positions of each kernel. A simple 24*24 images would typically result in over 160’000 features, each made of a sum/subtraction of pixels values. It would computationally be impossible for live face detection. So, how do we speed up this process ? once the good region has been identified by a rectangle, it is useless to run the window over a completely different region of the image. This can be achieved by Adaboost. compute the rectangle features using the integral image principle, which is way faster. We’ll cover this in the next section. There are several types of rectangles that can be applied for Haar Features extraction. According to the original paper : the two-rectangle feature is the difference between the sum of the pixels within two rectangular regions, used mainly for detecting edges (a,b) the three-rectangle feature computes the sum within two outside rectangles subtracted from the sum in a center rectangle, used mainly for detecting lines (c,d) the four-rectangle feature computes the difference between diagonal pairs of rectangle (e) Now that the features have been selected, we apply them on the set of training images using Adaboost classification, that combines a set of weak classifiers to create an accurate ensemble model. With 200 features (instead of 160’000 initially), an accuracy of 95% is achieved. The authors of the paper have selected 6’000 features. Computing the rectangle features in a convolutional kernel style can be long, very long. For this reason, the authors, Viola and Jones, proposed an intermediate representation for the image : the integral image. The role of the integral image is to allow any rectangular sum to be computed simply, using only four values. We’ll see how it works ! Suppose we want to determine the rectangle features at a given pixel with coordinates (x,y). Then, the integral image of the pixel in the sum of the pixels above and to the left of the given pixel. where ii(x,y) is the integral image and i(x,y) is the original image. When you compute the whole integral image, there is a form a recurrence which requires only one pass over the original image. Indeed, we can define the following pair of recurrences : where s(x,y) is the cumulative row sum and and s(x−1)=0, ii(−1,y)=0. How can that be useful ? Well, consider a region D for which we would like to estimate the sum of the pixels. We have defined 3 other regions : A, B and C. The value of the integral image at point 1 is the sum of the pixels in rectangle A. The value at point 2 is u0005u0004A + B The value at point 3 is u0005u0004A + C The value at point 4 is u0005u0004A + B + C + D. Therefore, the sum of pixels in region D can simply be computed as : 4+1−(2+3). And over a single pass, we have computed the value inside a rectangle using only 4 array references. One should simply be aware that rectangles are quite simple features in practice, but sufficient for face detection. Steerable filters tend to be more flexible when it comes to complex problems. Given a set of labeled training images (positive or negative), Adaboost is used to : select a small set of features and train the classifier Since most features among the 160’000 are supposed to be quite irrelevant, the weak learning algorithm around which we build a boosting model is designed to select the single rectangle feature which splits best negative and positive examples. Although the process described above is quite efficient, a major issue remains. In an image, most of the image is a non-face region. Giving equal importance to each region of the image makes no sense, since we should mainly focus on the regions that are most likely to contain a picture. Viola and Jones achieved an increased detection rate while reducing computation time using Cascading Classifiers. The key idea is to reject sub-windows that do not contain faces while identifying regions that do. Since the task is to identify properly the face, we want to minimize the false negative rate, i.e the sub-windows that contain a face and have not been identified as such. A series of classifiers are applied to every sub-window. These classifiers are simple decision trees : if the first classifier is positive, we move on to the second if the second classifier is positive, we move on to the third ... Any negative result at some point leads to a rejection of the sub-window as potentially containing a face. The initial classifier eliminates most negative examples at a low computational cost, and the following classifiers eliminate additional negative examples but require more computational effort. The classifiers are trained using Adaboost and adjusting the threshold to minimize the false rate. When training such model, the variables are the following : the number of classifier stages the number of features in each stage the threshold of each stage Luckily in OpenCV, this whole model is already pre-trained for face detection. If you’d like to know more on Boosting techniques, I invite you to check my article on Adaboost. The next step simply is to locate the pre-trained weights. We will be using default pre-trained models to detect face, eyes and mouth. Depending on your version of Python, the files should be located somewhere over here : /usr/local/lib/python3.7/site-packages/cv2/data Once identified, we’ll declare Cascade classifiers this way : cascPath = "/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml"eyePath = "/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"smilePath = "/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"faceCascade = cv2.CascadeClassifier(cascPath)eyeCascade = cv2.CascadeClassifier(eyePath)smileCascade = cv2.CascadeClassifier(smilePath) Before implementing the real time face detection algorithm, let’s try a simple version on an image. We can start by loading a test image : # Load the imagegray = cv2.imread('face_detect_test.jpeg', 0)plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show() Then, we detect the face and we add a rectangle around it : # Detect facesfaces = faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,flags=cv2.CASCADE_SCALE_IMAGE)# For each facefor (x, y, w, h) in faces: # Draw rectangle around the face cv2.rectangle(gray, (x, y), (x+w, y+h), (255, 255, 255), 3) Here is a list of the most common parameters of the detectMultiScale function : scaleFactor : Parameter specifying how much the image size is reduced at each image scale. minNeighbors : Parameter specifying how many neighbors each candidate rectangle should have to retain it. minSize : Minimum possible object size. Objects smaller than that are ignored. maxSize : Maximum possible object size. Objects larger than that are ignored. Finally, display the result : plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show() Face detection works well on our test image. Let’s move on to real time now ! Let’s move on to the Python implementation of the live facial detection. The first step is to launch the camera, and capture the video. Then, we’ll transform the image to a gray scale image. This is used to reduce the dimension of the input image. Indeed, instead of 3 points per pixel describing Red, Green, Blue, we apply a simple linear transformation : This is implemented by default in OpenCV. video_capture = cv2.VideoCapture(0)while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) Now, we’ll use the faceCascade variable define above, which contains a pre-trained algorithm, and apply it to the gray scale image. faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) For each face detected, we’ll draw a rectangle around the face : for (x, y, w, h) in faces: if w > 250 : cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 3) roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w] For each mouth detected, draw a rectangle around it : smile = smileCascade.detectMultiScale( roi_gray, scaleFactor= 1.16, minNeighbors=35, minSize=(25, 25), flags=cv2.CASCADE_SCALE_IMAGE ) for (sx, sy, sw, sh) in smile: cv2.rectangle(roi_color, (sh, sy), (sx+sw, sy+sh), (255, 0, 0), 2) cv2.putText(frame,'Smile',(x + sx,y + sy), 1, 1, (0, 255, 0), 1) For each eye detected, draw a rectangle around it : eyes = eyeCascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.putText(frame,'Eye',(x + ex,y + ey), 1, 1, (0, 255, 0), 1) Then, count the total number of faces, and display the overall image : cv2.putText(frame,'Number of Faces : ' + str(len(faces)),(40, 40), font, 1,(255,0,0),2) # Display the resulting frame cv2.imshow('Video', frame) And implement an exit option when we want to stop the camera by pressing q : if cv2.waitKey(1) & 0xFF == ord('q'): break Finally, when everything is done, release the capture and destroy all windows. There are some troubles killing windows on Mac which might require killing Python from the Activity Manager later on. video_capture.release()cv2.destroyAllWindows() I’ve made a quick YouTube illustration of the face detection algorithm. The second most popular implement for face detection is offered by Dlib and uses a concept called Histogram of Oriented Gradients (HOG). This is an implementation of the original paper by Dalal and Triggs. The idea behind HOG is to extract features into a vector, and feed it into a classification algorithm like a Support Vector Machine for example that will assess whether a face (or any object you train it to recognize actually) is present in a region or not. The features extracted are the distribution (histograms) of directions of gradients (oriented gradients) of the image. Gradients are typically large around edges and corners and allow us to detect those regions. In the original paper, the process was implemented for human body detection, and the detection chain was the following : First of all, the input images must but of the same size (crop and rescale images). The patches we’ll apply require an aspect ratio of 1:2, so the dimensions of the input images might be 64x128 or 100x200 for example. The first step is to compute the horizontal and vertical gradients of the image, by applying the following kernels : The gradient of an image typically removes non-essential information. The gradient of the image we were considering above can be found this way in Python : gray = cv2.imread('images/face_detect_test.jpeg', 0)im = np.float32(gray) / 255.0# Calculate gradient gx = cv2.Sobel(im, cv2.CV_32F, 1, 0, ksize=1)gy = cv2.Sobel(im, cv2.CV_32F, 0, 1, ksize=1)mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True) And plot the picture : plt.figure(figsize=(12,8))plt.imshow(mag)plt.show() We have not pre-processed the image before though. The image is then divided into 8x8 cells to offer a compact representation and make our HOG more robust to noise. Then, we compute a HOG for each of those cells. To estimate the direction of a gradient inside a region, we simply build a histogram among the 64 values of the gradient directions (8x8) and their magnitude (another 64 values) inside each region. The categories of the histogram correspond to angles of the gradient, from 0 to 180°. Ther are 9 categories overall : 0°, 20°, 40°... 160°. The code above gave us 2 information : direction of the gradient and magnitude of the gradient When we build the HOG, there are 3 subcases : the angle is smaller than 160° and not halfway between 2 classes. In such case, the angle will be added in the right category of the HOG the angle is smaller than 160° and exactly between 2 classes. In such case, we consider an equal contribution to the 2 nearest classes and split the magnitude in 2 the angle is larger than 160°. In such case, we consider that the pixel contributed proportionally to 160° and to 0°. The HOG looks like this for each 8x8 cell : Finally, a 16x16 block can be applied in order to normalize the image and make it invariant to lighting for example. This is simply achieved by dividing each value of the HOG of size 8x8 by the L2-norm of the HOG of the 16x16 block that contains it, which is in fact a simple vector of length 9*4 = 36. Finally, all the 36x1 vectors are concatenated into a large vector. And we are done ! We have our feature vector, on which we can train a soft SVM classifier (C=0.01). The implementation is pretty straight forward : face_detect = dlib.get_frontal_face_detector()rects = face_detect(gray, 1)for (i, rect) in enumerate(rects):(x, y, w, h) = face_utils.rect_to_bb(rect) cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 255, 255), 3) plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show() As previously, the algorithm is pretty easy to implement. We are also implementing a lighter version by detecting only the face. Dlib makes it really easy to detect facial key-points too, but it’s another topic. This last method is based on Convolutional Neural Networks (CNN). It also implements a paper on Max-Margin Object Detection (MMOD) for enhanced results. Convolutional Neural Network (CNN) are feed-forward neural network that are mostly used for computer vision. They offer an automated image pre-treatment as well as a dense neural network part. CNNs are special types of neural networks for processing datas with grid-like topology. The architecture of the CNN is inspired by the visual cortex of animals. In previous approaches, a great part of the work was to select the filters in order to create the features in order to extract as much information from the image as possible. With the rise of deep learning and greater computation capacities, this work can now be automated. The name of the CNNs comes from the fact that we convolve the initial image input with a set of filters. The parameter to choose remains the number of filters to apply, and the dimension of the filters. The dimension of the filter is called the kernel size. The stride length is the number of pixels by which we shift this filter. Typical values for the stride lie between 2 and 5. The output of the CNN in this specific case is a binary classification, that takes value 1 if there is a face, 0 otherwise. Some elements change in the implementation. The first step is to download the pre-trained model here. Move the weights to your folder, and define dnnDaceDetector : dnnFaceDetector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat") Then, quite similarly to what we have done so far : rects = dnnFaceDetector(gray, 1)for (i, rect) in enumerate(rects): x1 = rect.rect.left() y1 = rect.rect.top() x2 = rect.rect.right() y2 = rect.rect.bottom() # Rectangle around the face cv2.rectangle(gray, (x1, y1), (x2, y2), (255, 255, 255), 3)plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show() Finally, we’ll implement the real time version of the CNN face detection : Tough question, but we’ll just go through 2 metrics that are important : the computation time the accuracy In terms of speed, HoG seems to be the fastest algorithm, followed by Haar Cascade classifier and CNNs. However, CNNs in Dlib tend to be the most accurate algorithm. HoG perform pretty well but have some issues identifying small faces. HaarCascade Classifiers perform around as good as HoG overall. I have personally used mainly HoG in my personal projects due to its speed for live face detection. Conclusion : I hope you enjoyed this quick tutorial on OpenCV and Dlib for face detection. Don’t hesitate to drop a comment if you have any question/remark. HOG DLIB Viola-Jones Paper Face Detection 1 Face Detection 2 Face Detection 3
[ { "code": null, "e": 519, "s": 171, "text": "In this tutorial, we’ll see how to create and launch a face detection algorithm in Python using OpenCV and Dlib. We’ll also add some features to detect eyes and mouth on multiple faces at the same time. This article will go through the most basic implementations of face detection including Cascade Classifiers, HOG windows and Deep Learning CNNs." }, { "code": null, "e": 554, "s": 519, "text": "We’ll cover face detection using :" }, { "code": null, "e": 592, "s": 554, "text": "Haar Cascade Classifiers using OpenCV" }, { "code": null, "e": 635, "s": 592, "text": "Histogram of Oriented Gradients using Dlib" }, { "code": null, "e": 676, "s": 635, "text": "Convolutional Neural Networks using Dlib" }, { "code": null, "e": 792, "s": 676, "text": "This article was originally published on my personal blog : https://maelfabien.github.io/tutorials/face-detection/#" }, { "code": null, "e": 884, "s": 792, "text": "The Github repository of this article (and all the others from my blog) can be found here :" }, { "code": null, "e": 895, "s": 884, "text": "github.com" }, { "code": null, "e": 1225, "s": 895, "text": "We’ll be using OpenCV, an open source library for computer vision, written in C/C++, that has interfaces in C++, Python and Java. It supports Windows, Linux, MacOS, iOS and Android. Some of our work will also require using Dlib, a modern C++ toolkit containing machine learning algorithms and tools for creating complex software." }, { "code": null, "e": 1300, "s": 1225, "text": "The first step is to install OpenCV, and Dlib. Run the following command :" }, { "code": null, "e": 1342, "s": 1300, "text": "pip install opencv-pythonpip install dlib" }, { "code": null, "e": 1403, "s": 1342, "text": "Depending on your version, the file will be installed here :" }, { "code": null, "e": 1446, "s": 1403, "text": "/usr/local/lib/python3.7/site-packages/cv2" }, { "code": null, "e": 1506, "s": 1446, "text": "If you encounter some issues with Dlib, check this article." }, { "code": null, "e": 1577, "s": 1506, "text": "We’ll create a new Jupyter notebook / python file and start off with :" }, { "code": null, "e": 1691, "s": 1577, "text": "import cv2import matplotlib.pyplot as pltimport dlibfrom imutils import face_utilsfont = cv2.FONT_HERSHEY_SIMPLEX" }, { "code": null, "e": 1735, "s": 1691, "text": "We’ll explore Cascade Classifiers at first." }, { "code": null, "e": 2003, "s": 1735, "text": "Cascade classifier, or namely cascade of boosted classifiers working with haar-like features, is a special case of ensemble learning, called boosting. It typically relies on Adaboost classifiers (and other models such as Real Adaboost, Gentle Adaboost or Logitboost)." }, { "code": null, "e": 2169, "s": 2003, "text": "Cascade classifiers are trained on a few hundred sample images of image that contain the object we want to detect, and other images that do not contain those images." }, { "code": null, "e": 2348, "s": 2169, "text": "How can we detect if a face is there or not ? There is an algorithm, called Viola–Jones object detection framework, that includes all the steps required for live face detection :" }, { "code": null, "e": 2408, "s": 2348, "text": "Haar Feature Selection, features derived from Haar wavelets" }, { "code": null, "e": 2430, "s": 2408, "text": "Create integral image" }, { "code": null, "e": 2448, "s": 2430, "text": "Adaboost Training" }, { "code": null, "e": 2470, "s": 2448, "text": "Cascading Classifiers" }, { "code": null, "e": 2512, "s": 2470, "text": "The original paper was published in 2001." }, { "code": null, "e": 2585, "s": 2512, "text": "There are some common features that we find on most common human faces :" }, { "code": null, "e": 2628, "s": 2585, "text": "a dark eye region compared to upper-cheeks" }, { "code": null, "e": 2677, "s": 2628, "text": "a bright nose bridge region compared to the eyes" }, { "code": null, "e": 2724, "s": 2677, "text": "some specific location of eyes, mouth, nose..." }, { "code": null, "e": 2823, "s": 2724, "text": "The characteristics are called Haar Features. The feature extraction process will look like this :" }, { "code": null, "e": 3087, "s": 2823, "text": "In this example, the first feature measures the difference in intensity between the region of the eyes and a region across the upper cheeks. The feature value is simply computed by summing the pixels in the black area and subtracting the pixels in the white area." }, { "code": null, "e": 3485, "s": 3087, "text": "Then, we apply this rectangle as a convolutional kernel, over our whole image. In order to be exhaustive, we should apply all possible dimensions and positions of each kernel. A simple 24*24 images would typically result in over 160’000 features, each made of a sum/subtraction of pixels values. It would computationally be impossible for live face detection. So, how do we speed up this process ?" }, { "code": null, "e": 3657, "s": 3485, "text": "once the good region has been identified by a rectangle, it is useless to run the window over a completely different region of the image. This can be achieved by Adaboost." }, { "code": null, "e": 3783, "s": 3657, "text": "compute the rectangle features using the integral image principle, which is way faster. We’ll cover this in the next section." }, { "code": null, "e": 3905, "s": 3783, "text": "There are several types of rectangles that can be applied for Haar Features extraction. According to the original paper :" }, { "code": null, "e": 4049, "s": 3905, "text": "the two-rectangle feature is the difference between the sum of the pixels within two rectangular regions, used mainly for detecting edges (a,b)" }, { "code": null, "e": 4209, "s": 4049, "text": "the three-rectangle feature computes the sum within two outside rectangles subtracted from the sum in a center rectangle, used mainly for detecting lines (c,d)" }, { "code": null, "e": 4300, "s": 4209, "text": "the four-rectangle feature computes the difference between diagonal pairs of rectangle (e)" }, { "code": null, "e": 4632, "s": 4300, "text": "Now that the features have been selected, we apply them on the set of training images using Adaboost classification, that combines a set of weak classifiers to create an accurate ensemble model. With 200 features (instead of 160’000 initially), an accuracy of 95% is achieved. The authors of the paper have selected 6’000 features." }, { "code": null, "e": 4979, "s": 4632, "text": "Computing the rectangle features in a convolutional kernel style can be long, very long. For this reason, the authors, Viola and Jones, proposed an intermediate representation for the image : the integral image. The role of the integral image is to allow any rectangular sum to be computed simply, using only four values. We’ll see how it works !" }, { "code": null, "e": 5177, "s": 4979, "text": "Suppose we want to determine the rectangle features at a given pixel with coordinates (x,y). Then, the integral image of the pixel in the sum of the pixels above and to the left of the given pixel." }, { "code": null, "e": 5247, "s": 5177, "text": "where ii(x,y) is the integral image and i(x,y) is the original image." }, { "code": null, "e": 5431, "s": 5247, "text": "When you compute the whole integral image, there is a form a recurrence which requires only one pass over the original image. Indeed, we can define the following pair of recurrences :" }, { "code": null, "e": 5500, "s": 5431, "text": "where s(x,y) is the cumulative row sum and and s(x−1)=0, ii(−1,y)=0." }, { "code": null, "e": 5656, "s": 5500, "text": "How can that be useful ? Well, consider a region D for which we would like to estimate the sum of the pixels. We have defined 3 other regions : A, B and C." }, { "code": null, "e": 5740, "s": 5656, "text": "The value of the integral image at point 1 is the sum of the pixels in rectangle A." }, { "code": null, "e": 5780, "s": 5740, "text": "The value at point 2 is u0005u0004A + B" }, { "code": null, "e": 5820, "s": 5780, "text": "The value at point 3 is u0005u0004A + C" }, { "code": null, "e": 5869, "s": 5820, "text": "The value at point 4 is u0005u0004A + B + C + D." }, { "code": null, "e": 5949, "s": 5869, "text": "Therefore, the sum of pixels in region D can simply be computed as : 4+1−(2+3)." }, { "code": null, "e": 6050, "s": 5949, "text": "And over a single pass, we have computed the value inside a rectangle using only 4 array references." }, { "code": null, "e": 6245, "s": 6050, "text": "One should simply be aware that rectangles are quite simple features in practice, but sufficient for face detection. Steerable filters tend to be more flexible when it comes to complex problems." }, { "code": null, "e": 6330, "s": 6245, "text": "Given a set of labeled training images (positive or negative), Adaboost is used to :" }, { "code": null, "e": 6361, "s": 6330, "text": "select a small set of features" }, { "code": null, "e": 6386, "s": 6361, "text": "and train the classifier" }, { "code": null, "e": 6629, "s": 6386, "text": "Since most features among the 160’000 are supposed to be quite irrelevant, the weak learning algorithm around which we build a boosting model is designed to select the single rectangle feature which splits best negative and positive examples." }, { "code": null, "e": 7031, "s": 6629, "text": "Although the process described above is quite efficient, a major issue remains. In an image, most of the image is a non-face region. Giving equal importance to each region of the image makes no sense, since we should mainly focus on the regions that are most likely to contain a picture. Viola and Jones achieved an increased detection rate while reducing computation time using Cascading Classifiers." }, { "code": null, "e": 7302, "s": 7031, "text": "The key idea is to reject sub-windows that do not contain faces while identifying regions that do. Since the task is to identify properly the face, we want to minimize the false negative rate, i.e the sub-windows that contain a face and have not been identified as such." }, { "code": null, "e": 7405, "s": 7302, "text": "A series of classifiers are applied to every sub-window. These classifiers are simple decision trees :" }, { "code": null, "e": 7467, "s": 7405, "text": "if the first classifier is positive, we move on to the second" }, { "code": null, "e": 7529, "s": 7467, "text": "if the second classifier is positive, we move on to the third" }, { "code": null, "e": 7533, "s": 7529, "text": "..." }, { "code": null, "e": 7834, "s": 7533, "text": "Any negative result at some point leads to a rejection of the sub-window as potentially containing a face. The initial classifier eliminates most negative examples at a low computational cost, and the following classifiers eliminate additional negative examples but require more computational effort." }, { "code": null, "e": 7993, "s": 7834, "text": "The classifiers are trained using Adaboost and adjusting the threshold to minimize the false rate. When training such model, the variables are the following :" }, { "code": null, "e": 8025, "s": 7993, "text": "the number of classifier stages" }, { "code": null, "e": 8062, "s": 8025, "text": "the number of features in each stage" }, { "code": null, "e": 8090, "s": 8062, "text": "the threshold of each stage" }, { "code": null, "e": 8169, "s": 8090, "text": "Luckily in OpenCV, this whole model is already pre-trained for face detection." }, { "code": null, "e": 8266, "s": 8169, "text": "If you’d like to know more on Boosting techniques, I invite you to check my article on Adaboost." }, { "code": null, "e": 8488, "s": 8266, "text": "The next step simply is to locate the pre-trained weights. We will be using default pre-trained models to detect face, eyes and mouth. Depending on your version of Python, the files should be located somewhere over here :" }, { "code": null, "e": 8536, "s": 8488, "text": "/usr/local/lib/python3.7/site-packages/cv2/data" }, { "code": null, "e": 8598, "s": 8536, "text": "Once identified, we’ll declare Cascade classifiers this way :" }, { "code": null, "e": 8992, "s": 8598, "text": "cascPath = \"/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml\"eyePath = \"/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml\"smilePath = \"/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml\"faceCascade = cv2.CascadeClassifier(cascPath)eyeCascade = cv2.CascadeClassifier(eyePath)smileCascade = cv2.CascadeClassifier(smilePath)" }, { "code": null, "e": 9131, "s": 8992, "text": "Before implementing the real time face detection algorithm, let’s try a simple version on an image. We can start by loading a test image :" }, { "code": null, "e": 9258, "s": 9131, "text": "# Load the imagegray = cv2.imread('face_detect_test.jpeg', 0)plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show()" }, { "code": null, "e": 9318, "s": 9258, "text": "Then, we detect the face and we add a rectangle around it :" }, { "code": null, "e": 9577, "s": 9318, "text": "# Detect facesfaces = faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,flags=cv2.CASCADE_SCALE_IMAGE)# For each facefor (x, y, w, h) in faces: # Draw rectangle around the face cv2.rectangle(gray, (x, y), (x+w, y+h), (255, 255, 255), 3)" }, { "code": null, "e": 9657, "s": 9577, "text": "Here is a list of the most common parameters of the detectMultiScale function :" }, { "code": null, "e": 9748, "s": 9657, "text": "scaleFactor : Parameter specifying how much the image size is reduced at each image scale." }, { "code": null, "e": 9854, "s": 9748, "text": "minNeighbors : Parameter specifying how many neighbors each candidate rectangle should have to retain it." }, { "code": null, "e": 9933, "s": 9854, "text": "minSize : Minimum possible object size. Objects smaller than that are ignored." }, { "code": null, "e": 10011, "s": 9933, "text": "maxSize : Maximum possible object size. Objects larger than that are ignored." }, { "code": null, "e": 10041, "s": 10011, "text": "Finally, display the result :" }, { "code": null, "e": 10107, "s": 10041, "text": "plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show()" }, { "code": null, "e": 10185, "s": 10107, "text": "Face detection works well on our test image. Let’s move on to real time now !" }, { "code": null, "e": 10542, "s": 10185, "text": "Let’s move on to the Python implementation of the live facial detection. The first step is to launch the camera, and capture the video. Then, we’ll transform the image to a gray scale image. This is used to reduce the dimension of the input image. Indeed, instead of 3 points per pixel describing Red, Green, Blue, we apply a simple linear transformation :" }, { "code": null, "e": 10584, "s": 10542, "text": "This is implemented by default in OpenCV." }, { "code": null, "e": 10746, "s": 10584, "text": "video_capture = cv2.VideoCapture(0)while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)" }, { "code": null, "e": 10878, "s": 10746, "text": "Now, we’ll use the faceCascade variable define above, which contains a pre-trained algorithm, and apply it to the gray scale image." }, { "code": null, "e": 11047, "s": 10878, "text": "faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE )" }, { "code": null, "e": 11112, "s": 11047, "text": "For each face detected, we’ll draw a rectangle around the face :" }, { "code": null, "e": 11311, "s": 11112, "text": "for (x, y, w, h) in faces: if w > 250 : cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 3) roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w]" }, { "code": null, "e": 11365, "s": 11311, "text": "For each mouth detected, draw a rectangle around it :" }, { "code": null, "e": 11718, "s": 11365, "text": "smile = smileCascade.detectMultiScale( roi_gray, scaleFactor= 1.16, minNeighbors=35, minSize=(25, 25), flags=cv2.CASCADE_SCALE_IMAGE ) for (sx, sy, sw, sh) in smile: cv2.rectangle(roi_color, (sh, sy), (sx+sw, sy+sh), (255, 0, 0), 2) cv2.putText(frame,'Smile',(x + sx,y + sy), 1, 1, (0, 255, 0), 1)" }, { "code": null, "e": 11770, "s": 11718, "text": "For each eye detected, draw a rectangle around it :" }, { "code": null, "e": 11981, "s": 11770, "text": "eyes = eyeCascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.putText(frame,'Eye',(x + ex,y + ey), 1, 1, (0, 255, 0), 1)" }, { "code": null, "e": 12052, "s": 11981, "text": "Then, count the total number of faces, and display the overall image :" }, { "code": null, "e": 12209, "s": 12052, "text": "cv2.putText(frame,'Number of Faces : ' + str(len(faces)),(40, 40), font, 1,(255,0,0),2) # Display the resulting frame cv2.imshow('Video', frame)" }, { "code": null, "e": 12286, "s": 12209, "text": "And implement an exit option when we want to stop the camera by pressing q :" }, { "code": null, "e": 12337, "s": 12286, "text": "if cv2.waitKey(1) & 0xFF == ord('q'): break" }, { "code": null, "e": 12534, "s": 12337, "text": "Finally, when everything is done, release the capture and destroy all windows. There are some troubles killing windows on Mac which might require killing Python from the Activity Manager later on." }, { "code": null, "e": 12581, "s": 12534, "text": "video_capture.release()cv2.destroyAllWindows()" }, { "code": null, "e": 12653, "s": 12581, "text": "I’ve made a quick YouTube illustration of the face detection algorithm." }, { "code": null, "e": 12859, "s": 12653, "text": "The second most popular implement for face detection is offered by Dlib and uses a concept called Histogram of Oriented Gradients (HOG). This is an implementation of the original paper by Dalal and Triggs." }, { "code": null, "e": 13117, "s": 12859, "text": "The idea behind HOG is to extract features into a vector, and feed it into a classification algorithm like a Support Vector Machine for example that will assess whether a face (or any object you train it to recognize actually) is present in a region or not." }, { "code": null, "e": 13329, "s": 13117, "text": "The features extracted are the distribution (histograms) of directions of gradients (oriented gradients) of the image. Gradients are typically large around edges and corners and allow us to detect those regions." }, { "code": null, "e": 13450, "s": 13329, "text": "In the original paper, the process was implemented for human body detection, and the detection chain was the following :" }, { "code": null, "e": 13668, "s": 13450, "text": "First of all, the input images must but of the same size (crop and rescale images). The patches we’ll apply require an aspect ratio of 1:2, so the dimensions of the input images might be 64x128 or 100x200 for example." }, { "code": null, "e": 13785, "s": 13668, "text": "The first step is to compute the horizontal and vertical gradients of the image, by applying the following kernels :" }, { "code": null, "e": 13855, "s": 13785, "text": "The gradient of an image typically removes non-essential information." }, { "code": null, "e": 13941, "s": 13855, "text": "The gradient of the image we were considering above can be found this way in Python :" }, { "code": null, "e": 14191, "s": 13941, "text": "gray = cv2.imread('images/face_detect_test.jpeg', 0)im = np.float32(gray) / 255.0# Calculate gradient gx = cv2.Sobel(im, cv2.CV_32F, 1, 0, ksize=1)gy = cv2.Sobel(im, cv2.CV_32F, 0, 1, ksize=1)mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)" }, { "code": null, "e": 14214, "s": 14191, "text": "And plot the picture :" }, { "code": null, "e": 14266, "s": 14214, "text": "plt.figure(figsize=(12,8))plt.imshow(mag)plt.show()" }, { "code": null, "e": 14317, "s": 14266, "text": "We have not pre-processed the image before though." }, { "code": null, "e": 14479, "s": 14317, "text": "The image is then divided into 8x8 cells to offer a compact representation and make our HOG more robust to noise. Then, we compute a HOG for each of those cells." }, { "code": null, "e": 14817, "s": 14479, "text": "To estimate the direction of a gradient inside a region, we simply build a histogram among the 64 values of the gradient directions (8x8) and their magnitude (another 64 values) inside each region. The categories of the histogram correspond to angles of the gradient, from 0 to 180°. Ther are 9 categories overall : 0°, 20°, 40°... 160°." }, { "code": null, "e": 14856, "s": 14817, "text": "The code above gave us 2 information :" }, { "code": null, "e": 14882, "s": 14856, "text": "direction of the gradient" }, { "code": null, "e": 14912, "s": 14882, "text": "and magnitude of the gradient" }, { "code": null, "e": 14958, "s": 14912, "text": "When we build the HOG, there are 3 subcases :" }, { "code": null, "e": 15095, "s": 14958, "text": "the angle is smaller than 160° and not halfway between 2 classes. In such case, the angle will be added in the right category of the HOG" }, { "code": null, "e": 15259, "s": 15095, "text": "the angle is smaller than 160° and exactly between 2 classes. In such case, we consider an equal contribution to the 2 nearest classes and split the magnitude in 2" }, { "code": null, "e": 15377, "s": 15259, "text": "the angle is larger than 160°. In such case, we consider that the pixel contributed proportionally to 160° and to 0°." }, { "code": null, "e": 15421, "s": 15377, "text": "The HOG looks like this for each 8x8 cell :" }, { "code": null, "e": 15724, "s": 15421, "text": "Finally, a 16x16 block can be applied in order to normalize the image and make it invariant to lighting for example. This is simply achieved by dividing each value of the HOG of size 8x8 by the L2-norm of the HOG of the 16x16 block that contains it, which is in fact a simple vector of length 9*4 = 36." }, { "code": null, "e": 15892, "s": 15724, "text": "Finally, all the 36x1 vectors are concatenated into a large vector. And we are done ! We have our feature vector, on which we can train a soft SVM classifier (C=0.01)." }, { "code": null, "e": 15940, "s": 15892, "text": "The implementation is pretty straight forward :" }, { "code": null, "e": 16227, "s": 15940, "text": "face_detect = dlib.get_frontal_face_detector()rects = face_detect(gray, 1)for (i, rect) in enumerate(rects):(x, y, w, h) = face_utils.rect_to_bb(rect) cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 255, 255), 3) plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show()" }, { "code": null, "e": 16439, "s": 16227, "text": "As previously, the algorithm is pretty easy to implement. We are also implementing a lighter version by detecting only the face. Dlib makes it really easy to detect facial key-points too, but it’s another topic." }, { "code": null, "e": 16592, "s": 16439, "text": "This last method is based on Convolutional Neural Networks (CNN). It also implements a paper on Max-Margin Object Detection (MMOD) for enhanced results." }, { "code": null, "e": 16946, "s": 16592, "text": "Convolutional Neural Network (CNN) are feed-forward neural network that are mostly used for computer vision. They offer an automated image pre-treatment as well as a dense neural network part. CNNs are special types of neural networks for processing datas with grid-like topology. The architecture of the CNN is inspired by the visual cortex of animals." }, { "code": null, "e": 17602, "s": 16946, "text": "In previous approaches, a great part of the work was to select the filters in order to create the features in order to extract as much information from the image as possible. With the rise of deep learning and greater computation capacities, this work can now be automated. The name of the CNNs comes from the fact that we convolve the initial image input with a set of filters. The parameter to choose remains the number of filters to apply, and the dimension of the filters. The dimension of the filter is called the kernel size. The stride length is the number of pixels by which we shift this filter. Typical values for the stride lie between 2 and 5." }, { "code": null, "e": 17726, "s": 17602, "text": "The output of the CNN in this specific case is a binary classification, that takes value 1 if there is a face, 0 otherwise." }, { "code": null, "e": 17770, "s": 17726, "text": "Some elements change in the implementation." }, { "code": null, "e": 17890, "s": 17770, "text": "The first step is to download the pre-trained model here. Move the weights to your folder, and define dnnDaceDetector :" }, { "code": null, "e": 17973, "s": 17890, "text": "dnnFaceDetector = dlib.cnn_face_detection_model_v1(\"mmod_human_face_detector.dat\")" }, { "code": null, "e": 18025, "s": 17973, "text": "Then, quite similarly to what we have done so far :" }, { "code": null, "e": 18353, "s": 18025, "text": "rects = dnnFaceDetector(gray, 1)for (i, rect) in enumerate(rects): x1 = rect.rect.left() y1 = rect.rect.top() x2 = rect.rect.right() y2 = rect.rect.bottom() # Rectangle around the face cv2.rectangle(gray, (x1, y1), (x2, y2), (255, 255, 255), 3)plt.figure(figsize=(12,8))plt.imshow(gray, cmap='gray')plt.show()" }, { "code": null, "e": 18428, "s": 18353, "text": "Finally, we’ll implement the real time version of the CNN face detection :" }, { "code": null, "e": 18501, "s": 18428, "text": "Tough question, but we’ll just go through 2 metrics that are important :" }, { "code": null, "e": 18522, "s": 18501, "text": "the computation time" }, { "code": null, "e": 18535, "s": 18522, "text": "the accuracy" }, { "code": null, "e": 18639, "s": 18535, "text": "In terms of speed, HoG seems to be the fastest algorithm, followed by Haar Cascade classifier and CNNs." }, { "code": null, "e": 18834, "s": 18639, "text": "However, CNNs in Dlib tend to be the most accurate algorithm. HoG perform pretty well but have some issues identifying small faces. HaarCascade Classifiers perform around as good as HoG overall." }, { "code": null, "e": 18934, "s": 18834, "text": "I have personally used mainly HoG in my personal projects due to its speed for live face detection." }, { "code": null, "e": 19091, "s": 18934, "text": "Conclusion : I hope you enjoyed this quick tutorial on OpenCV and Dlib for face detection. Don’t hesitate to drop a comment if you have any question/remark." }, { "code": null, "e": 19095, "s": 19091, "text": "HOG" }, { "code": null, "e": 19100, "s": 19095, "text": "DLIB" }, { "code": null, "e": 19118, "s": 19100, "text": "Viola-Jones Paper" }, { "code": null, "e": 19135, "s": 19118, "text": "Face Detection 1" }, { "code": null, "e": 19152, "s": 19135, "text": "Face Detection 2" } ]
Circle Detection using OpenCV | Python - GeeksforGeeks
14 Jul, 2019 Circle detection finds a variety of uses in biomedical applications, ranging from iris detection to white blood cell segmentation. The technique followed is similar to the one used to detect lines, as discussed in this article. Basics of Circle Detection A circle can be described by the following equation: To detect circles, we may fix a point (x, y). Now, we are required to find 3 parameters: a, b and r. Therefore, the problem is in a 3-dimensional search space. To find possible circles, the algorithm uses a 3-D matrix called the “Accumulator Matrix” to store potential a, b and r values. The value of a (x-coordinate of the center) may range from 1 to rows, b (y-coordinate of the center) may range from 1 to cols, and r may range from 1 to maxRadius = . Below are the steps of the algorithm. Initializing the Accumulator Matrix: Initialize a matrix of dimensions rows * cols * maxRadius with zeros. Pre-processing the image: Apply blurring, grayscale and an edge detector on the image. This is done to ensure the circles show as darkened image edges. Looping through the points: Pick a point on the image. Fixing r and looping through a and b: Use a double nested loop to find a value of r, varying a and b in the given ranges.for a in range(rows): for b in range(cols): r = math.sqrt((xi - a)**2 + (yi - b)**2) accum_matrix[a][b][r] += 1 for a in range(rows): for b in range(cols): r = math.sqrt((xi - a)**2 + (yi - b)**2) accum_matrix[a][b][r] += 1 Voting: Pick the points in the accumulator matrix with the maximum value. These are strong points which indicate the existence of a circle with a, b and r parameters. This gives us the Hough space of circles. Finding Circles: Finally, using the above circles as candidate circles, vote according to the image. The maximum voted circle in the accumulator matrix gives us the circle. The HoughCircles function in OpenCV has the following parameters which can be altered according to the image. Detection Method: OpenCV has an advanced implementation, HOUGH_GRADIENT, which uses gradient of the edges instead of filling up the entire 3D accumulator matrix, thereby speeding up the process.dp: This is the ratio of the resolution of original image to the accumulator matrix.minDist: This parameter controls the minimum distance between detected circles.Param1: Canny edge detection requires two parameters — minVal and maxVal. Param1 is the higher threshold of the two. The second one is set as Param1/2.Param2: This is the accumulator threshold for the candidate detected circles. By increasing this threshold value, we can ensure that only the best circles, corresponding to larger accumulator values, are returned.minRadius: Minimum circle radius.maxRadius: Maximum circle radius. Below is the code for finding circles using OpenCV on the above input image. import cv2import numpy as np # Read image.img = cv2.imread('eyes.jpg', cv2.IMREAD_COLOR) # Convert to grayscale.gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Blur using 3 * 3 kernel.gray_blurred = cv2.blur(gray, (3, 3)) # Apply Hough transform on the blurred image.detected_circles = cv2.HoughCircles(gray_blurred, cv2.HOUGH_GRADIENT, 1, 20, param1 = 50, param2 = 30, minRadius = 1, maxRadius = 40) # Draw circles that are detected.if detected_circles is not None: # Convert the circle parameters a, b and r to integers. detected_circles = np.uint16(np.around(detected_circles)) for pt in detected_circles[0, :]: a, b, r = pt[0], pt[1], pt[2] # Draw the circumference of the circle. cv2.circle(img, (a, b), r, (0, 255, 0), 2) # Draw a small circle (of radius 1) to show the center. cv2.circle(img, (a, b), 1, (0, 0, 255), 3) cv2.imshow("Detected Circle", img) cv2.waitKey(0) Output: Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 25749, "s": 25721, "text": "\n14 Jul, 2019" }, { "code": null, "e": 25977, "s": 25749, "text": "Circle detection finds a variety of uses in biomedical applications, ranging from iris detection to white blood cell segmentation. The technique followed is similar to the one used to detect lines, as discussed in this article." }, { "code": null, "e": 26004, "s": 25977, "text": "Basics of Circle Detection" }, { "code": null, "e": 26057, "s": 26004, "text": "A circle can be described by the following equation:" }, { "code": null, "e": 26512, "s": 26057, "text": "To detect circles, we may fix a point (x, y). Now, we are required to find 3 parameters: a, b and r. Therefore, the problem is in a 3-dimensional search space. To find possible circles, the algorithm uses a 3-D matrix called the “Accumulator Matrix” to store potential a, b and r values. The value of a (x-coordinate of the center) may range from 1 to rows, b (y-coordinate of the center) may range from 1 to cols, and r may range from 1 to maxRadius = ." }, { "code": null, "e": 26550, "s": 26512, "text": "Below are the steps of the algorithm." }, { "code": null, "e": 26657, "s": 26550, "text": "Initializing the Accumulator Matrix: Initialize a matrix of dimensions rows * cols * maxRadius with zeros." }, { "code": null, "e": 26809, "s": 26657, "text": "Pre-processing the image: Apply blurring, grayscale and an edge detector on the image. This is done to ensure the circles show as darkened image edges." }, { "code": null, "e": 26865, "s": 26809, "text": "Looping through the points: Pick a point on the image." }, { "code": null, "e": 27115, "s": 26865, "text": "Fixing r and looping through a and b: Use a double nested loop to find a value of r, varying a and b in the given ranges.for a in range(rows): for b in range(cols): r = math.sqrt((xi - a)**2 + (yi - b)**2) accum_matrix[a][b][r] += 1" }, { "code": "for a in range(rows): for b in range(cols): r = math.sqrt((xi - a)**2 + (yi - b)**2) accum_matrix[a][b][r] += 1", "e": 27244, "s": 27115, "text": null }, { "code": null, "e": 27453, "s": 27244, "text": "Voting: Pick the points in the accumulator matrix with the maximum value. These are strong points which indicate the existence of a circle with a, b and r parameters. This gives us the Hough space of circles." }, { "code": null, "e": 27626, "s": 27453, "text": "Finding Circles: Finally, using the above circles as candidate circles, vote according to the image. The maximum voted circle in the accumulator matrix gives us the circle." }, { "code": null, "e": 27736, "s": 27626, "text": "The HoughCircles function in OpenCV has the following parameters which can be altered according to the image." }, { "code": null, "e": 28524, "s": 27736, "text": "Detection Method: OpenCV has an advanced implementation, HOUGH_GRADIENT, which uses gradient of the edges instead of filling up the entire 3D accumulator matrix, thereby speeding up the process.dp: This is the ratio of the resolution of original image to the accumulator matrix.minDist: This parameter controls the minimum distance between detected circles.Param1: Canny edge detection requires two parameters — minVal and maxVal. Param1 is the higher threshold of the two. The second one is set as Param1/2.Param2: This is the accumulator threshold for the candidate detected circles. By increasing this threshold value, we can ensure that only the best circles, corresponding to larger accumulator values, are returned.minRadius: Minimum circle radius.maxRadius: Maximum circle radius." }, { "code": null, "e": 28601, "s": 28524, "text": "Below is the code for finding circles using OpenCV on the above input image." }, { "code": "import cv2import numpy as np # Read image.img = cv2.imread('eyes.jpg', cv2.IMREAD_COLOR) # Convert to grayscale.gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Blur using 3 * 3 kernel.gray_blurred = cv2.blur(gray, (3, 3)) # Apply Hough transform on the blurred image.detected_circles = cv2.HoughCircles(gray_blurred, cv2.HOUGH_GRADIENT, 1, 20, param1 = 50, param2 = 30, minRadius = 1, maxRadius = 40) # Draw circles that are detected.if detected_circles is not None: # Convert the circle parameters a, b and r to integers. detected_circles = np.uint16(np.around(detected_circles)) for pt in detected_circles[0, :]: a, b, r = pt[0], pt[1], pt[2] # Draw the circumference of the circle. cv2.circle(img, (a, b), r, (0, 255, 0), 2) # Draw a small circle (of radius 1) to show the center. cv2.circle(img, (a, b), 1, (0, 0, 255), 3) cv2.imshow(\"Detected Circle\", img) cv2.waitKey(0)", "e": 29581, "s": 28601, "text": null }, { "code": null, "e": 29589, "s": 29581, "text": "Output:" }, { "code": null, "e": 29606, "s": 29589, "text": "Image-Processing" }, { "code": null, "e": 29613, "s": 29606, "text": "OpenCV" }, { "code": null, "e": 29620, "s": 29613, "text": "Python" }, { "code": null, "e": 29718, "s": 29620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29736, "s": 29718, "text": "Python Dictionary" }, { "code": null, "e": 29768, "s": 29736, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29790, "s": 29768, "text": "Enumerate() in Python" }, { "code": null, "e": 29832, "s": 29790, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29858, "s": 29832, "text": "Python String | replace()" }, { "code": null, "e": 29887, "s": 29858, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29924, "s": 29887, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29966, "s": 29924, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30008, "s": 29966, "text": "Check if element exists in list in Python" } ]
Convert an ArrayList to HashSet in Java
To convert ArrayList to HashSet, firstly create an ArrayList − List<String> l = new ArrayList<String>(); Add elements to the ArrayList − l.add("Accent"); l.add("Speech"); l.add("Diction"); l.add("Tone"); l.add("Pronunciation"); Now convert the ArrayList to HashSet − Set<String> s = new HashSet<String>(l); The following is an example to convert an ArrayList to HashSet in Java. Live Demo import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args) { List<String> l = new ArrayList<String>(); l.add("Accent"); l.add("Speech"); l.add("Diction"); l.add("Tone"); l.add("Pronunciation"); Set<String> s = new HashSet<String>(l); System.out.println("HashSet elements..."); for (Object ob : s) System.out.println(ob); } } HashSet elements... Tone Pronunciation Accent Speech Diction
[ { "code": null, "e": 1125, "s": 1062, "text": "To convert ArrayList to HashSet, firstly create an ArrayList −" }, { "code": null, "e": 1167, "s": 1125, "text": "List<String> l = new ArrayList<String>();" }, { "code": null, "e": 1199, "s": 1167, "text": "Add elements to the ArrayList −" }, { "code": null, "e": 1290, "s": 1199, "text": "l.add(\"Accent\");\nl.add(\"Speech\");\nl.add(\"Diction\");\nl.add(\"Tone\");\nl.add(\"Pronunciation\");" }, { "code": null, "e": 1329, "s": 1290, "text": "Now convert the ArrayList to HashSet −" }, { "code": null, "e": 1369, "s": 1329, "text": "Set<String> s = new HashSet<String>(l);" }, { "code": null, "e": 1441, "s": 1369, "text": "The following is an example to convert an ArrayList to HashSet in Java." }, { "code": null, "e": 1452, "s": 1441, "text": " Live Demo" }, { "code": null, "e": 1942, "s": 1452, "text": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.HashSet;\npublic class Main {\n public static void main(String[] args) {\n List<String> l = new ArrayList<String>();\n l.add(\"Accent\");\n l.add(\"Speech\");\n l.add(\"Diction\");\n l.add(\"Tone\");\n l.add(\"Pronunciation\");\n Set<String> s = new HashSet<String>(l);\n System.out.println(\"HashSet elements...\");\n for (Object ob : s)\n System.out.println(ob);\n }\n}" }, { "code": null, "e": 2003, "s": 1942, "text": "HashSet elements...\nTone\nPronunciation\nAccent\nSpeech\nDiction" } ]
Try TextHero: The Absolute Simplest way to Clean and Analyze Text in Pandas | by Eric Kleppen | Towards Data Science
I am always on the lookout for new tools to help me simplify my natural language processing pipelines, so when I stumbled upon a short video clip showing Texthero’s functionality I knew I had to try it right away. Texthero is designed as a Pandas wrapper, so it makes it easier than ever to preprocess and analyze text based Pandas Series. Immediately, I pulled up the docs, opened a notebook and downloaded a couple thousand Reddit threads to analyze to give the new lib a test. NOTE: The Texthero library is still in beta! There might be bugs, and pipelines might change. I found a bug in the wordcloud functionality and reported it. It should be fixed in a coming update! I will look at these a lot closer when working with the code, but for a quick overview, Texthero is broke into four modules of functionality: The Preprocessing module is all about efficiently cleaning text-based Pandas series. It is primarily using Regular Expressions (regex) under the hood. The NLP module houses a few common NLP tasks, like Named Entity Recognition and Noun Chunks. It is using Spacy under the hood. The Representation module is used to create word vectors using different algorithms. It includes things like Principle Component Analysis and kMeans as well. It uses scikit-learn for TF-IDF and Count, and embeddings are loaded pre-computed from language models. The Visualization module is used to visualize the representations in a scatter plot or generate wordclouds. This module currently has only a few features and uses Plotly and WordCloud under the hood. Review the documentation for a complete list of features! Text preprocessing, representation and visualization from zero to hero.texthero.org Although installation was easy using pip, I encountered a conflict when trying to install it in my environment that has Apache Airflow due to a pandas version problem. Also, it took a while to install in a new environment since it uses so many other libraries on the backend. It downloads a couple additional things after importing for the first time too. For the dataset, I am using PRAW to pull data from Reddit. Check this article if you need a PRAW refresher. towardsdatascience.com !pip install textheroimport prawimport pandas as pd import texthero as herofrom config import cid, csec, ua #PRAW credentials Notice when you import Texthero for the first time, you will see it downloads a few things from NLTK and Spacy: I am pulling data from the Teaching subreddit to see if we can identify any themes around concern for starting school up in the fall in COVID heavy America. #create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)#list for df conversionposts = []#return 1000 new posts from teachingnew = reddit.subreddit('teaching').new(limit=1000)#return the important attributesfor post in new: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframedf = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsdf.head(3) PRAW makes it super easy to pull data from Reddit and load it into a pandas dataframe. Notice I pull 1000 new posts from teaching. The dataframe output will look something like this using df.head(3): The real selling point of the texthero library is its simplified preprocessing pipeline. Can’t remember regex syntax? Texthero has you covered! Simply call the .clean() method and pass the dataframe series: df['clean_title'] = hero.clean(df['title']) It runs the following seven functions by default when using clean() fillna(s) Replace not assigned values with empty spaces.lowercase(s) Lowercase all text.remove_digits() Remove all blocks of digits.remove_punctuation() Remove all string.punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).remove_diacritics() Remove all accents from strings.remove_stopwords() Remove all stop words.remove_whitespace() Remove all white space between words. fillna(s) Replace not assigned values with empty spaces. lowercase(s) Lowercase all text. remove_digits() Remove all blocks of digits. remove_punctuation() Remove all string.punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). remove_diacritics() Remove all accents from strings. remove_stopwords() Remove all stop words. remove_whitespace() Remove all white space between words. If the default doesn’t do what is needed, creating a custom cleaning pipeline is super simple. For example, if I want to keep stop-words and stem the included words, I can comment out remove_stopwords and add texthero.preprocessing.stem() to the pipeline: from texthero import preprocessing#create a custom cleaning pipelinecustom_pipeline = [preprocessing.fillna , preprocessing.lowercase , preprocessing.remove_digits , preprocessing.remove_punctuation , preprocessing.remove_diacritics #, preprocessing.remove_stopwords , preprocessing.remove_whitespace , preprocessing.stem]#pass the custom_pipeline to the pipeline argumentdf['clean_title'] = hero.clean(df['title'], pipeline = custom_pipeline)df.head() Notice the custom_pipeline is a list of preprocessing functions. Check out the documentation for the full list of preprocessing features! Inspecting top words is only 1 line of code, and that is something I like to do to see if there are additional words I should consider adding to the stop words list. Texthero doesn’t yet have bar graphs built into it, it only has scatter, so I’ll use Plotly express to visualize the top words in a bar graph. tw = hero.visualization.top_words(df['clean_title']).head(10)import plotly.express as pxfig = px.bar(tw)fig.show()tw.head() Stemming the words and adding “ ‘ “ (notice it between teachers and students) to the stop words should give me more unique words. Stemming was already added to the custom pipeline, but the stop words need to be added. Stop words can be added to the stop word list using union on the two lists: from texthero import stopwordsdefault_stopwords = stopwords.DEFAULT#add a list of stopwords to the stopwordscustom_stopwords = default_stopwords.union(set(["'"]))#Call remove_stopwords and pass the custom_stopwords listdf['clean_title'] = hero.remove_stopwords(df['clean_title'], custom_stopwords) Notice the custom_stopwords list is passed into hero.remove_stopwords(). I’ll re-visualize it and check the results! The results look a bit better after stemming and additional stop words have been applied! Thanks to Panda’s .pipe(), chaining the Texthero module components together is super simple. To visualize the title, I am going to use Principle Component Analysis to compress the vector space. I am also going to run K-means clustering to add color. Remember, Texthero takes a Series as input and Series as output so I can set the output to be a new column in the dataframe. #Add pca value to dataframe to use as visualization coordinatesdf['pca'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.pca) )#Add k-means cluster to dataframe df['kmeans'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.kmeans) )df.head() PCA and K-means clustering have been applied using only a few lines of code! Now the data can be visualized using hero.scatterplot() #generate scatter plothero.scatterplot(df, 'pca', color = 'kmeans', hover_data=['title'] ) Since it uses Plotly under the hood, the scatter plot is as interactive as you’d expect! It can be zoomed in as needed. Now it is time to explore visualised results and see what insights can be gained! Although the library is still in beta, I see a promising future for Texthero and hope it gets the love it deserves. It makes cleaning and preparing text in Pandas dataframes a breeze. I hope a few more visualization options get added, but the scatter plot is a great start. If you’re interested in learning more about Natural Language Processing, check out my other articles covering some basic and advanced topics. towardsdatascience.com towardsdatascience.com towardsdatascience.com Thanks for reading. Here is the complete code: #create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)#list for df conversionposts = []#return 1000 new posts from teachingnew = reddit.subreddit('teaching').new(limit=1000)#return the important attributesfor post in new: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframedf = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsdf.head(3)from texthero import preprocessingcustom_pipeline = [preprocessing.fillna , preprocessing.lowercase , preprocessing.remove_digits , preprocessing.remove_punctuation , preprocessing.remove_diacritics , preprocessing.remove_stopwords , preprocessing.remove_whitespace , preprocessing.stem]df['clean_title'] = hero.clean(df['title'], pipeline = custom_pipeline)df.head()from texthero import stopwordsdefault_stopwords = stopwords.DEFAULTcustom_stopwords = default_stopwords.union(set(["'"]))df['clean_title'] = hero.remove_stopwords(df['clean_title'], custom_stopwords)hero.visualization.top_words(df['clean_title'])tw = hero.visualization.top_words(df['clean_title']).head(10)import plotly.express as pxfig = px.bar(tw)fig.show()df['pca'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.pca) )df['kmeans'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.kmeans) )hero.scatterplot(df, 'pca', color = 'kmeans', hover_data=['title'] ) If you enjoyed this, follow me on Medium for more Get FULL ACCESS and help support my content by subscribing Let’s connect on LinkedIn Analyze Data using Python? Check out my website — Eric Kleppen
[ { "code": null, "e": 651, "s": 171, "text": "I am always on the lookout for new tools to help me simplify my natural language processing pipelines, so when I stumbled upon a short video clip showing Texthero’s functionality I knew I had to try it right away. Texthero is designed as a Pandas wrapper, so it makes it easier than ever to preprocess and analyze text based Pandas Series. Immediately, I pulled up the docs, opened a notebook and downloaded a couple thousand Reddit threads to analyze to give the new lib a test." }, { "code": null, "e": 846, "s": 651, "text": "NOTE: The Texthero library is still in beta! There might be bugs, and pipelines might change. I found a bug in the wordcloud functionality and reported it. It should be fixed in a coming update!" }, { "code": null, "e": 988, "s": 846, "text": "I will look at these a lot closer when working with the code, but for a quick overview, Texthero is broke into four modules of functionality:" }, { "code": null, "e": 1139, "s": 988, "text": "The Preprocessing module is all about efficiently cleaning text-based Pandas series. It is primarily using Regular Expressions (regex) under the hood." }, { "code": null, "e": 1266, "s": 1139, "text": "The NLP module houses a few common NLP tasks, like Named Entity Recognition and Noun Chunks. It is using Spacy under the hood." }, { "code": null, "e": 1528, "s": 1266, "text": "The Representation module is used to create word vectors using different algorithms. It includes things like Principle Component Analysis and kMeans as well. It uses scikit-learn for TF-IDF and Count, and embeddings are loaded pre-computed from language models." }, { "code": null, "e": 1728, "s": 1528, "text": "The Visualization module is used to visualize the representations in a scatter plot or generate wordclouds. This module currently has only a few features and uses Plotly and WordCloud under the hood." }, { "code": null, "e": 1786, "s": 1728, "text": "Review the documentation for a complete list of features!" }, { "code": null, "e": 1870, "s": 1786, "text": "Text preprocessing, representation and visualization from zero to hero.texthero.org" }, { "code": null, "e": 2226, "s": 1870, "text": "Although installation was easy using pip, I encountered a conflict when trying to install it in my environment that has Apache Airflow due to a pandas version problem. Also, it took a while to install in a new environment since it uses so many other libraries on the backend. It downloads a couple additional things after importing for the first time too." }, { "code": null, "e": 2334, "s": 2226, "text": "For the dataset, I am using PRAW to pull data from Reddit. Check this article if you need a PRAW refresher." }, { "code": null, "e": 2357, "s": 2334, "text": "towardsdatascience.com" }, { "code": null, "e": 2483, "s": 2357, "text": "!pip install textheroimport prawimport pandas as pd import texthero as herofrom config import cid, csec, ua #PRAW credentials" }, { "code": null, "e": 2595, "s": 2483, "text": "Notice when you import Texthero for the first time, you will see it downloads a few things from NLTK and Spacy:" }, { "code": null, "e": 2752, "s": 2595, "text": "I am pulling data from the Teaching subreddit to see if we can identify any themes around concern for starting school up in the fall in COVID heavy America." }, { "code": null, "e": 3349, "s": 2752, "text": "#create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)#list for df conversionposts = []#return 1000 new posts from teachingnew = reddit.subreddit('teaching').new(limit=1000)#return the important attributesfor post in new: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframedf = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsdf.head(3)" }, { "code": null, "e": 3549, "s": 3349, "text": "PRAW makes it super easy to pull data from Reddit and load it into a pandas dataframe. Notice I pull 1000 new posts from teaching. The dataframe output will look something like this using df.head(3):" }, { "code": null, "e": 3756, "s": 3549, "text": "The real selling point of the texthero library is its simplified preprocessing pipeline. Can’t remember regex syntax? Texthero has you covered! Simply call the .clean() method and pass the dataframe series:" }, { "code": null, "e": 3800, "s": 3756, "text": "df['clean_title'] = hero.clean(df['title'])" }, { "code": null, "e": 3868, "s": 3800, "text": "It runs the following seven functions by default when using clean()" }, { "code": null, "e": 4237, "s": 3868, "text": "fillna(s) Replace not assigned values with empty spaces.lowercase(s) Lowercase all text.remove_digits() Remove all blocks of digits.remove_punctuation() Remove all string.punctuation (!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~).remove_diacritics() Remove all accents from strings.remove_stopwords() Remove all stop words.remove_whitespace() Remove all white space between words." }, { "code": null, "e": 4294, "s": 4237, "text": "fillna(s) Replace not assigned values with empty spaces." }, { "code": null, "e": 4327, "s": 4294, "text": "lowercase(s) Lowercase all text." }, { "code": null, "e": 4372, "s": 4327, "text": "remove_digits() Remove all blocks of digits." }, { "code": null, "e": 4459, "s": 4372, "text": "remove_punctuation() Remove all string.punctuation (!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~)." }, { "code": null, "e": 4512, "s": 4459, "text": "remove_diacritics() Remove all accents from strings." }, { "code": null, "e": 4554, "s": 4512, "text": "remove_stopwords() Remove all stop words." }, { "code": null, "e": 4612, "s": 4554, "text": "remove_whitespace() Remove all white space between words." }, { "code": null, "e": 4868, "s": 4612, "text": "If the default doesn’t do what is needed, creating a custom cleaning pipeline is super simple. For example, if I want to keep stop-words and stem the included words, I can comment out remove_stopwords and add texthero.preprocessing.stem() to the pipeline:" }, { "code": null, "e": 5447, "s": 4868, "text": "from texthero import preprocessing#create a custom cleaning pipelinecustom_pipeline = [preprocessing.fillna , preprocessing.lowercase , preprocessing.remove_digits , preprocessing.remove_punctuation , preprocessing.remove_diacritics #, preprocessing.remove_stopwords , preprocessing.remove_whitespace , preprocessing.stem]#pass the custom_pipeline to the pipeline argumentdf['clean_title'] = hero.clean(df['title'], pipeline = custom_pipeline)df.head()" }, { "code": null, "e": 5585, "s": 5447, "text": "Notice the custom_pipeline is a list of preprocessing functions. Check out the documentation for the full list of preprocessing features!" }, { "code": null, "e": 5894, "s": 5585, "text": "Inspecting top words is only 1 line of code, and that is something I like to do to see if there are additional words I should consider adding to the stop words list. Texthero doesn’t yet have bar graphs built into it, it only has scatter, so I’ll use Plotly express to visualize the top words in a bar graph." }, { "code": null, "e": 6018, "s": 5894, "text": "tw = hero.visualization.top_words(df['clean_title']).head(10)import plotly.express as pxfig = px.bar(tw)fig.show()tw.head()" }, { "code": null, "e": 6312, "s": 6018, "text": "Stemming the words and adding “ ‘ “ (notice it between teachers and students) to the stop words should give me more unique words. Stemming was already added to the custom pipeline, but the stop words need to be added. Stop words can be added to the stop word list using union on the two lists:" }, { "code": null, "e": 6610, "s": 6312, "text": "from texthero import stopwordsdefault_stopwords = stopwords.DEFAULT#add a list of stopwords to the stopwordscustom_stopwords = default_stopwords.union(set([\"'\"]))#Call remove_stopwords and pass the custom_stopwords listdf['clean_title'] = hero.remove_stopwords(df['clean_title'], custom_stopwords)" }, { "code": null, "e": 6727, "s": 6610, "text": "Notice the custom_stopwords list is passed into hero.remove_stopwords(). I’ll re-visualize it and check the results!" }, { "code": null, "e": 6817, "s": 6727, "text": "The results look a bit better after stemming and additional stop words have been applied!" }, { "code": null, "e": 7192, "s": 6817, "text": "Thanks to Panda’s .pipe(), chaining the Texthero module components together is super simple. To visualize the title, I am going to use Principle Component Analysis to compress the vector space. I am also going to run K-means clustering to add color. Remember, Texthero takes a Series as input and Series as output so I can set the output to be a new column in the dataframe." }, { "code": null, "e": 7509, "s": 7192, "text": "#Add pca value to dataframe to use as visualization coordinatesdf['pca'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.pca) )#Add k-means cluster to dataframe df['kmeans'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.kmeans) )df.head()" }, { "code": null, "e": 7642, "s": 7509, "text": "PCA and K-means clustering have been applied using only a few lines of code! Now the data can be visualized using hero.scatterplot()" }, { "code": null, "e": 7733, "s": 7642, "text": "#generate scatter plothero.scatterplot(df, 'pca', color = 'kmeans', hover_data=['title'] )" }, { "code": null, "e": 7935, "s": 7733, "text": "Since it uses Plotly under the hood, the scatter plot is as interactive as you’d expect! It can be zoomed in as needed. Now it is time to explore visualised results and see what insights can be gained!" }, { "code": null, "e": 8351, "s": 7935, "text": "Although the library is still in beta, I see a promising future for Texthero and hope it gets the love it deserves. It makes cleaning and preparing text in Pandas dataframes a breeze. I hope a few more visualization options get added, but the scatter plot is a great start. If you’re interested in learning more about Natural Language Processing, check out my other articles covering some basic and advanced topics." }, { "code": null, "e": 8374, "s": 8351, "text": "towardsdatascience.com" }, { "code": null, "e": 8397, "s": 8374, "text": "towardsdatascience.com" }, { "code": null, "e": 8420, "s": 8397, "text": "towardsdatascience.com" }, { "code": null, "e": 8467, "s": 8420, "text": "Thanks for reading. Here is the complete code:" }, { "code": null, "e": 10195, "s": 8467, "text": "#create a reddit connectionreddit = praw.Reddit(client_id= cid, client_secret= csec, user_agent= ua)#list for df conversionposts = []#return 1000 new posts from teachingnew = reddit.subreddit('teaching').new(limit=1000)#return the important attributesfor post in new: posts.append([post.title, post.score, post.num_comments, post.selftext, post.created, post.pinned, post.total_awards_received])#create a dataframedf = pd.DataFrame(posts,columns=['title', 'score', 'comments', 'post', 'created', 'pinned', 'total awards'])#return top 3 df rowsdf.head(3)from texthero import preprocessingcustom_pipeline = [preprocessing.fillna , preprocessing.lowercase , preprocessing.remove_digits , preprocessing.remove_punctuation , preprocessing.remove_diacritics , preprocessing.remove_stopwords , preprocessing.remove_whitespace , preprocessing.stem]df['clean_title'] = hero.clean(df['title'], pipeline = custom_pipeline)df.head()from texthero import stopwordsdefault_stopwords = stopwords.DEFAULTcustom_stopwords = default_stopwords.union(set([\"'\"]))df['clean_title'] = hero.remove_stopwords(df['clean_title'], custom_stopwords)hero.visualization.top_words(df['clean_title'])tw = hero.visualization.top_words(df['clean_title']).head(10)import plotly.express as pxfig = px.bar(tw)fig.show()df['pca'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.pca) )df['kmeans'] = ( df['clean_title'] .pipe(hero.tfidf) .pipe(hero.kmeans) )hero.scatterplot(df, 'pca', color = 'kmeans', hover_data=['title'] )" }, { "code": null, "e": 10245, "s": 10195, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 10304, "s": 10245, "text": "Get FULL ACCESS and help support my content by subscribing" }, { "code": null, "e": 10330, "s": 10304, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 10378, "s": 10330, "text": "Analyze Data using Python? Check out my website" } ]
Batch Script - Align Right
This used to align text to the right, which is normally used to improve readability of number columns. @echo off set x = 1000 set y = 1 set y = %y% echo %x% set y = %y:~-4% echo %y% A few key things to note about the above program is − Spaces are added to the variable of y, in this case we are adding 9 spaces to the variable of y. Spaces are added to the variable of y, in this case we are adding 9 spaces to the variable of y. We are using the ~-4 option to say that we just want to show the last 4 characters of the string y. We are using the ~-4 option to say that we just want to show the last 4 characters of the string y. The above command produces the following output. The key thing to note is that the value of 2 is aligned to match the units columns when displaying numbers. 1000 1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2272, "s": 2169, "text": "This used to align text to the right, which is normally used to improve readability of number columns." }, { "code": null, "e": 2358, "s": 2272, "text": "@echo off \nset x = 1000 \nset y = 1 \nset y = %y% \necho %x% \n\nset y = %y:~-4% \necho %y%" }, { "code": null, "e": 2412, "s": 2358, "text": "A few key things to note about the above program is −" }, { "code": null, "e": 2509, "s": 2412, "text": "Spaces are added to the variable of y, in this case we are adding 9 spaces to the variable of y." }, { "code": null, "e": 2606, "s": 2509, "text": "Spaces are added to the variable of y, in this case we are adding 9 spaces to the variable of y." }, { "code": null, "e": 2706, "s": 2606, "text": "We are using the ~-4 option to say that we just want to show the last 4 characters of the string y." }, { "code": null, "e": 2806, "s": 2706, "text": "We are using the ~-4 option to say that we just want to show the last 4 characters of the string y." }, { "code": null, "e": 2963, "s": 2806, "text": "The above command produces the following output. The key thing to note is that the value of 2 is aligned to match the units columns when displaying numbers." }, { "code": null, "e": 2971, "s": 2963, "text": "1000\n1\n" }, { "code": null, "e": 2978, "s": 2971, "text": " Print" }, { "code": null, "e": 2989, "s": 2978, "text": " Add Notes" } ]
Create Left to Right slide animation in Android?
This example demonstrates how do I create left to right side animation in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" android:id="@+id/relativeLayout" tools:context=".MainActivity"> <Button android:id="@+id/btnSlideLeft" android:text="Slide Left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="30dp"/> <Button android:id="@+id/btnSlideRight" android:text="Slide Right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btnSlideLeft" android:layout_centerHorizontal="true" android:layout_marginTop="10dp"/> <TextView android:layout_centerInParent="true" android:text="Cristiano Ronaldo is the Best Player in the World" android:visibility="invisible" android:textSize="16sp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView"/> <TextView android:layout_centerInParent="true" android:text="Messi is the Best Player in the World" android:layout_below="@id/textView" android:visibility="invisible" android:textSize="16sp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView1"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.transition.Slide; import android.transition.TransitionManager; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button btnSlideLeft, btnSlideRight; TextView textView, textView1; RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); textView1 = findViewById(R.id.textView1); btnSlideLeft = findViewById(R.id.btnSlideLeft); btnSlideRight = findViewById(R.id.btnSlideRight); relativeLayout = findViewById(R.id.relativeLayout); btnSlideLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Slide slide = new Slide(); slide.setSlideEdge(Gravity.START); TransitionManager.beginDelayedTransition(relativeLayout, slide); textView.setVisibility(View.VISIBLE); } }); btnSlideRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Slide slide = new Slide(); slide.setSlideEdge(Gravity.END); TransitionManager.beginDelayedTransition(relativeLayout, slide); textView1.setVisibility(View.VISIBLE); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I create left to right side animation in android." }, { "code": null, "e": 1274, "s": 1145, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2964, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n android:id=\"@+id/relativeLayout\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnSlideLeft\"\n android:text=\"Slide Left\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"30dp\"/>\n <Button\n android:id=\"@+id/btnSlideRight\"\n android:text=\"Slide Right\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnSlideLeft\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"10dp\"/>\n <TextView\n android:layout_centerInParent=\"true\"\n android:text=\"Cristiano Ronaldo is the Best Player in the World\"\n android:visibility=\"invisible\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"/>\n <TextView\n android:layout_centerInParent=\"true\"\n android:text=\"Messi is the Best Player in the World\"\n android:layout_below=\"@id/textView\"\n android:visibility=\"invisible\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView1\"/>\n</RelativeLayout>" }, { "code": null, "e": 3021, "s": 2964, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4633, "s": 3021, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.transition.Slide;\nimport android.transition.TransitionManager;\nimport android.view.Gravity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n Button btnSlideLeft, btnSlideRight;\n TextView textView, textView1;\n RelativeLayout relativeLayout;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n textView1 = findViewById(R.id.textView1);\n btnSlideLeft = findViewById(R.id.btnSlideLeft);\n btnSlideRight = findViewById(R.id.btnSlideRight);\n relativeLayout = findViewById(R.id.relativeLayout);\n btnSlideLeft.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Slide slide = new Slide();\n slide.setSlideEdge(Gravity.START);\n TransitionManager.beginDelayedTransition(relativeLayout, slide);\n textView.setVisibility(View.VISIBLE);\n }\n });\n btnSlideRight.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Slide slide = new Slide();\n slide.setSlideEdge(Gravity.END);\n TransitionManager.beginDelayedTransition(relativeLayout, slide);\n textView1.setVisibility(View.VISIBLE);\n }\n });\n }\n}" }, { "code": null, "e": 4688, "s": 4633, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5358, "s": 4688, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5705, "s": 5358, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5746, "s": 5705, "text": "Click here to download the project code." } ]
How to write a comment in a JSP page?
JSP comment marks to text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out", a part of your JSP page. Following is the syntax of the JSP comments − <%-- This is JSP comment --%> Following example shows the JSP Comments − <html> <head> <title>A Comment Test</title> </head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html> The above code will generate the following result − A Test of Comments There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary −
[ { "code": null, "e": 1229, "s": 1062, "text": "JSP comment marks to text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or \"comment out\", a part of your JSP page." }, { "code": null, "e": 1275, "s": 1229, "text": "Following is the syntax of the JSP comments −" }, { "code": null, "e": 1305, "s": 1275, "text": "<%-- This is JSP comment --%>" }, { "code": null, "e": 1348, "s": 1305, "text": "Following example shows the JSP Comments −" }, { "code": null, "e": 1543, "s": 1348, "text": "<html>\n <head>\n <title>A Comment Test</title>\n </head>\n <body>\n <h2>A Test of Comments</h2>\n <%-- This comment will not be visible in the page source --%>\n </body>\n</html>" }, { "code": null, "e": 1595, "s": 1543, "text": "The above code will generate the following result −" }, { "code": null, "e": 1614, "s": 1595, "text": "A Test of Comments" }, { "code": null, "e": 1785, "s": 1614, "text": "There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary −" } ]
How to Run 30 Machine Learning Models with a Few Lines of Code | by Ismael Araujo | Towards Data Science
When starting a new supervised Machine Learning project, one of the first steps is to analyze the data, understand what we are trying to accomplish, and which machine learning algorithms could help us achieve our goals. While the scikit-learn library makes our lives easier by making possible to run models with a few lines of code, it can also be time-consuming when you need to test multiple models. However, what if we could run multiple vanilla models at once before diving into more complex approaches and have a better idea of what models in which we should invest our precious time? That’s what lazy predict tries (successfully) to accomplish. It runs 30 machine learning models in just a few seconds and gives us a grasp of how models will perform with our dataset. To better understand how we can use lazy predict, I created a Titanic Survivor Prediction project so that you can code along. You can find the full notebook here. You can code along with me. Basic experience with Python, Pandas, and scikit-learn will help you better understand what is going on. Importing and cleaning data First, let's import pyforest. PyForest imports the 40 most popular Python libraries with one line of code. I wrote an article about it, and you can find it here. I will turn some ugly warning messages off using the warning library. I will also import some metrics libraries. We will need it later on. import pyforestimport warningswarnings.filterwarnings("ignore")from sklearn import metricsfrom sklearn.metrics import accuracy_score Now, let's import the dataset we will be using from Kaggle. You can find the dataset on this link. Note that I didn't import Pandas. That's because it comes included with pyforest. # importing .csv files using Pandastrain = pd.read_csv(‘train.csv’)test = pd.read_csv(‘test.csv’) I will skip some Exploratory Data Analysis in this article because our primary focus is to start using lazypredict. However, in my initial EDA that you can find in my GitHub, I noticed that we need to convert the column Sex into numeric. We can easily do that with a lambda function. train['Sex'] = train['Sex'].apply(lambda x: 1 if x == 'male' else 2) We can also drop a few categorical columns that we will not be used for this micro project. For homework, I recommend you trying to play around with these features when you finish this article. train.drop(columns=[‘Name’,’Ticket’,’Cabin’, ‘PassengerId’, ‘Parch’, ‘Embarked’], inplace=True) Train Test Split Let's now split our train set into the variables X and y. I will address all the features to X, except Survived, which is our target label. X = train.drop([‘Survived’], axis=1)y = train.Survived And now, let's split the variable into train and test sets. I will go with the default 0.25 for the test size. You can easily add other values using. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) Modeling with LazyPredict Now it's time for some fun. If this is your first time using lazypredict, you will have to install it. To do so, you can type pip install lazypredict in your terminal. If you already have it installed, let's import it to your project. Since this is a classification project, let's import LazyClassifier as well. import lazypredictfrom lazypredict.Supervised import LazyClassifier Finally, let's run the models and see how it goes. clf = LazyClassifier(verbose=0,ignore_warnings=True)models, predictions = clf.fit(X_train, X_test, y_train, y_test)models Voilá. You just iterated over 30 models in less than 2 seconds. That is incredibly fast and effortless. However, how can we make sure that these results are accurate? Well, we can now check the results by running a few models and comparing them. For this project, I will test the dataset with a Random Forest and Logistic Regression model. Let’s see if we can get anywhere close to the results we just saw. Let’s start with Random Forest. rf = RandomForestClassifier()rf.fit(X_train, y_train)y_pred = rf.predict(X_test) As we can see, the accuracy and F1-Score got a very similar result. Let's now try Logistic Regression. rf = LogisticRegression()rf.fit(X_train, y_train)y_pred_lr = rf.predict(X_test) Again, we got a very similar result. It seems that the results are trustworthy. That was easy. Conclusion lazypredict is an easy and fast library that gives a good prediction of how our models will behave if your dataset. Keep in mind that the results obtained with lazy predict SHOULD NOT be considered final models. Statistics is a large component of Data Science, and since different models have different approaches, you should know how each of the models works before choosing your final one. More importantly, Data Science is a complex field, and there aren’t magic solutions without pros and cons. Use it as your first iteration to confirm your approach planned and always double-check the results using tools such as scikit-learn. Have fun and let me know if it worked for you!
[ { "code": null, "e": 762, "s": 172, "text": "When starting a new supervised Machine Learning project, one of the first steps is to analyze the data, understand what we are trying to accomplish, and which machine learning algorithms could help us achieve our goals. While the scikit-learn library makes our lives easier by making possible to run models with a few lines of code, it can also be time-consuming when you need to test multiple models. However, what if we could run multiple vanilla models at once before diving into more complex approaches and have a better idea of what models in which we should invest our precious time?" }, { "code": null, "e": 1242, "s": 762, "text": "That’s what lazy predict tries (successfully) to accomplish. It runs 30 machine learning models in just a few seconds and gives us a grasp of how models will perform with our dataset. To better understand how we can use lazy predict, I created a Titanic Survivor Prediction project so that you can code along. You can find the full notebook here. You can code along with me. Basic experience with Python, Pandas, and scikit-learn will help you better understand what is going on." }, { "code": null, "e": 1270, "s": 1242, "text": "Importing and cleaning data" }, { "code": null, "e": 1571, "s": 1270, "text": "First, let's import pyforest. PyForest imports the 40 most popular Python libraries with one line of code. I wrote an article about it, and you can find it here. I will turn some ugly warning messages off using the warning library. I will also import some metrics libraries. We will need it later on." }, { "code": null, "e": 1704, "s": 1571, "text": "import pyforestimport warningswarnings.filterwarnings(\"ignore\")from sklearn import metricsfrom sklearn.metrics import accuracy_score" }, { "code": null, "e": 1885, "s": 1704, "text": "Now, let's import the dataset we will be using from Kaggle. You can find the dataset on this link. Note that I didn't import Pandas. That's because it comes included with pyforest." }, { "code": null, "e": 1983, "s": 1885, "text": "# importing .csv files using Pandastrain = pd.read_csv(‘train.csv’)test = pd.read_csv(‘test.csv’)" }, { "code": null, "e": 2267, "s": 1983, "text": "I will skip some Exploratory Data Analysis in this article because our primary focus is to start using lazypredict. However, in my initial EDA that you can find in my GitHub, I noticed that we need to convert the column Sex into numeric. We can easily do that with a lambda function." }, { "code": null, "e": 2336, "s": 2267, "text": "train['Sex'] = train['Sex'].apply(lambda x: 1 if x == 'male' else 2)" }, { "code": null, "e": 2530, "s": 2336, "text": "We can also drop a few categorical columns that we will not be used for this micro project. For homework, I recommend you trying to play around with these features when you finish this article." }, { "code": null, "e": 2626, "s": 2530, "text": "train.drop(columns=[‘Name’,’Ticket’,’Cabin’, ‘PassengerId’, ‘Parch’, ‘Embarked’], inplace=True)" }, { "code": null, "e": 2643, "s": 2626, "text": "Train Test Split" }, { "code": null, "e": 2783, "s": 2643, "text": "Let's now split our train set into the variables X and y. I will address all the features to X, except Survived, which is our target label." }, { "code": null, "e": 2838, "s": 2783, "text": "X = train.drop([‘Survived’], axis=1)y = train.Survived" }, { "code": null, "e": 2988, "s": 2838, "text": "And now, let's split the variable into train and test sets. I will go with the default 0.25 for the test size. You can easily add other values using." }, { "code": null, "e": 3063, "s": 2988, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)" }, { "code": null, "e": 3089, "s": 3063, "text": "Modeling with LazyPredict" }, { "code": null, "e": 3401, "s": 3089, "text": "Now it's time for some fun. If this is your first time using lazypredict, you will have to install it. To do so, you can type pip install lazypredict in your terminal. If you already have it installed, let's import it to your project. Since this is a classification project, let's import LazyClassifier as well." }, { "code": null, "e": 3469, "s": 3401, "text": "import lazypredictfrom lazypredict.Supervised import LazyClassifier" }, { "code": null, "e": 3520, "s": 3469, "text": "Finally, let's run the models and see how it goes." }, { "code": null, "e": 3642, "s": 3520, "text": "clf = LazyClassifier(verbose=0,ignore_warnings=True)models, predictions = clf.fit(X_train, X_test, y_train, y_test)models" }, { "code": null, "e": 4082, "s": 3642, "text": "Voilá. You just iterated over 30 models in less than 2 seconds. That is incredibly fast and effortless. However, how can we make sure that these results are accurate? Well, we can now check the results by running a few models and comparing them. For this project, I will test the dataset with a Random Forest and Logistic Regression model. Let’s see if we can get anywhere close to the results we just saw. Let’s start with Random Forest." }, { "code": null, "e": 4163, "s": 4082, "text": "rf = RandomForestClassifier()rf.fit(X_train, y_train)y_pred = rf.predict(X_test)" }, { "code": null, "e": 4266, "s": 4163, "text": "As we can see, the accuracy and F1-Score got a very similar result. Let's now try Logistic Regression." }, { "code": null, "e": 4346, "s": 4266, "text": "rf = LogisticRegression()rf.fit(X_train, y_train)y_pred_lr = rf.predict(X_test)" }, { "code": null, "e": 4441, "s": 4346, "text": "Again, we got a very similar result. It seems that the results are trustworthy. That was easy." }, { "code": null, "e": 4452, "s": 4441, "text": "Conclusion" } ]
Divide array into increasing and decreasing subsequence without changing the order - GeeksforGeeks
14 Sep, 2021 Given a merged sequence which consists of two sequences which got merged, one of them was strictly increasing and the other was strictly decreasing. Elements of increasing sequence were inserted between elements of the decreasing one without changing the order. Sequences [1, 3, 4] and [10, 4, 2] can produce the following resulting sequences: [10, 1, 3, 4, 2, 4], [1, 3, 4, 10, 4, 2]. The following sequence cannot be the result of these insertions: [1, 10, 4, 4, 3, 2] because the order of elements in the increasing sequence was changed. Given a merged sequence, the task is to find any two suitable initial sequences, one of them should be strictly increasing, and another should be strictly decreasing. Note: An empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Examples: Input: arr[] = {5, 1, 3, 6, 8, 2, 9, 0, 10} Output: [1, 3, 6, 8, 9, 10] [5, 2, 0] Input: arr[] = {1, 2, 4, 0, 2} Output: -1 No such sequences possible. Method 1: We can modify Longest Increasing Sequence) and solve the required problem. It will take O(nlogn) time. Method 2: We can also solve this problem only in a single traversal. The Idea used here is that maintain two sorted arrays. For a new element x, If it can be appended to only one of the arrays then append it. If it can be appended to neither, then the answer is -1. If it can be appended to both then check the next element y, if y > x then append x to the increasing one otherwise append x to the decreasing one. Now when we encounter an element which can be included in both the sequence we need to decide based on the next element’s value. Let’s consider a situation where we need to iterate over the remaining value x,y,z where ( x < z < y) and we have already the last element of the increasing and decreasing sequence as inc and dec respectively from the visited portion of the array. Case 1 : x<y and inc<x<dec so we can include x in any sequence. If we include it in decreasing sequence then dec will become x. And then for y we have only one choice i.e. to include it in increasing sequence as y>dec and inc becomes y. If we do this we cannot insert z in any sequence as z>dec and z<inc. But if we include x to increasing sequence (inc becomes x) and y to decreasing sequence (dec becomes y) following the same logic then we can place z in any sequence and get an answer. Case 2 : x>=y and inc<x<dec it follows the same logic as above. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print strictly increasing and// strictly decreasing sequence if possiblevoid Find_Sequence(int arr[], int n){ // Arrays to store strictly increasing and // decreasing sequence vector<int> inc_arr, dec_arr; // Initializing last element of both sequence int flag = 0; long inc = -1, dec = 1e7; // Iterating through the array for (int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.emplace_back(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.emplace_back(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.emplace_back(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.emplace_back(arr[i]); } // Else we can not make such sequences // from the given array else { cout << -1 << endl; flag = 1; break; } } // Print the required sequences if (!flag) { for (auto i = inc_arr.begin(); i != inc_arr.end(); i++) cout << *i << " "; cout << endl; for (auto i = dec_arr.begin(); i != dec_arr.end(); i++) cout << *i << " "; cout << endl; }} // Driver codeint main(){ int arr[] = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Find_Sequence(arr, n);} // This code is contributed by sanjeev2552 // Java implementation of the approachimport java.util.*; class GFG{ // Function to print strictly increasing and // strictly decreasing sequence if possible static void Find_Sequence(int[] arr, int n) { // Arrays to store strictly increasing and // decreasing sequence Vector<Integer> inc_arr = new Vector<>(), dec_arr = new Vector<>(); // Initializing last element of both sequence int flag = 0; long inc = -1, dec = (long) 1e7; // Iterating through the array for (int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.add(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.add(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.add(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.add(arr[i]); } // Else we can not make such sequences // from the given array else { System.out.println(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { for (int i : inc_arr) System.out.print(i + " "); System.out.println(); for (int i : dec_arr) System.out.print(i + " "); System.out.println(); } } // Driver Code public static void main(String[] args) { int[] arr = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = arr.length; Find_Sequence(arr, n); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the approach # Function to print strictly increasing and# strictly decreasing sequence if possibledef Find_Sequence(array, n): # Arrays to store strictly increasing and # decreasing sequence inc_arr, dec_arr =[], [] # Initializing last element of both sequence inc, dec = -1, 1e7 # Iterating through the array for i in range(n): # If current element can be appended # to both the sequences if inc < array[i] < dec: # If next element is greater than # the current element # Then append it to the strictly # increasing array if array[i] < array[i + 1]: inc = array[i] inc_arr.append(array[i]) # Otherwise append it to the # strictly decreasing array else: dec = array[i] dec_arr.append(array[i]) # If current element can be appended # to the increasing sequence only elif inc < array[i]: inc = array[i] inc_arr.append(array[i]) # If current element can be appended # to the decreasing sequence only elif dec > array[i]: dec = array[i] dec_arr.append(array[i]) # Else we can not make such sequences # from the given array else: print('-1') break # Print the required sequences else: print(inc_arr, dec_arr) # Driver codearr = [5, 1, 3, 6, 8, 2, 9, 0, 10]n = len(arr)Find_Sequence(arr, n) // C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print strictly increasing and// strictly decreasing sequence if possiblestatic void Find_Sequence(int[] arr, int n){ // Arrays to store strictly increasing and // decreasing sequence ArrayList inc_arr = new ArrayList(); ArrayList dec_arr = new ArrayList(); // Initializing last element of both sequence int flag = 0; long inc = -1, dec = (long)1e7; // Iterating through the array for(int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.Add(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.Add(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.Add(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.Add(arr[i]); } // Else we can not make such sequences // from the given array else { Console.Write(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { foreach(int i in inc_arr) Console.Write(i + " "); Console.Write('\n'); foreach(int i in dec_arr) Console.Write(i + " "); Console.Write('\n'); }} // Driver Codepublic static void Main(string[] args){ int[] arr = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = arr.Length; Find_Sequence(arr, n);}} // This code is contributed by rutvik_56 <?php// Php implementation of the approach // Function to print strictly increasing and// strictly decreasing sequence if possiblefunction Find_Sequence($arr, $n){ // Arrays to store strictly increasing and // decreasing sequence $inc_arr = array(); $dec_arr = array(); // Initializing last element of both sequence $inc = -1; $dec = 1e7; // Iterating through the array for ($i = 0; $i < $n ; $i++) { // If current element can be appended // to both the sequences if ($inc < $arr[$i] && $arr[$i] < $dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if ($arr[$i] < $arr[$i + 1]) { $inc = $arr[$i]; array_push($inc_arr, $arr[$i]); } // Otherwise append it to the // strictly decreasing array else { $dec = $arr[$i]; array_push($dec_arr, $arr[$i]); } } // If current element can be appended // to the increasing sequence only else if ($inc < $arr[$i]) { $inc = $arr[$i]; array_push($inc_arr, $arr[$i]); } // If current element can be appended // to the decreasing sequence only else if($dec > $arr[$i]) { $dec = $arr[$i]; array_push($dec_arr, $arr[$i]); } // Else we can not make such sequences // from the given array else { echo '-1'; break; } } // Print the required sequences print_r($inc_arr); print_r($dec_arr);} // Driver code$arr = array(5, 1, 3, 6, 8, 2, 9, 0, 10);$n = count($arr);Find_Sequence($arr, $n); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to print strictly increasing and // strictly decreasing sequence if possible function Find_Sequence(arr, n) { // Arrays to store strictly increasing and // decreasing sequence let inc_arr =[], dec_arr = []; // Initializing last element of both sequence let flag = 0; let inc = -1, dec = 1e7; // Iterating through the array for (let i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.push(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.push(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.push(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.push(arr[i]); } // Else we can not make such sequences // from the given array else { document.write(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { document.write("["); for (let i in inc_arr) document.write( inc_arr[i] + " "); document.write("] "); document.write("["); for (let i in dec_arr) document.write( dec_arr[i] + " "); document.write("]"); } } // Driver Code let arr = [ 5, 1, 3, 6, 8, 2, 9, 0, 10 ]; let n = arr.length; Find_Sequence(arr, n); // This code is contributed by target_2.</script> [1, 3, 6, 8, 9, 10] [5, 2, 0] ankthon sanjeev2552 rutvik_56 target_2 khushboogoyal499 Debomit Dey Constructive Algorithms subsequence Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 25498, "s": 25470, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25760, "s": 25498, "text": "Given a merged sequence which consists of two sequences which got merged, one of them was strictly increasing and the other was strictly decreasing. Elements of increasing sequence were inserted between elements of the decreasing one without changing the order." }, { "code": null, "e": 26040, "s": 25760, "text": "Sequences [1, 3, 4] and [10, 4, 2] can produce the following resulting sequences: [10, 1, 3, 4, 2, 4], [1, 3, 4, 10, 4, 2]. The following sequence cannot be the result of these insertions: [1, 10, 4, 4, 3, 2] because the order of elements in the increasing sequence was changed. " }, { "code": null, "e": 26331, "s": 26040, "text": "Given a merged sequence, the task is to find any two suitable initial sequences, one of them should be strictly increasing, and another should be strictly decreasing. Note: An empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Examples: " }, { "code": null, "e": 26413, "s": 26331, "text": "Input: arr[] = {5, 1, 3, 6, 8, 2, 9, 0, 10} Output: [1, 3, 6, 8, 9, 10] [5, 2, 0]" }, { "code": null, "e": 26484, "s": 26413, "text": "Input: arr[] = {1, 2, 4, 0, 2} Output: -1 No such sequences possible. " }, { "code": null, "e": 26597, "s": 26484, "text": "Method 1: We can modify Longest Increasing Sequence) and solve the required problem. It will take O(nlogn) time." }, { "code": null, "e": 26743, "s": 26597, "text": "Method 2: We can also solve this problem only in a single traversal. The Idea used here is that maintain two sorted arrays. For a new element x, " }, { "code": null, "e": 26807, "s": 26743, "text": "If it can be appended to only one of the arrays then append it." }, { "code": null, "e": 26864, "s": 26807, "text": "If it can be appended to neither, then the answer is -1." }, { "code": null, "e": 27012, "s": 26864, "text": "If it can be appended to both then check the next element y, if y > x then append x to the increasing one otherwise append x to the decreasing one." }, { "code": null, "e": 27390, "s": 27012, "text": "Now when we encounter an element which can be included in both the sequence we need to decide based on the next element’s value. Let’s consider a situation where we need to iterate over the remaining value x,y,z where ( x < z < y) and we have already the last element of the increasing and decreasing sequence as inc and dec respectively from the visited portion of the array. " }, { "code": null, "e": 27417, "s": 27390, "text": "Case 1 : x<y and inc<x<dec" }, { "code": null, "e": 27455, "s": 27417, "text": "so we can include x in any sequence. " }, { "code": null, "e": 27698, "s": 27455, "text": "If we include it in decreasing sequence then dec will become x. And then for y we have only one choice i.e. to include it in increasing sequence as y>dec and inc becomes y. If we do this we cannot insert z in any sequence as z>dec and z<inc. " }, { "code": null, "e": 27882, "s": 27698, "text": "But if we include x to increasing sequence (inc becomes x) and y to decreasing sequence (dec becomes y) following the same logic then we can place z in any sequence and get an answer." }, { "code": null, "e": 27910, "s": 27882, "text": "Case 2 : x>=y and inc<x<dec" }, { "code": null, "e": 27946, "s": 27910, "text": "it follows the same logic as above." }, { "code": null, "e": 27998, "s": 27946, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28002, "s": 27998, "text": "C++" }, { "code": null, "e": 28007, "s": 28002, "text": "Java" }, { "code": null, "e": 28015, "s": 28007, "text": "Python3" }, { "code": null, "e": 28018, "s": 28015, "text": "C#" }, { "code": null, "e": 28022, "s": 28018, "text": "PHP" }, { "code": null, "e": 28033, "s": 28022, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print strictly increasing and// strictly decreasing sequence if possiblevoid Find_Sequence(int arr[], int n){ // Arrays to store strictly increasing and // decreasing sequence vector<int> inc_arr, dec_arr; // Initializing last element of both sequence int flag = 0; long inc = -1, dec = 1e7; // Iterating through the array for (int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.emplace_back(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.emplace_back(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.emplace_back(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.emplace_back(arr[i]); } // Else we can not make such sequences // from the given array else { cout << -1 << endl; flag = 1; break; } } // Print the required sequences if (!flag) { for (auto i = inc_arr.begin(); i != inc_arr.end(); i++) cout << *i << \" \"; cout << endl; for (auto i = dec_arr.begin(); i != dec_arr.end(); i++) cout << *i << \" \"; cout << endl; }} // Driver codeint main(){ int arr[] = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Find_Sequence(arr, n);} // This code is contributed by sanjeev2552", "e": 30261, "s": 28033, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to print strictly increasing and // strictly decreasing sequence if possible static void Find_Sequence(int[] arr, int n) { // Arrays to store strictly increasing and // decreasing sequence Vector<Integer> inc_arr = new Vector<>(), dec_arr = new Vector<>(); // Initializing last element of both sequence int flag = 0; long inc = -1, dec = (long) 1e7; // Iterating through the array for (int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.add(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.add(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.add(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.add(arr[i]); } // Else we can not make such sequences // from the given array else { System.out.println(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { for (int i : inc_arr) System.out.print(i + \" \"); System.out.println(); for (int i : dec_arr) System.out.print(i + \" \"); System.out.println(); } } // Driver Code public static void main(String[] args) { int[] arr = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = arr.length; Find_Sequence(arr, n); }} // This code is contributed by// sanjeev2552", "e": 32741, "s": 30261, "text": null }, { "code": "# Python3 implementation of the approach # Function to print strictly increasing and# strictly decreasing sequence if possibledef Find_Sequence(array, n): # Arrays to store strictly increasing and # decreasing sequence inc_arr, dec_arr =[], [] # Initializing last element of both sequence inc, dec = -1, 1e7 # Iterating through the array for i in range(n): # If current element can be appended # to both the sequences if inc < array[i] < dec: # If next element is greater than # the current element # Then append it to the strictly # increasing array if array[i] < array[i + 1]: inc = array[i] inc_arr.append(array[i]) # Otherwise append it to the # strictly decreasing array else: dec = array[i] dec_arr.append(array[i]) # If current element can be appended # to the increasing sequence only elif inc < array[i]: inc = array[i] inc_arr.append(array[i]) # If current element can be appended # to the decreasing sequence only elif dec > array[i]: dec = array[i] dec_arr.append(array[i]) # Else we can not make such sequences # from the given array else: print('-1') break # Print the required sequences else: print(inc_arr, dec_arr) # Driver codearr = [5, 1, 3, 6, 8, 2, 9, 0, 10]n = len(arr)Find_Sequence(arr, n)", "e": 34296, "s": 32741, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print strictly increasing and// strictly decreasing sequence if possiblestatic void Find_Sequence(int[] arr, int n){ // Arrays to store strictly increasing and // decreasing sequence ArrayList inc_arr = new ArrayList(); ArrayList dec_arr = new ArrayList(); // Initializing last element of both sequence int flag = 0; long inc = -1, dec = (long)1e7; // Iterating through the array for(int i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.Add(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.Add(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.Add(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.Add(arr[i]); } // Else we can not make such sequences // from the given array else { Console.Write(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { foreach(int i in inc_arr) Console.Write(i + \" \"); Console.Write('\\n'); foreach(int i in dec_arr) Console.Write(i + \" \"); Console.Write('\\n'); }} // Driver Codepublic static void Main(string[] args){ int[] arr = { 5, 1, 3, 6, 8, 2, 9, 0, 10 }; int n = arr.Length; Find_Sequence(arr, n);}} // This code is contributed by rutvik_56", "e": 36552, "s": 34296, "text": null }, { "code": "<?php// Php implementation of the approach // Function to print strictly increasing and// strictly decreasing sequence if possiblefunction Find_Sequence($arr, $n){ // Arrays to store strictly increasing and // decreasing sequence $inc_arr = array(); $dec_arr = array(); // Initializing last element of both sequence $inc = -1; $dec = 1e7; // Iterating through the array for ($i = 0; $i < $n ; $i++) { // If current element can be appended // to both the sequences if ($inc < $arr[$i] && $arr[$i] < $dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if ($arr[$i] < $arr[$i + 1]) { $inc = $arr[$i]; array_push($inc_arr, $arr[$i]); } // Otherwise append it to the // strictly decreasing array else { $dec = $arr[$i]; array_push($dec_arr, $arr[$i]); } } // If current element can be appended // to the increasing sequence only else if ($inc < $arr[$i]) { $inc = $arr[$i]; array_push($inc_arr, $arr[$i]); } // If current element can be appended // to the decreasing sequence only else if($dec > $arr[$i]) { $dec = $arr[$i]; array_push($dec_arr, $arr[$i]); } // Else we can not make such sequences // from the given array else { echo '-1'; break; } } // Print the required sequences print_r($inc_arr); print_r($dec_arr);} // Driver code$arr = array(5, 1, 3, 6, 8, 2, 9, 0, 10);$n = count($arr);Find_Sequence($arr, $n); // This code is contributed by Ryuga?>", "e": 38429, "s": 36552, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print strictly increasing and // strictly decreasing sequence if possible function Find_Sequence(arr, n) { // Arrays to store strictly increasing and // decreasing sequence let inc_arr =[], dec_arr = []; // Initializing last element of both sequence let flag = 0; let inc = -1, dec = 1e7; // Iterating through the array for (let i = 0; i < n; i++) { // If current element can be appended // to both the sequences if (inc < arr[i] && arr[i] < dec) { // If next element is greater than // the current element // Then append it to the strictly // increasing array if (arr[i] < arr[i + 1]) { inc = arr[i]; inc_arr.push(arr[i]); } // Otherwise append it to the // strictly decreasing array else { dec = arr[i]; dec_arr.push(arr[i]); } } // If current element can be appended // to the increasing sequence only else if (inc < arr[i]) { inc = arr[i]; inc_arr.push(arr[i]); } // If current element can be appended // to the decreasing sequence only else if (dec > arr[i]) { dec = arr[i]; dec_arr.push(arr[i]); } // Else we can not make such sequences // from the given array else { document.write(-1); flag = 1; break; } } // Print the required sequences if (flag == 0) { document.write(\"[\"); for (let i in inc_arr) document.write( inc_arr[i] + \" \"); document.write(\"] \"); document.write(\"[\"); for (let i in dec_arr) document.write( dec_arr[i] + \" \"); document.write(\"]\"); } } // Driver Code let arr = [ 5, 1, 3, 6, 8, 2, 9, 0, 10 ]; let n = arr.length; Find_Sequence(arr, n); // This code is contributed by target_2.</script>", "e": 40891, "s": 38429, "text": null }, { "code": null, "e": 40921, "s": 40891, "text": "[1, 3, 6, 8, 9, 10] [5, 2, 0]" }, { "code": null, "e": 40931, "s": 40923, "text": "ankthon" }, { "code": null, "e": 40943, "s": 40931, "text": "sanjeev2552" }, { "code": null, "e": 40953, "s": 40943, "text": "rutvik_56" }, { "code": null, "e": 40962, "s": 40953, "text": "target_2" }, { "code": null, "e": 40979, "s": 40962, "text": "khushboogoyal499" }, { "code": null, "e": 40991, "s": 40979, "text": "Debomit Dey" }, { "code": null, "e": 41015, "s": 40991, "text": "Constructive Algorithms" }, { "code": null, "e": 41027, "s": 41015, "text": "subsequence" }, { "code": null, "e": 41034, "s": 41027, "text": "Arrays" }, { "code": null, "e": 41041, "s": 41034, "text": "Greedy" }, { "code": null, "e": 41048, "s": 41041, "text": "Arrays" }, { "code": null, "e": 41055, "s": 41048, "text": "Greedy" }, { "code": null, "e": 41153, "s": 41055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41162, "s": 41153, "text": "Comments" }, { "code": null, "e": 41175, "s": 41162, "text": "Old Comments" }, { "code": null, "e": 41223, "s": 41175, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 41267, "s": 41223, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 41290, "s": 41267, "text": "Introduction to Arrays" }, { "code": null, "e": 41322, "s": 41290, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41336, "s": 41322, "text": "Linear Search" }, { "code": null, "e": 41387, "s": 41336, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 41445, "s": 41387, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 41496, "s": 41445, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 41527, "s": 41496, "text": "Huffman Coding | Greedy Algo-3" } ]
How to stretch and scale background image using CSS? - GeeksforGeeks
27 Feb, 2019 The background-size property is used to stretch and scale background image. This property set the size of background image. Here we will see all possible examples of background-size and background-scale property. Syntax: background-size: auto|length|cover|contain|initial|inherit; cover: This property value is used to stretch the background-image in x and y direction and cover the whole area.length: This property value is used to scale the background-image. It change the background-image size. The length value can be in form of px, em, % etc. Example 1: This example stretches the background-image in x and y direction. <!DOCTYPE html><html> <head> <style> /*background-size: 100% auto with no repeat */ #example1 { width:600px; /* screen width */ height:200px; /* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: 100% auto; } /*background-size:auto with no repeat*/ #example2 { width:600px; /* screen width */ height:200px; /* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: auto; } /* background-size: cover with no repeat */ #example3 { border: 2px solid black; width:600px; /* screen width */ height:200px; /* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: cover; } </style> </head> <body> <h2>background-size: 100% auto :</h2> <p> The background image is displayed in its original size. </p> <div id="example1"></div> <h2>background-size: auto (default):</h2> <p>The background image is set to auto.</p> <div id="example2"></div> <h2>background-size: cover:</h2> <p> The background image is set to cover to specified area. </p> <div id="example3"></div> </body></html> Output: Example 2: This example scales the background-image. <!DOCTYPE html><html> <head> <style> /*background-size: initial with no repeat */ #example1 { width:600px;/* screen width */ height:200px;/* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: initial; } /*background-size: contain with repeat */ #example2 { border: 2px solid black; width:600px;/* screen width */ height:200px;/* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-size: contain; } /*background-size: 300px 100px with no repeat */ #example3 { border: 2px solid black; width:600px;/* screen width */ height:200px;/* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: 300px 100px; } </style> </head> <body> <h2>background-size: initial:</h2> <p>The background image is set to initial.</p> <div id="example1"></div> <h2>background-size: contain:</h2> <p>The background image is set to contain.</p> <div id="example2"></div> <h2>background-size: 300px 100px:</h2> <p>The background image is set in pixel size.</p> <div id="example3"></div> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24506, "s": 24478, "text": "\n27 Feb, 2019" }, { "code": null, "e": 24719, "s": 24506, "text": "The background-size property is used to stretch and scale background image. This property set the size of background image. Here we will see all possible examples of background-size and background-scale property." }, { "code": null, "e": 24727, "s": 24719, "text": "Syntax:" }, { "code": null, "e": 24787, "s": 24727, "text": "background-size: auto|length|cover|contain|initial|inherit;" }, { "code": null, "e": 25054, "s": 24787, "text": "cover: This property value is used to stretch the background-image in x and y direction and cover the whole area.length: This property value is used to scale the background-image. It change the background-image size. The length value can be in form of px, em, % etc." }, { "code": null, "e": 25131, "s": 25054, "text": "Example 1: This example stretches the background-image in x and y direction." }, { "code": "<!DOCTYPE html><html> <head> <style> /*background-size: 100% auto with no repeat */ #example1 { width:600px; /* screen width */ height:200px; /* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: 100% auto; } /*background-size:auto with no repeat*/ #example2 { width:600px; /* screen width */ height:200px; /* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: auto; } /* background-size: cover with no repeat */ #example3 { border: 2px solid black; width:600px; /* screen width */ height:200px; /* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: cover; } </style> </head> <body> <h2>background-size: 100% auto :</h2> <p> The background image is displayed in its original size. </p> <div id=\"example1\"></div> <h2>background-size: auto (default):</h2> <p>The background image is set to auto.</p> <div id=\"example2\"></div> <h2>background-size: cover:</h2> <p> The background image is set to cover to specified area. </p> <div id=\"example3\"></div> </body></html> ", "e": 26892, "s": 25131, "text": null }, { "code": null, "e": 26900, "s": 26892, "text": "Output:" }, { "code": null, "e": 26953, "s": 26900, "text": "Example 2: This example scales the background-image." }, { "code": "<!DOCTYPE html><html> <head> <style> /*background-size: initial with no repeat */ #example1 { width:600px;/* screen width */ height:200px;/* screen height */ border: 2px solid black; background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: initial; } /*background-size: contain with repeat */ #example2 { border: 2px solid black; width:600px;/* screen width */ height:200px;/* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-size: contain; } /*background-size: 300px 100px with no repeat */ #example3 { border: 2px solid black; width:600px;/* screen width */ height:200px;/* screen height */ background: url(https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-45-8.png); background-repeat: no-repeat; background-size: 300px 100px; } </style> </head> <body> <h2>background-size: initial:</h2> <p>The background image is set to initial.</p> <div id=\"example1\"></div> <h2>background-size: contain:</h2> <p>The background image is set to contain.</p> <div id=\"example2\"></div> <h2>background-size: 300px 100px:</h2> <p>The background image is set in pixel size.</p> <div id=\"example3\"></div> </body></html>", "e": 28604, "s": 26953, "text": null }, { "code": null, "e": 28612, "s": 28604, "text": "Output:" }, { "code": null, "e": 28749, "s": 28612, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28758, "s": 28749, "text": "CSS-Misc" }, { "code": null, "e": 28765, "s": 28758, "text": "Picked" }, { "code": null, "e": 28769, "s": 28765, "text": "CSS" }, { "code": null, "e": 28774, "s": 28769, "text": "HTML" }, { "code": null, "e": 28791, "s": 28774, "text": "Web Technologies" }, { "code": null, "e": 28796, "s": 28791, "text": "HTML" }, { "code": null, "e": 28894, "s": 28796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28952, "s": 28894, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28989, "s": 28952, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29053, "s": 28989, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29090, "s": 29053, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29131, "s": 29090, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 29191, "s": 29131, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29252, "s": 29191, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29305, "s": 29252, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29355, "s": 29305, "text": "How to Insert Form Data into Database using PHP ?" } ]
Destructuring of Props in ReactJS - GeeksforGeeks
24 May, 2021 Destructuring is a simple property that is used to make code much clear and readable, mainly when we pass props in React. What is Destructuring? Destructuring is a characteristic of JavaScript, It is used to take out sections of data from an array or objects, We can assign them to new own variables created by the developer. In destructuring, It does not change an array or any object, it makes a copy of the desired object or array element by assigning them in its own new variables, later we can use this new variable in React (class or functional) components. It makes the code more clear. When we access the props using this keyword, we have to use this/ this.props throughout the program, but by the use of restructuring, we can discard this/ this.props by assigning them in new variables. This is very difficult to monitor props in complex applications, so by assigning these props in new own variables we can make a code more readable. Advantages of Destructuring: It makes developer’s life easy, by assigning their own variables. Nested data is more complex, it takes time to access, but by the use of destructuring, we can access faster of nested data. It improves the sustainability, readability of code. It helps to cut the amount of code used in an application. It trims the number of steps taken to access data properties. It provides components with the exact data properties. It saves time from iterate over an array of objects multiple times. In ReactJS We use multiple times ternary operators inside the render function, without destructuring it looks complex and hard to access them, but by the use of destructuring, we can improve the readability of ternary operators. How to use Destructuring? We can use the Destructuring in the following method in ReactJS: 1. Using this.props method In this example, we are going to simply display some words using destructuring and without destructuring. Project Structure: It will look like the following. Destructuring gives access to the use of props in a more readable format and discards the need for props for every property. App.js: Now write down the following code in the App.js file. Here, App is our default component where we will print our component code. Javascript import React from "react"import Greet from './component/Greet' class App extends React.component{ render(){ return( <div className = "App"> <Greet active="KAPIL GARG" activeStatus = "CSE"/> </div> ); }}export default App; Greet.js: In this file, We will write component code about the destructuring process. Without Destructuring:App.jsApp.jsimport React from 'react'; const Greet = props =>{ return ( <div> <div className="XYZ"> <h3> {props.active} </h3> </div> <div className="PQR"> <h1>{props.activeStatus}</h1> </div> </div> ) }export default Greet;Output: Here props are unnecessarily coming again inside the return, so more concise names of these Destructuring properties are used.Output for Without Destructuring App.js import React from 'react'; const Greet = props =>{ return ( <div> <div className="XYZ"> <h3> {props.active} </h3> </div> <div className="PQR"> <h1>{props.activeStatus}</h1> </div> </div> ) }export default Greet; Output: Here props are unnecessarily coming again inside the return, so more concise names of these Destructuring properties are used. Output for Without Destructuring With Destructuring:App.jsApp.jsimport React from 'react'; const Greet = props =>{ // Destructuring const {active, activeStatus} = props; return ( <div> <div className="XYZ"> <h3> {active} </h3> </div> <div className="PQR"> <h1>{activeStatus}</h1> </div> </div> ) }export default Greet;Output:Output for With Destructuring App.js import React from 'react'; const Greet = props =>{ // Destructuring const {active, activeStatus} = props; return ( <div> <div className="XYZ"> <h3> {active} </h3> </div> <div className="PQR"> <h1>{activeStatus}</h1> </div> </div> ) }export default Greet; Output: Output for With Destructuring 2. Using the Extraction method: There are many times when the value extracted during Destructuring no more exist, then in this condition we can use of default behavior of Destructuring, in this, apply a default value to the newly declared properties of Destructuring In the following code, the activeObject will be set true if it is undefined in this.props. Const {active, activeStatus, activeObject = true } = this.props 3. Using the Re-assigning method: A variable name that is not a copy of the property being destructured may be used. This is achieved by reassigning as shown below. In the following code, the properties active, activeStatus have been destructured and reassigned as variables named generating, objectMessage. const { active : generating, activeStatus : objectMessage} = this.props ReactJS-Advanced JavaScript ReactJS 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 Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n24 May, 2021" }, { "code": null, "e": 25434, "s": 25312, "text": "Destructuring is a simple property that is used to make code much clear and readable, mainly when we pass props in React." }, { "code": null, "e": 25457, "s": 25434, "text": "What is Destructuring?" }, { "code": null, "e": 25638, "s": 25457, "text": "Destructuring is a characteristic of JavaScript, It is used to take out sections of data from an array or objects, We can assign them to new own variables created by the developer." }, { "code": null, "e": 25876, "s": 25638, "text": "In destructuring, It does not change an array or any object, it makes a copy of the desired object or array element by assigning them in its own new variables, later we can use this new variable in React (class or functional) components." }, { "code": null, "e": 26108, "s": 25876, "text": "It makes the code more clear. When we access the props using this keyword, we have to use this/ this.props throughout the program, but by the use of restructuring, we can discard this/ this.props by assigning them in new variables." }, { "code": null, "e": 26256, "s": 26108, "text": "This is very difficult to monitor props in complex applications, so by assigning these props in new own variables we can make a code more readable." }, { "code": null, "e": 26285, "s": 26256, "text": "Advantages of Destructuring:" }, { "code": null, "e": 26351, "s": 26285, "text": "It makes developer’s life easy, by assigning their own variables." }, { "code": null, "e": 26475, "s": 26351, "text": "Nested data is more complex, it takes time to access, but by the use of destructuring, we can access faster of nested data." }, { "code": null, "e": 26528, "s": 26475, "text": "It improves the sustainability, readability of code." }, { "code": null, "e": 26587, "s": 26528, "text": "It helps to cut the amount of code used in an application." }, { "code": null, "e": 26649, "s": 26587, "text": "It trims the number of steps taken to access data properties." }, { "code": null, "e": 26704, "s": 26649, "text": "It provides components with the exact data properties." }, { "code": null, "e": 26772, "s": 26704, "text": "It saves time from iterate over an array of objects multiple times." }, { "code": null, "e": 27001, "s": 26772, "text": "In ReactJS We use multiple times ternary operators inside the render function, without destructuring it looks complex and hard to access them, but by the use of destructuring, we can improve the readability of ternary operators." }, { "code": null, "e": 27027, "s": 27001, "text": "How to use Destructuring?" }, { "code": null, "e": 27092, "s": 27027, "text": "We can use the Destructuring in the following method in ReactJS:" }, { "code": null, "e": 27119, "s": 27092, "text": "1. Using this.props method" }, { "code": null, "e": 27225, "s": 27119, "text": "In this example, we are going to simply display some words using destructuring and without destructuring." }, { "code": null, "e": 27277, "s": 27225, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27402, "s": 27277, "text": "Destructuring gives access to the use of props in a more readable format and discards the need for props for every property." }, { "code": null, "e": 27539, "s": 27402, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we will print our component code." }, { "code": null, "e": 27550, "s": 27539, "text": "Javascript" }, { "code": "import React from \"react\"import Greet from './component/Greet' class App extends React.component{ render(){ return( <div className = \"App\"> <Greet active=\"KAPIL GARG\" activeStatus = \"CSE\"/> </div> ); }}export default App;", "e": 27815, "s": 27550, "text": null }, { "code": null, "e": 27901, "s": 27815, "text": "Greet.js: In this file, We will write component code about the destructuring process." }, { "code": null, "e": 28414, "s": 27901, "text": "Without Destructuring:App.jsApp.jsimport React from 'react'; const Greet = props =>{ return ( <div> <div className=\"XYZ\"> <h3> {props.active} </h3> </div> <div className=\"PQR\"> <h1>{props.activeStatus}</h1> </div> </div> ) }export default Greet;Output: Here props are unnecessarily coming again inside the return, so more concise names of these Destructuring properties are used.Output for Without Destructuring" }, { "code": null, "e": 28421, "s": 28414, "text": "App.js" }, { "code": "import React from 'react'; const Greet = props =>{ return ( <div> <div className=\"XYZ\"> <h3> {props.active} </h3> </div> <div className=\"PQR\"> <h1>{props.activeStatus}</h1> </div> </div> ) }export default Greet;", "e": 28734, "s": 28421, "text": null }, { "code": null, "e": 28869, "s": 28734, "text": "Output: Here props are unnecessarily coming again inside the return, so more concise names of these Destructuring properties are used." }, { "code": null, "e": 28902, "s": 28869, "text": "Output for Without Destructuring" }, { "code": null, "e": 29331, "s": 28902, "text": "With Destructuring:App.jsApp.jsimport React from 'react'; const Greet = props =>{ // Destructuring const {active, activeStatus} = props; return ( <div> <div className=\"XYZ\"> <h3> {active} </h3> </div> <div className=\"PQR\"> <h1>{activeStatus}</h1> </div> </div> ) }export default Greet;Output:Output for With Destructuring" }, { "code": null, "e": 29338, "s": 29331, "text": "App.js" }, { "code": "import React from 'react'; const Greet = props =>{ // Destructuring const {active, activeStatus} = props; return ( <div> <div className=\"XYZ\"> <h3> {active} </h3> </div> <div className=\"PQR\"> <h1>{activeStatus}</h1> </div> </div> ) }export default Greet;", "e": 29700, "s": 29338, "text": null }, { "code": null, "e": 29708, "s": 29700, "text": "Output:" }, { "code": null, "e": 29738, "s": 29708, "text": "Output for With Destructuring" }, { "code": null, "e": 29770, "s": 29738, "text": "2. Using the Extraction method:" }, { "code": null, "e": 30005, "s": 29770, "text": "There are many times when the value extracted during Destructuring no more exist, then in this condition we can use of default behavior of Destructuring, in this, apply a default value to the newly declared properties of Destructuring" }, { "code": null, "e": 30096, "s": 30005, "text": "In the following code, the activeObject will be set true if it is undefined in this.props." }, { "code": null, "e": 30160, "s": 30096, "text": "Const {active, activeStatus, activeObject = true } = this.props" }, { "code": null, "e": 30194, "s": 30160, "text": "3. Using the Re-assigning method:" }, { "code": null, "e": 30325, "s": 30194, "text": "A variable name that is not a copy of the property being destructured may be used. This is achieved by reassigning as shown below." }, { "code": null, "e": 30468, "s": 30325, "text": "In the following code, the properties active, activeStatus have been destructured and reassigned as variables named generating, objectMessage." }, { "code": null, "e": 30540, "s": 30468, "text": "const { active : generating, activeStatus : objectMessage} = this.props" }, { "code": null, "e": 30557, "s": 30540, "text": "ReactJS-Advanced" }, { "code": null, "e": 30568, "s": 30557, "text": "JavaScript" }, { "code": null, "e": 30576, "s": 30568, "text": "ReactJS" }, { "code": null, "e": 30674, "s": 30576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30735, "s": 30674, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30776, "s": 30735, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30816, "s": 30776, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30870, "s": 30816, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30918, "s": 30870, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30961, "s": 30918, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31006, "s": 30961, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 31071, "s": 31006, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 31139, "s": 31071, "text": "How to pass data from one component to other component in ReactJS ?" } ]
PHP for loops
The for loop - Loops through a block of code a specified number of times. The for loop is used when you know in advance how many times the script should run. Parameters: init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value The example below displays the numbers from 0 to 10: $x = 0; - Initialize the loop counter ($x), and set the start value to 0 $x <= 10; - Continue the loop as long as $x is less than or equal to 10 $x++ - Increase the loop counter value by 1 for each iteration This example counts to 100 by tens: $x = 0; - Initialize the loop counter ($x), and set the start value to 0 $x <= 100; - Continue the loop as long as $x is less than or equal to 100 $x+=10 - Increase the loop counter value by 10 for each iteration Create a loop that runs from 0 to 9. ($i = 0; $i < 10; ) { echo $i; } 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.
[ { "code": null, "e": 74, "s": 0, "text": "The for loop - Loops through a block of code a specified number of times." }, { "code": null, "e": 158, "s": 74, "text": "The for loop is used when you know in advance how many times the script should run." }, { "code": null, "e": 170, "s": 158, "text": "Parameters:" }, { "code": null, "e": 218, "s": 170, "text": "init counter: Initialize the loop counter value" }, { "code": null, "e": 353, "s": 218, "text": "test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends." }, { "code": null, "e": 405, "s": 353, "text": "increment counter: Increases the loop counter value" }, { "code": null, "e": 458, "s": 405, "text": "The example below displays the numbers from 0 to 10:" }, { "code": null, "e": 531, "s": 458, "text": "$x = 0; - Initialize the loop counter ($x), and set the start value to 0" }, { "code": null, "e": 603, "s": 531, "text": "$x <= 10; - Continue the loop as long as $x is less than or equal to 10" }, { "code": null, "e": 666, "s": 603, "text": "$x++ - Increase the loop counter value by 1 for each iteration" }, { "code": null, "e": 702, "s": 666, "text": "This example counts to 100 by tens:" }, { "code": null, "e": 775, "s": 702, "text": "$x = 0; - Initialize the loop counter ($x), and set the start value to 0" }, { "code": null, "e": 849, "s": 775, "text": "$x <= 100; - Continue the loop as long as $x is less than or equal to 100" }, { "code": null, "e": 915, "s": 849, "text": "$x+=10 - Increase the loop counter value by 10 for each iteration" }, { "code": null, "e": 952, "s": 915, "text": "Create a loop that runs from 0 to 9." }, { "code": null, "e": 989, "s": 952, "text": " ($i = 0; $i < 10; ) {\n echo $i;\n}\n" }, { "code": null, "e": 1022, "s": 989, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1064, "s": 1022, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1171, "s": 1064, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1190, "s": 1171, "text": "help@w3schools.com" } ]
Django Form submission without Page Reload - GeeksforGeeks
16 Feb, 2021 Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. In this article we will see form submission in django without reloading the page using Jquery and Ajax For installing django open cmd or terminal and write below command pip3 install django Then create new project django-admin startproject newproj cd newproj Then for creating new app Windows python manage.py startapp main Ubuntu python3 manage.py startapp main Add your app name in settings.py Create new directory inside app and name it as templates inside that create another directory and name it as main(Your app name) Run this command to migrate python manage.py migrate Create new model inside models.py models.py Python3 from django.db import models # Create your models here.class Todo(models.Model): task = models.CharField(max_length=200) def __str__(self): return f"{self.task}" python manage.py makemigrations python manage.py migrate admin.py Python3 from django.contrib import adminfrom .models import *# Register your models here. admin.site.register(Todo) Create new file inside templates directory and name it as form.html HTML <!DOCTYPE html><html><head> <title>Todo List</title></head><body> <form method="post" id="task-form"> {% csrf_token %} <input type="text" placeholder="Enter Task" name="task" id="task" required> <button type="submit">Save</button> </form> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).on('submit','#task-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "home" %}', data: { task:$("#task").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert('Saved'); } }) }); </script> </body></html> Create new view inside views.py to handle get and post request. Python3 from django.shortcuts import renderfrom .models import Todo# Create your views here.def home(request): if request.method == 'POST': task=request.POST.get('task') print(task) new = Todo(task=task) new.save() return render(request,"main/form.html") Create new file inside your app and name it as urls.py Python3 from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name="home"),] Add main.urls in project urls myproj/urls.py Python3 from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include("main.urls"))] To run the app write command python manage.py runserver Output Admin Page Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n16 Feb, 2021" }, { "code": null, "e": 24617, "s": 24318, "text": "Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source." }, { "code": null, "e": 24720, "s": 24617, "text": "In this article we will see form submission in django without reloading the page using Jquery and Ajax" }, { "code": null, "e": 24787, "s": 24720, "text": "For installing django open cmd or terminal and write below command" }, { "code": null, "e": 24807, "s": 24787, "text": "pip3 install django" }, { "code": null, "e": 24831, "s": 24807, "text": "Then create new project" }, { "code": null, "e": 24865, "s": 24831, "text": "django-admin startproject newproj" }, { "code": null, "e": 24876, "s": 24865, "text": "cd newproj" }, { "code": null, "e": 24903, "s": 24876, "text": "Then for creating new app " }, { "code": null, "e": 24911, "s": 24903, "text": "Windows" }, { "code": null, "e": 24942, "s": 24911, "text": "python manage.py startapp main" }, { "code": null, "e": 24949, "s": 24942, "text": "Ubuntu" }, { "code": null, "e": 24981, "s": 24949, "text": "python3 manage.py startapp main" }, { "code": null, "e": 25014, "s": 24981, "text": "Add your app name in settings.py" }, { "code": null, "e": 25143, "s": 25014, "text": "Create new directory inside app and name it as templates inside that create another directory and name it as main(Your app name)" }, { "code": null, "e": 25171, "s": 25143, "text": "Run this command to migrate" }, { "code": null, "e": 25196, "s": 25171, "text": "python manage.py migrate" }, { "code": null, "e": 25230, "s": 25196, "text": "Create new model inside models.py" }, { "code": null, "e": 25240, "s": 25230, "text": "models.py" }, { "code": null, "e": 25248, "s": 25240, "text": "Python3" }, { "code": "from django.db import models # Create your models here.class Todo(models.Model): task = models.CharField(max_length=200) def __str__(self): return f\"{self.task}\"", "e": 25426, "s": 25248, "text": null }, { "code": null, "e": 25458, "s": 25426, "text": "python manage.py makemigrations" }, { "code": null, "e": 25483, "s": 25458, "text": "python manage.py migrate" }, { "code": null, "e": 25492, "s": 25483, "text": "admin.py" }, { "code": null, "e": 25500, "s": 25492, "text": "Python3" }, { "code": "from django.contrib import adminfrom .models import *# Register your models here. admin.site.register(Todo)", "e": 25609, "s": 25500, "text": null }, { "code": null, "e": 25677, "s": 25609, "text": "Create new file inside templates directory and name it as form.html" }, { "code": null, "e": 25682, "s": 25677, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Todo List</title></head><body> <form method=\"post\" id=\"task-form\"> {% csrf_token %} <input type=\"text\" placeholder=\"Enter Task\" name=\"task\" id=\"task\" required> <button type=\"submit\">Save</button> </form> <script src=\"https://code.jquery.com/jquery-3.5.1.js\" integrity=\"sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=\" crossorigin=\"anonymous\"></script> <script type=\"text/javascript\"> $(document).on('submit','#task-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url \"home\" %}', data: { task:$(\"#task\").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert('Saved'); } }) }); </script> </body></html>", "e": 26621, "s": 25682, "text": null }, { "code": null, "e": 26686, "s": 26621, "text": "Create new view inside views.py to handle get and post request." }, { "code": null, "e": 26694, "s": 26686, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom .models import Todo# Create your views here.def home(request): if request.method == 'POST': task=request.POST.get('task') print(task) new = Todo(task=task) new.save() return render(request,\"main/form.html\")", "e": 26975, "s": 26694, "text": null }, { "code": null, "e": 27030, "s": 26975, "text": "Create new file inside your app and name it as urls.py" }, { "code": null, "e": 27038, "s": 27030, "text": "Python3" }, { "code": "from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name=\"home\"),]", "e": 27135, "s": 27038, "text": null }, { "code": null, "e": 27165, "s": 27135, "text": "Add main.urls in project urls" }, { "code": null, "e": 27180, "s": 27165, "text": "myproj/urls.py" }, { "code": null, "e": 27188, "s": 27180, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include(\"main.urls\"))]", "e": 27344, "s": 27188, "text": null }, { "code": null, "e": 27373, "s": 27344, "text": "To run the app write command" }, { "code": null, "e": 27400, "s": 27373, "text": "python manage.py runserver" }, { "code": null, "e": 27407, "s": 27400, "text": "Output" }, { "code": null, "e": 27418, "s": 27407, "text": "Admin Page" }, { "code": null, "e": 27432, "s": 27418, "text": "Python Django" }, { "code": null, "e": 27439, "s": 27432, "text": "Python" }, { "code": null, "e": 27537, "s": 27439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27569, "s": 27537, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27625, "s": 27569, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27667, "s": 27625, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27722, "s": 27667, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27764, "s": 27722, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27786, "s": 27764, "text": "Defaultdict in Python" }, { "code": null, "e": 27825, "s": 27786, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27856, "s": 27825, "text": "Python | os.path.join() method" }, { "code": null, "e": 27885, "s": 27856, "text": "Create a directory in Python" } ]
Boolean parseBoolean() method in Java with examples - GeeksforGeeks
01 Oct, 2018 The parseBoolean() method of Boolean Class is a built in static method of the class java.lang.Boolean which is used to convert a given string to its boolean value. Syntax: Boolean.parseBoolean(String value) Parameters: It takes one parameter value of type string which contains the value which is to be converted to boolean. Return Value: It returns a primitive boolean value. It returns the true if the given value is equals “true” ignoring cases. Else it returns false. Below are java code to illustrate parseBoolean() method: Example 1: class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = "TrUe"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }} true Example 2: class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = "true"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }} true Example 3: class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = "gfg"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }} false Java - util package Java-Functions 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 Internal Working of HashMap in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n01 Oct, 2018" }, { "code": null, "e": 25401, "s": 25237, "text": "The parseBoolean() method of Boolean Class is a built in static method of the class java.lang.Boolean which is used to convert a given string to its boolean value." }, { "code": null, "e": 25409, "s": 25401, "text": "Syntax:" }, { "code": null, "e": 25444, "s": 25409, "text": "Boolean.parseBoolean(String value)" }, { "code": null, "e": 25562, "s": 25444, "text": "Parameters: It takes one parameter value of type string which contains the value which is to be converted to boolean." }, { "code": null, "e": 25709, "s": 25562, "text": "Return Value: It returns a primitive boolean value. It returns the true if the given value is equals “true” ignoring cases. Else it returns false." }, { "code": null, "e": 25766, "s": 25709, "text": "Below are java code to illustrate parseBoolean() method:" }, { "code": null, "e": 25777, "s": 25766, "text": "Example 1:" }, { "code": "class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = \"TrUe\"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }}", "e": 26103, "s": 25777, "text": null }, { "code": null, "e": 26109, "s": 26103, "text": "true\n" }, { "code": null, "e": 26120, "s": 26109, "text": "Example 2:" }, { "code": "class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = \"true\"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }}", "e": 26446, "s": 26120, "text": null }, { "code": null, "e": 26452, "s": 26446, "text": "true\n" }, { "code": null, "e": 26463, "s": 26452, "text": "Example 3:" }, { "code": "class GeeksforGeeks { // Driver method public static void main(String[] args) { // string value String value = \"gfg\"; // parseBoolean using parse Boolean() method boolean result = Boolean.parseBoolean(value); // printing the result System.out.println(result); }}", "e": 26788, "s": 26463, "text": null }, { "code": null, "e": 26795, "s": 26788, "text": "false\n" }, { "code": null, "e": 26815, "s": 26795, "text": "Java - util package" }, { "code": null, "e": 26830, "s": 26815, "text": "Java-Functions" }, { "code": null, "e": 26835, "s": 26830, "text": "Java" }, { "code": null, "e": 26840, "s": 26835, "text": "Java" }, { "code": null, "e": 26938, "s": 26840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26953, "s": 26938, "text": "Stream In Java" }, { "code": null, "e": 26974, "s": 26953, "text": "Constructors in Java" }, { "code": null, "e": 26993, "s": 26974, "text": "Exceptions in Java" }, { "code": null, "e": 27023, "s": 26993, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27069, "s": 27023, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27086, "s": 27069, "text": "Generics in Java" }, { "code": null, "e": 27107, "s": 27086, "text": "Introduction to Java" }, { "code": null, "e": 27150, "s": 27107, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27172, "s": 27150, "text": "PriorityQueue in Java" } ]
How to Convert Title to URL Slug using JavaScript ? - GeeksforGeeks
10 Oct, 2021 Given a title and the task is to convert title into URL slug using JavaScript. In this article, we will use HTML to design the basic structure of body, CSS is used to set the style of body and JavaScript is used to implement the logic structure. Prerequisite: HTML Basics JavaScript Basics Basically below program will convert a title into a URL Slug using JavaScript. Approach: Create an HTML form with input for title and output for URL slug with unique ids. Add some CSS style to the element. Below is the basic HTML code implementation: HTML <!DOCTYPE html><html> <head> <style> fieldset.slugify { color: #515151; border: 1px solid #ccc; padding: 15px; } .slugify legend { font-size: 16px; font-weight: 600; padding: 0 10px; } .slugify input { display: block; padding: 8px; margin: 8px; } .slug-output { color: #05ab13; font-size: 20px; font-weight: 500; } </style></head> <body> <form> <fieldset class="slugify"> <legend>GeeksforGeeks</legend> <label for="slug-source">Input Title: </label> <input type="text" value="" id="slug-source" /> <label for="slug-target">URL Slug: </label> <input type="text" value="" id="slug-target" /> <button type="button" onClick="myFunction()"> Convert </button> <p> <span class="slug-ouput"> Generated URL Slug </span>: <span id="slug-target-span"></span> </p> </fieldset> </form></body> </html> Here, we have used the replace() function in JavaScript to make a string slug. The created slug string can be further used in URLs. Below is the JavaScript Code implementation: Javascript <script> function myFunction() { var a = document.getElementById("slug-source").value; var b = a.toLowerCase().replace(/ /g, '-') .replace(/[^\w-]+/g, ''); document.getElementById("slug-target").value = b; document.getElementById("slug-target-span").innerHTML = b; }</script> Example: In this example, we will combine the above two sections of code (HTML and JavaScript code) to convert title into URL slug. HTML <!DOCTYPE html><html> <head> <style> fieldset.slugify { color: #515151; border: 1px solid #ccc; padding: 15px; } .slugify legend { font-size: 16px; font-weight: 600; padding: 0 10px; } .slugify input { display: block; padding: 8px; margin: 8px; } .slug-output { color: #05ab13; font-size: 20px; font-weight: 500; } </style></head> <body> <form> <fieldset class="slugify"> <legend>GeeksforGeeks</legend> <label for="slug-source">Input Title: </label> <input type="text" value="" id="slug-source" /> <label for="slug-target">URL Slug: </label> <input type="text" value="" id="slug-target" /> <button type="button" onClick="myFunction()"> Convert </button> <p> <span class="slug-ouput">Generated URL Slug</span>: <span id="slug-target-span"></span> </p> </fieldset> </form> <script type="text/javascript"> function myFunction() { var a = document.getElementById("slug-source").value; var b = a.toLowerCase().replace(/ /g, '-') .replace(/[^\w-]+/g, ''); document.getElementById("slug-target").value = b; document.getElementById("slug-target-span").innerHTML = b; } </script></body> </html> Output: adnanirshad158 CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to set space between the flexbox ? HTML Cheat Sheet - A Basic Guide to HTML How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24254, "s": 24226, "text": "\n10 Oct, 2021" }, { "code": null, "e": 24501, "s": 24254, "text": "Given a title and the task is to convert title into URL slug using JavaScript. In this article, we will use HTML to design the basic structure of body, CSS is used to set the style of body and JavaScript is used to implement the logic structure. " }, { "code": null, "e": 24515, "s": 24501, "text": "Prerequisite:" }, { "code": null, "e": 24529, "s": 24517, "text": "HTML Basics" }, { "code": null, "e": 24547, "s": 24529, "text": "JavaScript Basics" }, { "code": null, "e": 24628, "s": 24549, "text": "Basically below program will convert a title into a URL Slug using JavaScript." }, { "code": null, "e": 24640, "s": 24630, "text": "Approach:" }, { "code": null, "e": 24724, "s": 24642, "text": "Create an HTML form with input for title and output for URL slug with unique ids." }, { "code": null, "e": 24759, "s": 24724, "text": "Add some CSS style to the element." }, { "code": null, "e": 24805, "s": 24759, "text": "Below is the basic HTML code implementation: " }, { "code": null, "e": 24810, "s": 24805, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> fieldset.slugify { color: #515151; border: 1px solid #ccc; padding: 15px; } .slugify legend { font-size: 16px; font-weight: 600; padding: 0 10px; } .slugify input { display: block; padding: 8px; margin: 8px; } .slug-output { color: #05ab13; font-size: 20px; font-weight: 500; } </style></head> <body> <form> <fieldset class=\"slugify\"> <legend>GeeksforGeeks</legend> <label for=\"slug-source\">Input Title: </label> <input type=\"text\" value=\"\" id=\"slug-source\" /> <label for=\"slug-target\">URL Slug: </label> <input type=\"text\" value=\"\" id=\"slug-target\" /> <button type=\"button\" onClick=\"myFunction()\"> Convert </button> <p> <span class=\"slug-ouput\"> Generated URL Slug </span>: <span id=\"slug-target-span\"></span> </p> </fieldset> </form></body> </html>", "e": 26000, "s": 24810, "text": null }, { "code": null, "e": 26079, "s": 26000, "text": "Here, we have used the replace() function in JavaScript to make a string slug." }, { "code": null, "e": 26132, "s": 26079, "text": "The created slug string can be further used in URLs." }, { "code": null, "e": 26178, "s": 26132, "text": "Below is the JavaScript Code implementation: " }, { "code": null, "e": 26189, "s": 26178, "text": "Javascript" }, { "code": "<script> function myFunction() { var a = document.getElementById(\"slug-source\").value; var b = a.toLowerCase().replace(/ /g, '-') .replace(/[^\\w-]+/g, ''); document.getElementById(\"slug-target\").value = b; document.getElementById(\"slug-target-span\").innerHTML = b; }</script>", "e": 26514, "s": 26189, "text": null }, { "code": null, "e": 26646, "s": 26514, "text": "Example: In this example, we will combine the above two sections of code (HTML and JavaScript code) to convert title into URL slug." }, { "code": null, "e": 26651, "s": 26646, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> fieldset.slugify { color: #515151; border: 1px solid #ccc; padding: 15px; } .slugify legend { font-size: 16px; font-weight: 600; padding: 0 10px; } .slugify input { display: block; padding: 8px; margin: 8px; } .slug-output { color: #05ab13; font-size: 20px; font-weight: 500; } </style></head> <body> <form> <fieldset class=\"slugify\"> <legend>GeeksforGeeks</legend> <label for=\"slug-source\">Input Title: </label> <input type=\"text\" value=\"\" id=\"slug-source\" /> <label for=\"slug-target\">URL Slug: </label> <input type=\"text\" value=\"\" id=\"slug-target\" /> <button type=\"button\" onClick=\"myFunction()\"> Convert </button> <p> <span class=\"slug-ouput\">Generated URL Slug</span>: <span id=\"slug-target-span\"></span> </p> </fieldset> </form> <script type=\"text/javascript\"> function myFunction() { var a = document.getElementById(\"slug-source\").value; var b = a.toLowerCase().replace(/ /g, '-') .replace(/[^\\w-]+/g, ''); document.getElementById(\"slug-target\").value = b; document.getElementById(\"slug-target-span\").innerHTML = b; } </script></body> </html>", "e": 28190, "s": 26651, "text": null }, { "code": null, "e": 28198, "s": 28190, "text": "Output:" }, { "code": null, "e": 28213, "s": 28198, "text": "adnanirshad158" }, { "code": null, "e": 28222, "s": 28213, "text": "CSS-Misc" }, { "code": null, "e": 28232, "s": 28222, "text": "HTML-Misc" }, { "code": null, "e": 28248, "s": 28232, "text": "JavaScript-Misc" }, { "code": null, "e": 28252, "s": 28248, "text": "CSS" }, { "code": null, "e": 28257, "s": 28252, "text": "HTML" }, { "code": null, "e": 28268, "s": 28257, "text": "JavaScript" }, { "code": null, "e": 28285, "s": 28268, "text": "Web Technologies" }, { "code": null, "e": 28312, "s": 28285, "text": "Web technologies Questions" }, { "code": null, "e": 28317, "s": 28312, "text": "HTML" }, { "code": null, "e": 28415, "s": 28317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28463, "s": 28415, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28500, "s": 28463, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28564, "s": 28500, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28601, "s": 28564, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28640, "s": 28601, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28681, "s": 28640, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28741, "s": 28681, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28789, "s": 28741, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28842, "s": 28789, "text": "Hide or show elements in HTML using display property" } ]
Minimum operations required to set all elements of binary matrix - GeeksforGeeks
22 Apr, 2021 Given a binary matrix of N rows and M columns. The operation allowed on the matrix is to choose any index (x, y) and toggle all the elements between the rectangle having top-left as (0, 0) and bottom-right as (x-1, y-1). Toggling the element means changing 1 to 0 and 0 to 1. The task is to find minimum operations required to make set all the elements of the matrix i.e make all elements as 1.Examples: Input : mat[][] = 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 Output : 1 In one move, choose (3, 3) to make the whole matrix consisting of only 1s. Input : mat[][] = 0 0 1 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 Output : 3 The idea is to start from the end point (N – 1, M – 1) and traverse the matrix in reverse order. Whenever we encounter a cell which has a value of 0, flip it. Why traversing from end point ? Suppose there are 0 at (x, y) and (x + 1, y + 1) cell. You shouldn’t flip a cell (x + 1, y + 1) after cell (x, y) because after you flipped (x, y) to 1, in next move to flip (x + 1, y + 1) cell, you will flip again (x, y) to 0. So there is no benefit from the first move for flipping (x, y) cell.Below is implementation of this approach: C++ Java Python 3 C# PHP Javascript // C++ program to find minimum operations required// to set all the element of binary matrix#include <bits/stdc++.h>#define N 5#define M 5using namespace std; // Return minimum operation required to make all 1s.int minOperation(bool arr[N][M]){ int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if(arr[i][j] == 0) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == 1) arr[k][h] = 0; else arr[k][h] = 1; } } } } } return ans;} // Driven Programint main(){ bool mat[N][M] = { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; cout << minOperation(mat) << endl; return 0;} // Java program to find minimum operations required// to set all the element of binary matrix class GFG { static final int N = 5; static final int M = 5; // Return minimum operation required to make all 1s. static int minOperation(boolean arr[][]) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program public static void main(String[] args) { boolean mat[][] = { {false, false, true, true, true}, {false, false, false, true, true}, {false, false, false, true, true}, {true, true, true, true, true}, {true, true, true, true, true} }; System.out.println(minOperation(mat)); }} // This code is contributed// by PrinciRaj1992 # Python 3 program to find# minimum operations required# to set all the element of# binary matrix # Return minimum operation# required to make all 1s.def minOperation(arr): ans = 0 for i in range(N - 1, -1, -1): for j in range(M - 1, -1, -1): # check if this # cell equals 0 if(arr[i][j] == 0): # increase the # number of moves ans += 1 # flip from this cell # to the start point for k in range(i + 1): for h in range(j + 1): # flip the cell if (arr[k][h] == 1): arr[k][h] = 0 else: arr[k][h] = 1 return ans # Driver Codemat = [[ 0, 0, 1, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]M = 5N = 5 print(minOperation(mat)) # This code is contributed# by ChitraNayal using System; // C# program to find minimum operations required // to set all the element of binary matrix public class GFG{ public const int N = 5; public const int M = 5; // Return minimum operation required to make all 1s. public static int minOperation(bool[][] arr) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program public static void Main(string[] args) { bool[][] mat = new bool[][] { new bool[] {false, false, true, true, true}, new bool[] {false, false, false, true, true}, new bool[] {false, false, false, true, true}, new bool[] {true, true, true, true, true}, new bool[] {true, true, true, true, true} }; Console.WriteLine(minOperation(mat)); }} // This code is contributed by Shrikant13 <?php// PHP program to find minimum// operations required to set// all the element of binary matrix $N = 5;$M = 5; // Return minimum operation// required to make all 1s.function minOperation(&$arr){ global $N, $M; $ans = 0; for ($i = $N - 1; $i >= 0; $i--) { for ($j = $M - 1; $j >= 0; $j--) { // check if this // cell equals 0 if($arr[$i][$j] == 0) { // increase the // number of moves $ans++; // flip from this cell // to the start point for ($k = 0; $k <= $i; $k++) { for ($h = 0; $h <= $j; $h++) { // flip the cell if ($arr[$k][$h] == 1) $arr[$k][$h] = 0; else $arr[$k][$h] = 1; } } } } } return $ans;} // Driver Code$mat = array(array(0, 0, 1, 1, 1), array(0, 0, 0, 1, 1), array(0, 0, 0, 1, 1), array(1, 1, 1, 1, 1), array(1, 1, 1, 1, 1)); echo minOperation($mat); // This code is contributed// by ChitraNayal?> <script>// Javascript program to find minimum operations required// to set all the element of binary matrix let N = 5; let M = 5; // Return minimum operation required to make all 1s. function minOperation(arr) { let ans = 0; for (let i = N - 1; i >= 0; i--) { for (let j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (let k = 0; k <= i; k++) { for (let h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program let mat = [[ 0, 0, 1, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] document.write(minOperation(mat)) // This code is contributed by avanitrachhadiya2155</script> Output: 3 Time Complexity: O(N2 * M2). Space Complexity: O(N*M).This article is contributed by Anuj Chauhan. 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. ukasp princiraj1992 shrikanth13 avanitrachhadiya2155 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Efficiently compute sums of diagonals of a matrix Program to multiply two matrices Count all possible paths from top left to bottom right of a mXn matrix Printing all solutions in N-Queen Problem Min Cost Path | DP-6 The Celebrity Problem Python program to multiply two matrices Search in a row wise and column wise sorted matrix Flood fill Algorithm - how to implement fill() in paint?
[ { "code": null, "e": 25086, "s": 25058, "text": "\n22 Apr, 2021" }, { "code": null, "e": 25492, "s": 25086, "text": "Given a binary matrix of N rows and M columns. The operation allowed on the matrix is to choose any index (x, y) and toggle all the elements between the rectangle having top-left as (0, 0) and bottom-right as (x-1, y-1). Toggling the element means changing 1 to 0 and 0 to 1. The task is to find minimum operations required to make set all the elements of the matrix i.e make all elements as 1.Examples: " }, { "code": null, "e": 25880, "s": 25492, "text": "Input : mat[][] = 0 0 0 1 1\n 0 0 0 1 1\n 0 0 0 1 1\n 1 1 1 1 1\n 1 1 1 1 1\nOutput : 1\nIn one move, choose (3, 3) to make the\nwhole matrix consisting of only 1s.\n\nInput : mat[][] = 0 0 1 1 1\n 0 0 0 1 1\n 0 0 0 1 1\n 1 1 1 1 1\n 1 1 1 1 1\nOutput : 3" }, { "code": null, "e": 26413, "s": 25882, "text": "The idea is to start from the end point (N – 1, M – 1) and traverse the matrix in reverse order. Whenever we encounter a cell which has a value of 0, flip it. Why traversing from end point ? Suppose there are 0 at (x, y) and (x + 1, y + 1) cell. You shouldn’t flip a cell (x + 1, y + 1) after cell (x, y) because after you flipped (x, y) to 1, in next move to flip (x + 1, y + 1) cell, you will flip again (x, y) to 0. So there is no benefit from the first move for flipping (x, y) cell.Below is implementation of this approach: " }, { "code": null, "e": 26417, "s": 26413, "text": "C++" }, { "code": null, "e": 26422, "s": 26417, "text": "Java" }, { "code": null, "e": 26431, "s": 26422, "text": "Python 3" }, { "code": null, "e": 26434, "s": 26431, "text": "C#" }, { "code": null, "e": 26438, "s": 26434, "text": "PHP" }, { "code": null, "e": 26449, "s": 26438, "text": "Javascript" }, { "code": "// C++ program to find minimum operations required// to set all the element of binary matrix#include <bits/stdc++.h>#define N 5#define M 5using namespace std; // Return minimum operation required to make all 1s.int minOperation(bool arr[N][M]){ int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if(arr[i][j] == 0) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == 1) arr[k][h] = 0; else arr[k][h] = 1; } } } } } return ans;} // Driven Programint main(){ bool mat[N][M] = { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; cout << minOperation(mat) << endl; return 0;}", "e": 27641, "s": 26449, "text": null }, { "code": "// Java program to find minimum operations required// to set all the element of binary matrix class GFG { static final int N = 5; static final int M = 5; // Return minimum operation required to make all 1s. static int minOperation(boolean arr[][]) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program public static void main(String[] args) { boolean mat[][] = { {false, false, true, true, true}, {false, false, false, true, true}, {false, false, false, true, true}, {true, true, true, true, true}, {true, true, true, true, true} }; System.out.println(minOperation(mat)); }} // This code is contributed// by PrinciRaj1992", "e": 29298, "s": 27641, "text": null }, { "code": "# Python 3 program to find# minimum operations required# to set all the element of# binary matrix # Return minimum operation# required to make all 1s.def minOperation(arr): ans = 0 for i in range(N - 1, -1, -1): for j in range(M - 1, -1, -1): # check if this # cell equals 0 if(arr[i][j] == 0): # increase the # number of moves ans += 1 # flip from this cell # to the start point for k in range(i + 1): for h in range(j + 1): # flip the cell if (arr[k][h] == 1): arr[k][h] = 0 else: arr[k][h] = 1 return ans # Driver Codemat = [[ 0, 0, 1, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]M = 5N = 5 print(minOperation(mat)) # This code is contributed# by ChitraNayal", "e": 30356, "s": 29298, "text": null }, { "code": "using System; // C# program to find minimum operations required // to set all the element of binary matrix public class GFG{ public const int N = 5; public const int M = 5; // Return minimum operation required to make all 1s. public static int minOperation(bool[][] arr) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program public static void Main(string[] args) { bool[][] mat = new bool[][] { new bool[] {false, false, true, true, true}, new bool[] {false, false, false, true, true}, new bool[] {false, false, false, true, true}, new bool[] {true, true, true, true, true}, new bool[] {true, true, true, true, true} }; Console.WriteLine(minOperation(mat)); }} // This code is contributed by Shrikant13", "e": 32103, "s": 30356, "text": null }, { "code": "<?php// PHP program to find minimum// operations required to set// all the element of binary matrix $N = 5;$M = 5; // Return minimum operation// required to make all 1s.function minOperation(&$arr){ global $N, $M; $ans = 0; for ($i = $N - 1; $i >= 0; $i--) { for ($j = $M - 1; $j >= 0; $j--) { // check if this // cell equals 0 if($arr[$i][$j] == 0) { // increase the // number of moves $ans++; // flip from this cell // to the start point for ($k = 0; $k <= $i; $k++) { for ($h = 0; $h <= $j; $h++) { // flip the cell if ($arr[$k][$h] == 1) $arr[$k][$h] = 0; else $arr[$k][$h] = 1; } } } } } return $ans;} // Driver Code$mat = array(array(0, 0, 1, 1, 1), array(0, 0, 0, 1, 1), array(0, 0, 0, 1, 1), array(1, 1, 1, 1, 1), array(1, 1, 1, 1, 1)); echo minOperation($mat); // This code is contributed// by ChitraNayal?>", "e": 33427, "s": 32103, "text": null }, { "code": "<script>// Javascript program to find minimum operations required// to set all the element of binary matrix let N = 5; let M = 5; // Return minimum operation required to make all 1s. function minOperation(arr) { let ans = 0; for (let i = N - 1; i >= 0; i--) { for (let j = M - 1; j >= 0; j--) { // check if this cell equals 0 if (arr[i][j] == false) { // increase the number of moves ans++; // flip from this cell to the start point for (let k = 0; k <= i; k++) { for (let h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == true) { arr[k][h] = false; } else { arr[k][h] = true; } } } } } } return ans; } // Driven Program let mat = [[ 0, 0, 1, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] document.write(minOperation(mat)) // This code is contributed by avanitrachhadiya2155</script>", "e": 34826, "s": 33427, "text": null }, { "code": null, "e": 34836, "s": 34826, "text": "Output: " }, { "code": null, "e": 34838, "s": 34836, "text": "3" }, { "code": null, "e": 35317, "s": 34838, "text": "Time Complexity: O(N2 * M2). Space Complexity: O(N*M).This article is contributed by Anuj Chauhan. 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. " }, { "code": null, "e": 35323, "s": 35317, "text": "ukasp" }, { "code": null, "e": 35337, "s": 35323, "text": "princiraj1992" }, { "code": null, "e": 35349, "s": 35337, "text": "shrikanth13" }, { "code": null, "e": 35370, "s": 35349, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35377, "s": 35370, "text": "Matrix" }, { "code": null, "e": 35384, "s": 35377, "text": "Matrix" }, { "code": null, "e": 35482, "s": 35384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35544, "s": 35482, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 35594, "s": 35544, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 35627, "s": 35594, "text": "Program to multiply two matrices" }, { "code": null, "e": 35698, "s": 35627, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 35740, "s": 35698, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 35761, "s": 35740, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35783, "s": 35761, "text": "The Celebrity Problem" }, { "code": null, "e": 35823, "s": 35783, "text": "Python program to multiply two matrices" }, { "code": null, "e": 35874, "s": 35823, "text": "Search in a row wise and column wise sorted matrix" } ]
C# | Searching the index of specified object in Collection<T> - GeeksforGeeks
01 Feb, 2019 Collection<T>.IndexOf(T) method is used to search for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>. Syntax: public int IndexOf (T item); Here, item is the object to locate in the List<T>. The value can be null for reference types. Return Value: This method returns the zero-based index of the first occurrence of item within the entire Collection<T>, if found, otherwise, -1. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to search for the specified// object and returns the zero-based// index of the first occurrence within// the entire Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("D"); myColl.Add("E"); // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } // Searching for the specified object // and returns the zero-based index of // the first occurrence within the entire // Collection. If the object doesn't contain the // object, then -1 is returned Console.WriteLine("Index : " + myColl.IndexOf("D")); }} Output: A B C D D E Index : 3 Example 2: // C# code to search for the specified// object and returns the zero-based// index of the first occurrence within// the entire Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } // Searching for the specified object // and returns the zero-based index of // the first occurrence within the entire // Collection. If the object doesn't contain the // object, then -1 is returned Console.WriteLine("Index : " + myColl.IndexOf(7)); }} Output: 2 3 4 5 Index : -1 Note: The Collection<T> is searched forward starting at the first element and ending at the last element. This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list. This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.indexof?view=netframework-4.7.2 CSharp-Collection-Class CSharp-Collections.ObjectModel-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Lambda Expressions in C# Convert String to Character Array in C# C# | How to insert an element in an Array?
[ { "code": null, "e": 25657, "s": 25629, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25822, "s": 25657, "text": "Collection<T>.IndexOf(T) method is used to search for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>." }, { "code": null, "e": 25830, "s": 25822, "text": "Syntax:" }, { "code": null, "e": 25860, "s": 25830, "text": "public int IndexOf (T item);\n" }, { "code": null, "e": 25954, "s": 25860, "text": "Here, item is the object to locate in the List<T>. The value can be null for reference types." }, { "code": null, "e": 26099, "s": 25954, "text": "Return Value: This method returns the zero-based index of the first occurrence of item within the entire Collection<T>, if found, otherwise, -1." }, { "code": null, "e": 26179, "s": 26099, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 26190, "s": 26179, "text": "Example 1:" }, { "code": "// C# code to search for the specified// object and returns the zero-based// index of the first occurrence within// the entire Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Displaying the elements in myColl foreach(string str in myColl) { Console.WriteLine(str); } // Searching for the specified object // and returns the zero-based index of // the first occurrence within the entire // Collection. If the object doesn't contain the // object, then -1 is returned Console.WriteLine(\"Index : \" + myColl.IndexOf(\"D\")); }}", "e": 27213, "s": 26190, "text": null }, { "code": null, "e": 27221, "s": 27213, "text": "Output:" }, { "code": null, "e": 27244, "s": 27221, "text": "A\nB\nC\nD\nD\nE\nIndex : 3\n" }, { "code": null, "e": 27255, "s": 27244, "text": "Example 2:" }, { "code": "// C# code to search for the specified// object and returns the zero-based// index of the first occurrence within// the entire Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } // Searching for the specified object // and returns the zero-based index of // the first occurrence within the entire // Collection. If the object doesn't contain the // object, then -1 is returned Console.WriteLine(\"Index : \" + myColl.IndexOf(7)); }}", "e": 28204, "s": 27255, "text": null }, { "code": null, "e": 28212, "s": 28204, "text": "Output:" }, { "code": null, "e": 28232, "s": 28212, "text": "2\n3\n4\n5\nIndex : -1\n" }, { "code": null, "e": 28238, "s": 28232, "text": "Note:" }, { "code": null, "e": 28338, "s": 28238, "text": "The Collection<T> is searched forward starting at the first element and ending at the last element." }, { "code": null, "e": 28473, "s": 28338, "text": "This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list." }, { "code": null, "e": 28574, "s": 28473, "text": "This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 28585, "s": 28574, "text": "Reference:" }, { "code": null, "e": 28705, "s": 28585, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.indexof?view=netframework-4.7.2" }, { "code": null, "e": 28729, "s": 28705, "text": "CSharp-Collection-Class" }, { "code": null, "e": 28770, "s": 28729, "text": "CSharp-Collections.ObjectModel-Namespace" }, { "code": null, "e": 28784, "s": 28770, "text": "CSharp-method" }, { "code": null, "e": 28787, "s": 28784, "text": "C#" }, { "code": null, "e": 28885, "s": 28787, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28908, "s": 28885, "text": "Extension Method in C#" }, { "code": null, "e": 28936, "s": 28908, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28953, "s": 28936, "text": "C# | Inheritance" }, { "code": null, "e": 28975, "s": 28953, "text": "Partial Classes in C#" }, { "code": null, "e": 29004, "s": 28975, "text": "C# | Generics - Introduction" }, { "code": null, "e": 29044, "s": 29004, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29067, "s": 29044, "text": "Switch Statement in C#" }, { "code": null, "e": 29092, "s": 29067, "text": "Lambda Expressions in C#" }, { "code": null, "e": 29132, "s": 29092, "text": "Convert String to Character Array in C#" } ]
p5.js | draw() Function - GeeksforGeeks
23 Aug, 2019 The draw() function is called after setup() function. The draw() function is used to executes the code inside the block until the program is stopped or noLoop() is called. If the program does not contain noLoop() function within setup() function then draw() function will still be executed once before stopping it. It should always be controlled with noLoop(), redraw() and loop() functions. Syntax: draw() Below examples illustrate the draw() function in p5.js: Example 1: function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a rectangle rect(50, 50, 300, 200); } Output: Example 2: function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv = createDiv('GeeksforGeeks'); var myDiv1 = createDiv('A computer science portal for geeks'); // Use child() function myDiv.child(myDiv1); // Set the position of div element myDiv.position(150, 100); myDiv.style('text-align', 'center'); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font color myDiv.style('color', 'white'); } Output: JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer 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?
[ { "code": null, "e": 43612, "s": 43584, "text": "\n23 Aug, 2019" }, { "code": null, "e": 44004, "s": 43612, "text": "The draw() function is called after setup() function. The draw() function is used to executes the code inside the block until the program is stopped or noLoop() is called. If the program does not contain noLoop() function within setup() function then draw() function will still be executed once before stopping it. It should always be controlled with noLoop(), redraw() and loop() functions." }, { "code": null, "e": 44012, "s": 44004, "text": "Syntax:" }, { "code": null, "e": 44019, "s": 44012, "text": "draw()" }, { "code": null, "e": 44075, "s": 44019, "text": "Below examples illustrate the draw() function in p5.js:" }, { "code": null, "e": 44086, "s": 44075, "text": "Example 1:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a rectangle rect(50, 50, 300, 200); } ", "e": 44408, "s": 44086, "text": null }, { "code": null, "e": 44416, "s": 44408, "text": "Output:" }, { "code": null, "e": 44427, "s": 44416, "text": "Example 2:" }, { "code": "function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv = createDiv('GeeksforGeeks'); var myDiv1 = createDiv('A computer science portal for geeks'); // Use child() function myDiv.child(myDiv1); // Set the position of div element myDiv.position(150, 100); myDiv.style('text-align', 'center'); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font color myDiv.style('color', 'white'); }", "e": 45094, "s": 44427, "text": null }, { "code": null, "e": 45102, "s": 45094, "text": "Output:" }, { "code": null, "e": 45119, "s": 45102, "text": "JavaScript-p5.js" }, { "code": null, "e": 45130, "s": 45119, "text": "JavaScript" }, { "code": null, "e": 45147, "s": 45130, "text": "Web Technologies" }, { "code": null, "e": 45245, "s": 45147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45254, "s": 45245, "text": "Comments" }, { "code": null, "e": 45267, "s": 45254, "text": "Old Comments" }, { "code": null, "e": 45312, "s": 45267, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45381, "s": 45312, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 45442, "s": 45381, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45514, "s": 45442, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45541, "s": 45514, "text": "File uploading in React.js" }, { "code": null, "e": 45583, "s": 45541, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 45616, "s": 45583, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45678, "s": 45616, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 45721, "s": 45678, "text": "How to fetch data from an API in ReactJS ?" } ]
Git Staging Environment
One of the core functions of Git is the concepts of the Staging Environment, and the Commit. As you are working, you may be adding, editing and removing files. But whenever you hit a milestone or finish a part of the work, you should add the files to a Staging Environment. Staged files are files that are ready to be committed to the repository you are working on. You will learn more about commit shortly. For now, we are done working with index.html. So we can add it to the Staging Environment: git add index.html The file should be Staged. Let's check the status:: git status On branch master No commits yet Changes to be committed: (use "git rm --cached ..." to unstage) new file: index.html Now the file has been added to the Staging Environment. You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again. A README.md file that describes the repository (recommended for all repositories): A basic external style sheet (bluestyle.css): And update index.html to include the stylesheet: Now add all files in the current directory to the Staging Environment: git add --all Using --all instead of individual filenames will stage all changes (new, modified, and deleted) files. git status On branch master No commits yet Changes to be committed: (use "git rm --cached ..." to unstage) new file: README.md new file: bluestyle.css new file: index.html Now all 3 files are added to the Staging Environment, and we are ready to do our first commit. Note: The shorthand command for git add --all is git add -A Add index.html to the Stating Environment: git index.html 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.
[ { "code": null, "e": 93, "s": 0, "text": "One of the core functions of Git is the concepts of the Staging Environment, and the Commit." }, { "code": null, "e": 276, "s": 93, "text": "As you are working, you may be adding, editing and removing files. But \nwhenever you hit a milestone or finish a part of the work, you should add the \nfiles to a Staging Environment." }, { "code": null, "e": 413, "s": 276, "text": "Staged files are files that are ready to be \ncommitted to the \nrepository you are working on. You will learn more about \ncommit shortly." }, { "code": null, "e": 505, "s": 413, "text": "For now, we are done working with index.html. \nSo we can add it to the Staging Environment:" }, { "code": null, "e": 524, "s": 505, "text": "git add index.html" }, { "code": null, "e": 576, "s": 524, "text": "The file should be Staged. Let's check the status::" }, { "code": null, "e": 712, "s": 576, "text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: index.html" }, { "code": null, "e": 768, "s": 712, "text": "Now the file has been added to the Staging Environment." }, { "code": null, "e": 890, "s": 768, "text": "You can also stage more than one file at a time. Let's add 2 more files to our working folder. Use the text editor again." }, { "code": null, "e": 974, "s": 890, "text": "A README.md file that describes the repository (recommended for all \nrepositories):" }, { "code": null, "e": 1020, "s": 974, "text": "A basic external style sheet (bluestyle.css):" }, { "code": null, "e": 1069, "s": 1020, "text": "And update index.html to include the stylesheet:" }, { "code": null, "e": 1140, "s": 1069, "text": "Now add all files in the current directory to the Staging Environment:" }, { "code": null, "e": 1154, "s": 1140, "text": "git add --all" }, { "code": null, "e": 1258, "s": 1154, "text": "Using --all instead of individual filenames \nwill stage all changes (new, modified, and deleted) files." }, { "code": null, "e": 1464, "s": 1258, "text": "git status\nOn branch master\n\nNo commits yet\n\nChanges to be committed:\n (use \"git rm --cached ...\" to unstage)\n new file: README.md\n new file: bluestyle.css\n new file: index.html" }, { "code": null, "e": 1560, "s": 1464, "text": "Now all 3 files are added to the Staging Environment, and we are ready to do \nour first commit." }, { "code": null, "e": 1623, "s": 1560, "text": "Note: The shorthand command for \n git add --all is git add -A" }, { "code": null, "e": 1666, "s": 1623, "text": "Add index.html to the Stating Environment:" }, { "code": null, "e": 1683, "s": 1666, "text": "git index.html\n" }, { "code": null, "e": 1703, "s": 1683, "text": "\nStart the Exercise" }, { "code": null, "e": 1736, "s": 1703, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1778, "s": 1736, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1885, "s": 1778, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1904, "s": 1885, "text": "help@w3schools.com" } ]
JavaFX example to set action to the "exit" MenuItem
A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items. You can create a menu item by instantiating the javafx.scene.control.MenuItem class. The Menu class inherits a property named onAction from the javafx.scene.control.ButtonBase class, which is of the type ObjectProperty<EventHandler<ActionEvent>>. This property represents the action that is invoked whenever you press the button. You can set the value to this property using the setOnAction() method. To set action on a menu you need to − Instantiate the Menu class. Instantiate the Menu class. Create a MenuItem objects and add them to the Menu. Create a MenuItem objects and add them to the Menu. Invoke the setOnAction() method the menu item object. Invoke the setOnAction() method the menu item object. To the setOnAction() method you need to pass an EventHandler<ActionEvent> object wrapping the code for the action to perform within it. For exit operation, since you need to close the application you can use System.exit(0). import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.stage.Stage; public class ExitMenuItemAction extends Application { @Override public void start(Stage stage) { //Creating image view files ImageView imgView1 = new ImageView("UIControls/open.png"); imgView1.setFitWidth(20); imgView1.setFitHeight(20); ImageView imgView2 = new ImageView("UIControls/Save.png"); imgView2.setFitWidth(20); imgView2.setFitHeight(20); ImageView imgView3 = new ImageView("UIControls/Exit.png"); imgView3.setFitWidth(20); imgView3.setFitHeight(20); //Creating menu Menu fileMenu = new Menu("File"); //Creating menu Items MenuItem item1 = new MenuItem("Open File", imgView1); MenuItem item2 = new MenuItem("Save file", imgView2); MenuItem item3 = new MenuItem("Exit", imgView3); //Adding all the menu items to the menu fileMenu.getItems().addAll(item1, item2, item3); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(200); menuBar.setTranslateY(20); //Setting action to exit menu item item3.setOnAction((ActionEvent t) -> { System.exit(0); }); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Menu Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1229, "s": 1062, "text": "A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items." }, { "code": null, "e": 1314, "s": 1229, "text": "You can create a menu item by instantiating the javafx.scene.control.MenuItem class." }, { "code": null, "e": 1630, "s": 1314, "text": "The Menu class inherits a property named onAction from the javafx.scene.control.ButtonBase class, which is of the type ObjectProperty<EventHandler<ActionEvent>>. This property represents the action that is invoked whenever you press the button. You can set the value to this property using the setOnAction() method." }, { "code": null, "e": 1668, "s": 1630, "text": "To set action on a menu you need to −" }, { "code": null, "e": 1696, "s": 1668, "text": "Instantiate the Menu class." }, { "code": null, "e": 1724, "s": 1696, "text": "Instantiate the Menu class." }, { "code": null, "e": 1776, "s": 1724, "text": "Create a MenuItem objects and add them to the Menu." }, { "code": null, "e": 1828, "s": 1776, "text": "Create a MenuItem objects and add them to the Menu." }, { "code": null, "e": 1882, "s": 1828, "text": "Invoke the setOnAction() method the menu item object." }, { "code": null, "e": 1936, "s": 1882, "text": "Invoke the setOnAction() method the menu item object." }, { "code": null, "e": 2160, "s": 1936, "text": "To the setOnAction() method you need to pass an EventHandler<ActionEvent> object wrapping the code for the action to perform within it. For exit operation, since you need to close the application you can use System.exit(0)." }, { "code": null, "e": 3958, "s": 2160, "text": "import javafx.application.Application;\nimport javafx.event.ActionEvent;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ExitMenuItemAction extends Application {\n @Override\n public void start(Stage stage) {\n //Creating image view files\n ImageView imgView1 = new ImageView(\"UIControls/open.png\");\n imgView1.setFitWidth(20);\n imgView1.setFitHeight(20);\n ImageView imgView2 = new ImageView(\"UIControls/Save.png\");\n imgView2.setFitWidth(20);\n imgView2.setFitHeight(20);\n ImageView imgView3 = new ImageView(\"UIControls/Exit.png\");\n imgView3.setFitWidth(20);\n imgView3.setFitHeight(20);\n //Creating menu\n Menu fileMenu = new Menu(\"File\");\n //Creating menu Items\n MenuItem item1 = new MenuItem(\"Open File\", imgView1);\n MenuItem item2 = new MenuItem(\"Save file\", imgView2);\n MenuItem item3 = new MenuItem(\"Exit\", imgView3);\n //Adding all the menu items to the menu\n fileMenu.getItems().addAll(item1, item2, item3);\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(fileMenu);\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Setting action to exit menu item\n item3.setOnAction((ActionEvent t) -> {\n System.exit(0);\n });\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Java String equals() Method
❮ String Methods Compare strings to find out if they are equal: String myStr1 = "Hello"; String myStr2 = "Hello"; String myStr3 = "Another String"; System.out.println(myStr1.equals(myStr2)); // Returns true because they are equal System.out.println(myStr1.equals(myStr3)); // false Try it Yourself » The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically. public boolean equals(Object anotherObject) true - if the strings are equal false - if the strings are not equal 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.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 66, "s": 19, "text": "Compare strings to find out if they are equal:" }, { "code": null, "e": 284, "s": 66, "text": "String myStr1 = \"Hello\";\nString myStr2 = \"Hello\";\nString myStr3 = \"Another String\";\nSystem.out.println(myStr1.equals(myStr2)); // Returns true because they are equal\nSystem.out.println(myStr1.equals(myStr3)); // false" }, { "code": null, "e": 304, "s": 284, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 408, "s": 304, "text": "The equals() method compares two strings, \nand returns true if the strings are equal, and false if not." }, { "code": null, "e": 482, "s": 408, "text": "Tip: Use the compareTo() method to compare two strings lexicographically." }, { "code": null, "e": 527, "s": 482, "text": "public boolean equals(Object anotherObject)\n" }, { "code": null, "e": 559, "s": 527, "text": "true - if the strings are equal" }, { "code": null, "e": 596, "s": 559, "text": "false - if the strings are not equal" }, { "code": null, "e": 629, "s": 596, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 671, "s": 629, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 778, "s": 671, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 797, "s": 778, "text": "help@w3schools.com" } ]
Random String Generator using JavaScript - GeeksforGeeks
23 Nov, 2021 JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. In this article, we need to create a Random String Generator using Javascript that will generate a random set of strings & get displayed when the user clicks a button. Additionally, we can also take input for the length of the string from the user. On the client-side, it will render those strings once generated using the Document Object Model (DOM) concept. Approach: For generating Random Strings in Javascript, we can use in-built methods that will actually generate the strings and can manipulate the Document Object Model (DOM) accordingly. We will use the Math library to access the random() function that will help to generate the random index and multiple with the length of the string ie., it will append the character from the string or character set as it is passed. We can generate the random string in 2 ways ie., either we can iterate the loop for the specified length of the character set or we can use String.fromCharCode() method that will convert the UTF-16 codes into their equivalent characters and returns the string. By using the 2nd approach, we can manually take input for the length of the string from the user then generate the string of that particular length by accessing the DOM elements. For both approaches, we will use the Math.random() function. Generating Random Strings: Here, we will generate strings only with lowercase letters characters. Let’s start by discussing the two different approaches for generating the strings. Approach 1: Generating the random string from the specified length of the character set: Declare the character set that will use for generating string. Access the length of that character set from the input. Construct the iteration loop for random character generation. Use Math functions in javascript & assign them to the variable. We will utilize the above concepts & generate the strings randomly of user-defined length using Javascript and DOM manipulation. Defining the character set: We have defined a variable “characters” that will contain all the characters as we require. We will use another variable “result” which is initialized as an empty string.Accessing the length of the string: After this, we will fetch the length of the string that we need to generate by using the document.getElementById method to access the HTML element or the user input field that contains the length. length = document.getElementById("strlength").value; So, we have used the “strlength” id which is declared inside the HTML <input> tag. We can get the value of the element using the “.value” attribute and then assign it to a “length” variable. Thus, we have now obtained the length of the string that is needed to generate. Generating Random characters: We will use a for loop to generate n(length) number of characters and append those to the string. The loop will run from 0 till length -1 as the index value start from 0. for ( let i = 0; i < length; i++ ) { // Code } Now, we will use the Math.random() function to generate a random index in the string. Before that, we need to get the length of the “characters” string and store it in a const variable “charactersLength”. This will give us the length of the “charactersLength” string which is 26. Now, using the charAt() function that will return the character at a specified index in a string & we can get the random number. The Math.random() function will give the value between 0 & 1 ie., decimal value & we need to round it off to get an integer value. Hence, we use Math.floor to round off the decimal value. We will multiply the Math.random() function with the variable charactersLength, to get the exact integer value. Thus, this will give us an integer between 0 and characterslength-1. Math.floor(Math.random() * charactersLength) The above syntax will give the integer between 0 and the length of the charactersLength-1 as the strings in Javascript are 0 based indexing. Hence, by using characters.charAt() method, we can get the character at that particular index. We finally add it to the empty string “result” and at the end of the loop, we get a string with random characters. Example: This example describes the random number generation for the specified length of the character. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>String Generator</title></head> <body> <h2>Random String Generator</h2> <h4 id="target"></h4> <input id="strlength" type="number" value="5" min="1" max="100" /> <button id="gen" onClick="generate()">Generate</button> <script> function generate() { let length = document.getElementById("strlength").value; const characters = 'abcdefghijklmnopqrstuvwxyz'; let result = ' '; const charactersLength = characters.length; for(let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } document.getElementById("target").innerHTML = result } </script></body> </html> Output: Approach 2: Generating the random string by using the String.fromCharCode() function: Fetch the length of the string to be generated from the input. Construct the iteration loop for the random character generation. Use String and Math functions to generate characters. We can use in-built functions like String.fromCharCode() function to generate a random Character. The step for declaring the character set & accessing its length will be similar to the first approach ie., we will create the length variable to get the length of the user input. After that, we create an empty string “result” for storing the generated string. We then run a for loop to iterate over the length of the string. for ( let i = 0; i < length; i++ ) { // Code } Now, we use the function String.fromCharCode to generate characters one by one using the for loop. The String.fromCharCode takes in the integer or UTF-16 code units and gives the equivalent string. Here, we are using the integer 97 i.e. the starting point of lowercase letters. You can refer to the UTF-16 table to get the value of the lower case letters. So, getting that lowercase ‘a’ is 97 in UTF-16, we can add 26 to the number to get the last letter ‘z’ as 122. So, we simply need to generate 26 random numbers and add them to 97. We can use the Math.random() function that returns a value between 0 and 1 and to get the integer value we need to floor() function to get the exact integer value & hence, we use the Math.floor(). But this will only get us 0 , every time we need to multiply the number Math.random() with 26 to get that desired result. 97 + Math.floor(Math.random() * 26) This will give the value between 97 and 122 i.e. ‘a’ to ‘z’. Thus, by enclosing them in the function String.fromCharCode() to get the actual string. Displaying the generated Strings: We have displayed the string using the innerHTML property and by accessing the HTML element using its id value. So, using the “document.getElementById” method to get the element h4 with the id “target” from the HTML code and then access the HTML value using “.innerHTML”. We assign that value to the string “result” which is the randomly generated string. This will display the string in the HTML template. document.getElementById("target").innerHTML = result; Example: This example describes the random number generation using the String.fromCharCode() function. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>String Generator</title></head> <body> <h2>Random String Generator</h2> <h4 id="target"></h4> <input id="strlength" type="number" value="5" min="1" max="100" /> <button id="gen" onClick="generate()">Generate</button> <script> function generate() { let length = document.getElementById("strlength").value; let result = ' '; for(let i = 0; i < length; i++) { result += String.fromCharCode(97 + Math.floor(Math.random() * 26)); } document.getElementById("target").innerHTML = result } </script></body> </html> Output: HTML-Questions JavaScript-Methods JavaScript-Questions Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 26165, "s": 26137, "text": "\n23 Nov, 2021" }, { "code": null, "e": 26425, "s": 26165, "text": "JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments." }, { "code": null, "e": 26785, "s": 26425, "text": "In this article, we need to create a Random String Generator using Javascript that will generate a random set of strings & get displayed when the user clicks a button. Additionally, we can also take input for the length of the string from the user. On the client-side, it will render those strings once generated using the Document Object Model (DOM) concept." }, { "code": null, "e": 27205, "s": 26785, "text": "Approach: For generating Random Strings in Javascript, we can use in-built methods that will actually generate the strings and can manipulate the Document Object Model (DOM) accordingly. We will use the Math library to access the random() function that will help to generate the random index and multiple with the length of the string ie., it will append the character from the string or character set as it is passed. " }, { "code": null, "e": 27706, "s": 27205, "text": "We can generate the random string in 2 ways ie., either we can iterate the loop for the specified length of the character set or we can use String.fromCharCode() method that will convert the UTF-16 codes into their equivalent characters and returns the string. By using the 2nd approach, we can manually take input for the length of the string from the user then generate the string of that particular length by accessing the DOM elements. For both approaches, we will use the Math.random() function." }, { "code": null, "e": 27887, "s": 27706, "text": "Generating Random Strings: Here, we will generate strings only with lowercase letters characters. Let’s start by discussing the two different approaches for generating the strings." }, { "code": null, "e": 27976, "s": 27887, "text": "Approach 1: Generating the random string from the specified length of the character set:" }, { "code": null, "e": 28039, "s": 27976, "text": "Declare the character set that will use for generating string." }, { "code": null, "e": 28095, "s": 28039, "text": "Access the length of that character set from the input." }, { "code": null, "e": 28157, "s": 28095, "text": "Construct the iteration loop for random character generation." }, { "code": null, "e": 28221, "s": 28157, "text": "Use Math functions in javascript & assign them to the variable." }, { "code": null, "e": 28350, "s": 28221, "text": "We will utilize the above concepts & generate the strings randomly of user-defined length using Javascript and DOM manipulation." }, { "code": null, "e": 28781, "s": 28350, "text": "Defining the character set: We have defined a variable “characters” that will contain all the characters as we require. We will use another variable “result” which is initialized as an empty string.Accessing the length of the string: After this, we will fetch the length of the string that we need to generate by using the document.getElementById method to access the HTML element or the user input field that contains the length." }, { "code": null, "e": 28834, "s": 28781, "text": "length = document.getElementById(\"strlength\").value;" }, { "code": null, "e": 29106, "s": 28834, "text": "So, we have used the “strlength” id which is declared inside the HTML <input> tag. We can get the value of the element using the “.value” attribute and then assign it to a “length” variable. Thus, we have now obtained the length of the string that is needed to generate." }, { "code": null, "e": 29307, "s": 29106, "text": "Generating Random characters: We will use a for loop to generate n(length) number of characters and append those to the string. The loop will run from 0 till length -1 as the index value start from 0." }, { "code": null, "e": 29362, "s": 29307, "text": "for ( let i = 0; i < length; i++ ) {\n // Code\n}" }, { "code": null, "e": 29771, "s": 29362, "text": "Now, we will use the Math.random() function to generate a random index in the string. Before that, we need to get the length of the “characters” string and store it in a const variable “charactersLength”. This will give us the length of the “charactersLength” string which is 26. Now, using the charAt() function that will return the character at a specified index in a string & we can get the random number." }, { "code": null, "e": 30141, "s": 29771, "text": "The Math.random() function will give the value between 0 & 1 ie., decimal value & we need to round it off to get an integer value. Hence, we use Math.floor to round off the decimal value. We will multiply the Math.random() function with the variable charactersLength, to get the exact integer value. Thus, this will give us an integer between 0 and characterslength-1. " }, { "code": null, "e": 30186, "s": 30141, "text": "Math.floor(Math.random() * charactersLength)" }, { "code": null, "e": 30327, "s": 30186, "text": "The above syntax will give the integer between 0 and the length of the charactersLength-1 as the strings in Javascript are 0 based indexing." }, { "code": null, "e": 30537, "s": 30327, "text": "Hence, by using characters.charAt() method, we can get the character at that particular index. We finally add it to the empty string “result” and at the end of the loop, we get a string with random characters." }, { "code": null, "e": 30641, "s": 30537, "text": "Example: This example describes the random number generation for the specified length of the character." }, { "code": null, "e": 30646, "s": 30641, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>String Generator</title></head> <body> <h2>Random String Generator</h2> <h4 id=\"target\"></h4> <input id=\"strlength\" type=\"number\" value=\"5\" min=\"1\" max=\"100\" /> <button id=\"gen\" onClick=\"generate()\">Generate</button> <script> function generate() { let length = document.getElementById(\"strlength\").value; const characters = 'abcdefghijklmnopqrstuvwxyz'; let result = ' '; const charactersLength = characters.length; for(let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } document.getElementById(\"target\").innerHTML = result } </script></body> </html>", "e": 31433, "s": 30646, "text": null }, { "code": null, "e": 31441, "s": 31433, "text": "Output:" }, { "code": null, "e": 31527, "s": 31441, "text": "Approach 2: Generating the random string by using the String.fromCharCode() function:" }, { "code": null, "e": 31590, "s": 31527, "text": "Fetch the length of the string to be generated from the input." }, { "code": null, "e": 31656, "s": 31590, "text": "Construct the iteration loop for the random character generation." }, { "code": null, "e": 31710, "s": 31656, "text": "Use String and Math functions to generate characters." }, { "code": null, "e": 32133, "s": 31710, "text": "We can use in-built functions like String.fromCharCode() function to generate a random Character. The step for declaring the character set & accessing its length will be similar to the first approach ie., we will create the length variable to get the length of the user input. After that, we create an empty string “result” for storing the generated string. We then run a for loop to iterate over the length of the string." }, { "code": null, "e": 32187, "s": 32133, "text": "for ( let i = 0; i < length; i++ ) {\n // Code\n}" }, { "code": null, "e": 32723, "s": 32187, "text": "Now, we use the function String.fromCharCode to generate characters one by one using the for loop. The String.fromCharCode takes in the integer or UTF-16 code units and gives the equivalent string. Here, we are using the integer 97 i.e. the starting point of lowercase letters. You can refer to the UTF-16 table to get the value of the lower case letters. So, getting that lowercase ‘a’ is 97 in UTF-16, we can add 26 to the number to get the last letter ‘z’ as 122. So, we simply need to generate 26 random numbers and add them to 97." }, { "code": null, "e": 33043, "s": 32723, "text": "We can use the Math.random() function that returns a value between 0 and 1 and to get the integer value we need to floor() function to get the exact integer value & hence, we use the Math.floor(). But this will only get us 0 , every time we need to multiply the number Math.random() with 26 to get that desired result. " }, { "code": null, "e": 33079, "s": 33043, "text": "97 + Math.floor(Math.random() * 26)" }, { "code": null, "e": 33228, "s": 33079, "text": "This will give the value between 97 and 122 i.e. ‘a’ to ‘z’. Thus, by enclosing them in the function String.fromCharCode() to get the actual string." }, { "code": null, "e": 33669, "s": 33228, "text": "Displaying the generated Strings: We have displayed the string using the innerHTML property and by accessing the HTML element using its id value. So, using the “document.getElementById” method to get the element h4 with the id “target” from the HTML code and then access the HTML value using “.innerHTML”. We assign that value to the string “result” which is the randomly generated string. This will display the string in the HTML template." }, { "code": null, "e": 33723, "s": 33669, "text": "document.getElementById(\"target\").innerHTML = result;" }, { "code": null, "e": 33826, "s": 33723, "text": "Example: This example describes the random number generation using the String.fromCharCode() function." }, { "code": null, "e": 33831, "s": 33826, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>String Generator</title></head> <body> <h2>Random String Generator</h2> <h4 id=\"target\"></h4> <input id=\"strlength\" type=\"number\" value=\"5\" min=\"1\" max=\"100\" /> <button id=\"gen\" onClick=\"generate()\">Generate</button> <script> function generate() { let length = document.getElementById(\"strlength\").value; let result = ' '; for(let i = 0; i < length; i++) { result += String.fromCharCode(97 + Math.floor(Math.random() * 26)); } document.getElementById(\"target\").innerHTML = result } </script></body> </html>", "e": 34504, "s": 33831, "text": null }, { "code": null, "e": 34512, "s": 34504, "text": "Output:" }, { "code": null, "e": 34527, "s": 34512, "text": "HTML-Questions" }, { "code": null, "e": 34546, "s": 34527, "text": "JavaScript-Methods" }, { "code": null, "e": 34567, "s": 34546, "text": "JavaScript-Questions" }, { "code": null, "e": 34574, "s": 34567, "text": "Picked" }, { "code": null, "e": 34579, "s": 34574, "text": "HTML" }, { "code": null, "e": 34590, "s": 34579, "text": "JavaScript" }, { "code": null, "e": 34607, "s": 34590, "text": "Web Technologies" }, { "code": null, "e": 34612, "s": 34607, "text": "HTML" }, { "code": null, "e": 34710, "s": 34612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34734, "s": 34710, "text": "REST API (Introduction)" }, { "code": null, "e": 34775, "s": 34734, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 34812, "s": 34775, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 34841, "s": 34812, "text": "Form validation using jQuery" }, { "code": null, "e": 34861, "s": 34841, "text": "Angular File Upload" }, { "code": null, "e": 34901, "s": 34861, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34946, "s": 34901, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35007, "s": 34946, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35076, "s": 35007, "text": "How to calculate the number of days between two dates in javascript?" } ]
A simple, but strong AI bot for Tron/Lightriders on a hexagonal grid | by Gilles Vandewiele | Towards Data Science
A new academic year, which means a new batch of bright students taking their first steps in their engineering career. As last year, three of my fellow course assistants (Elias, Pieter and Ozan) and I created a platform for an AI bot competition, to be hosted during the course of Informatics (in which they learn to program in Python), given by prof. Dhoedt at Ghent University. This year, we decided to host the game of Tron (sometimes called continuous snake or Lightriders), as shown below. Since both Riddles.io and CodinGame (which you should definitely check out if you are interested in AI bots!) host an AI competition for Tron as well, we decided to slightly adapt the game to be played on a hexagonal grid, instead of a square. This to avoid students just copy-pasting available solutions of those platforms. A screenshot of the game can be found below. As last year, I decided to compete in the competition myself, but did not find that much spare time. Hence, my solution wasn’t a very strong one. Nevertheless, I ended up pretty high on the leaderboard (5th spot), with a minimal code base and a simple heuristic, based on path finding. To discuss my solution, I will not need as much time/lines as last year, and therefore I decided to add some extra content. I split this blog post up in several sections: Game and competition rulesA detailed overview of my strong heuristic (with code)A write-up by some of the top competitorsAn overview of how the competition platform was made (separate post) Game and competition rules A detailed overview of my strong heuristic (with code) A write-up by some of the top competitors An overview of how the competition platform was made (separate post) The rules of the game are rather straight-forward. Both players start at a random position (mirrored around the center of the map) and with a random orientation (there are 6 orientations in total). Each player must then decide if they want to rotate their snake (120° or 60° CW/CCW or 0°), before making a move forward (as depicted in the figure below). Each snake leaves behind an impenetrable trail. The first snake that crashes into a wall or a trail of himself or opponent, loses the game. The submitted agents have to follow a predefined interface: def generate_move(board, positions, orientations): """Generate a move. Args: board (np.array): playing field positions (list): list of positions `(x, y)` orientations (list): list of orientations (int in [0,5]) Returns: move (int): integer in [-2,2] """ return 0 Moreover, each agent must comply to the following constraints: It contains no import statements, with the exception of: numpy, functools, itertools, collections, operator, heapq, math, random, time The file size must not be larger than 1 Megabyte The execution time of generate_move may not exceed 1 second After submitting your first agent to our platform, you will be matched up with another player every 30 minutes. After each match, rankings (TrueSkill or ELO) of both players are adjusted according to the match result, and these rankings are used for the leaderboard. For more information on the ranking systems, please refer to my next post. The competition lasted for about 1 month. We noticed that luck had a significant impact on your final rank (due to the matchmaking algorithm). To combat this, and to end up with an as objective ranking as possible, we took the top-competitors from the leaderboard after a certain amount of time (first-year students only). These competitors were chosen to compete in the “play-offs”, where each agent played all other agents four times. For each win, an agent was assigned three points, while a draw (of which there were many) resulted in both agents being awarded a single point. Before implementing more complex techniques, such as reinforcement learning, genetic algorithms and alpha-beta pruning, it is always good practice to first implement an agent based on a heuristic. These can be used to test the strengths of your opponents, but more importantly the strength of later versions of your agent. Unfortunately, I did not manage to implement more complex techniques this year due to a lack of time and only uploaded my baseline agent, based on a heuristic (which turned out to be very strong). I will now discuss my implementation thoroughly. The main reasoning behind my agent is rather simple: “always pick the move which results in a maximal difference between the number of tiles you can reach first, and the number of tiles your opponent can reach first.” Obviously, there will be many situations in which each possible move results in the same score (especially in the beginning of the game). We break ties by minimizing the number of remaining legal moves after making a certain move and by minimizing the distance towards the middle (if it still can be reached). The main game loop thus looks as follows: Now let’s break everything down, starting from (probably) the most simple part in the code: getting all legal moves (get_legal_moves). In this function, we iterate over each integer in the interval [-2, 2] which are the five possible moves. We map each integer to a tuple of offsets (get_steps) that correspond to our move and update our positions and orientations hypothetically (_update_pos_orient) according to these offsets. Then, we calculate whether we still reside in the hexagonal grid (_valid_position) and whether we did not crash into an already occupied cell (_no_crash): The code is rather straight-forward and probably does not need a lot of elaboration. To check whether we still reside in the hexagonal grid, we have to ensure that we do not get an IndexError by checking if our x and y coordinates do not go out of the bounds of our playing fields. Moreover, since the board representation is a square with some cells that are not reachable, we need to ensure that our agent does not move onto one of these cells. By inspecting the smaller (7x7) playing field depicted on the homepage we notice that the sum of x and y of the legal cells is bounded by 3 and 9. This generalizes to all playing field sizes and we can thus say that: with k the size of the playing field. Moreover, to check whether we are not moving on an already occupied cell, we can just take the sum along the final axis of our playing board (remember that the final axis of this board contains a bitmap for each player) and check whether the value at the coordinate we want to move to is equal to 0. Further, the order of the offsets in _get_steps is order specifically such that we can directly index them using our newly calculated orientation, which is equal to (orientation + action) % 6. Using this new orientation, we can get the corresponding offsets and add these to our current coordinates to calculate our new coordinate. Now that we have a list of all the moves that will not result in us immediately losing, we can calculate a score for each of these moves, based on a heuristic. The heuristic we used is based on distances to each possible tile in the game field. We want to maximize the number of tiles we can reach in less moves than our opponent while minimizing the number of tiles he or she can reach first. A nice GIF, taken from the winning solution’s write-up in the Google Tron AI Challenge is displayed below. To calculate the minimal distance from a certain coordinate to another cell, we can use the A* path-finding algorithm or Dijkstra. But since we need to calculate a distance to all cells in our grid, we use a slightly adapted version. We keep track of a list of cells that still need to be visited (and the distances to each of these cells), called a frontier. For each cell in our frontier, we expand in all possible directions and add these new cells to our frontier (with a distance equal to our old distance + 1) if they have not yet been explored or if we discovered a path with a smaller amount of moves. Once we have calculated the distances to all cells for both players, we can easily calculate the number of tiles both players can reach first: And that’s it! It’s that simple. In summary, we retrieve a list of all possible legal moves we can make, we then iterate over these legal moves and calculate a score for each of them. The score is based on the number of tiles we can reach first from the new position after making that move and the number of tiles our opponent can reach first. There are a few extra details, such as subtracting a penalty term from the score if we are too close to our opponent to avoid head-to-head crashes and the handling in case of ties (which are broken based on the number of legal moves remaining to fill up the board and based on the distance to the middle, since that is important in the start of the game). As mentioned, only a limited amount of time was spent this year on writing my agent. Therefore, many possible improvements are left open. The most important ones are listed here: An adaptation of the heuristic function could result in significant gains. According to the write-up of the Google Tron AI Challenge this resulted in the author winning the competition. In his blog post, a nice example game state is provided, where the heuristic function used for my agent would assign a negative score while we (again we are red) are actually on the winning hand: Instead of calculating a score for each possible move, we could calculate a score for each possible sequence of moves, thus looking ahead more than 1 move. To solve this, we usually apply techniques such as alpha-beta pruning, but a few extra considerations will need to made since both players move simultaneously. One simple hack is to first retrieve all legal moves for your opponent, before iterating over all your legal moves (changing the game state) and then recursively call your opponent, passing along those moves. This ensures that both players can calculate their legal moves, using the same game state during the recursion. Calculating the score for each possible move (or sequence of moves) using Monte Carlo simulations, instead of using a heuristic function. Here, we would simulate a large number of games starting from a certain game state where each agent would make a random, but legal, move. The fraction of games we win from these simulations could be a good indication of the strength of a certain game state. Of course, it should be noted that the maximum time to make a move is only one second. I have not tested how many simulations one could make within that second. Evolving neural networks to play the game for you, is a very generic strategy that requires no knowledge of the game itself. It would require quite a lot of work to write a framework for this (or configure an already existing one), but once it is written (or get the hang of the existing framework), it could easily be adapted for other games. I found a lot of examples for the single-player snake game (e.g. here and here) but only a very small amount for continuous snake or tron (e.g. here). Reading the write-ups of the other top competitors, and combining the most important insights from all to create a superbot. Below are write-ups of some of the solutions of students that were ranked higher than my agent in the end: The bot is a result of all its predecessors. Instead of writing new code all over again each time I made a lot of meta-functions. A lot of smaller functions can always be recycled to the next generation. These functions range from determining whether a move is legal, to calculating the number of available cells and distances to these cells. But combining all these functions can turn into something rather complex. The code first calculates if the opponent is in the same field as him, if he isn’t he takes the most left moves with the maximal number of available cells (floodfill). If they are in the same field it’s all about having the best floodfill in the future. It starts by going to the center (6, 6). If the snakes start at the border he goes as wide as possible to try and trick the opponent, otherwise it takes the most central route to try to cut the field in equal halves. The center of the playing field is a very important position. I made a special function for this move. He looks which positions could give him advantage without giving the opponent advantage. If he doesn’t find a such position he moves towards the center, resulting in many possible options. Once the bots are done fighting for center, I’ve defined a functions that simulates the field if my snake goes straight in every possible direction. It analyses if my bot can take advantage from there (bigger floodfill) and if distances to that spot is shorter. It analyses situations as ‘success’, ‘maybe draw’ or ‘success but longer distance’. For the moves I could make he also runs that function as if he was to opponent and doesn’t do moves that could result in advantage for the opponent. This can take a while, so it stops doing this after 0.7 seconds and it just assumes the opponent won’t have advantage. If no success moves are possible he tries to stay as close to center and the enemy as possible. At the beginning of every turn, the agent generates several variables based on the data it receives, some of them being 2D arrays with their length and width equal to the length and width of the playing board, others being single-element integers or Booleans. These variables serve as input for eventually deciding which hexagon adjacent to the agent is the most suitable to go to next, and consequently how the agent should rotate to reach that hexagon, which is the output. The aforementioned variables generated by the agent include: * a 2D array where each element that corresponds to a hexagon refers to the number of adjacent hexagons that are not occupied by one of both agents or their trails * a 2D array where each element that corresponds to a hexagon refers to the shortest possible distance from that hexagon to the edge of the playing board (expressed in hexagons) * a Boolean that indicates whether both agents can still reach each other After calculating these variables, the agent assigns weights to the 2D arrays based on the values of the single-element variables. The 2D arrays are multiplied by their respective weights, and subsequently added together to construct a final 2D array. Each element in this final array that corresponds to a hexagon on the board has been assigned a value that is comparatively high if the agent estimates a comparatively high chance of winning the game by moving to that hexagon, and comparatively low if it estimates a comparatively low chance. Finally, the agent will check every hexagon around its position for the hexagon with the highest corresponding value in the final array and will output the rotation necessary to reach that hexagon. The final agent has two major versions, v8 and v10, where v10 has almost the exact same strategy as v8 except it’s much faster because it represents the board as a graph (which I’ll explain later). Both agents have a large set of utility functions that allow to write code much faster because these can be copied between versions since their implementation stays the same (e.g. is position x playable? How many cells can the agent reach from position x? What is the distance between position x and y? What is the closest position in set s to position x?). The rest of the code consists of algorithms to determine the best move. Most of these algorithms filter the moves that are playable and passes them on to another algorithm to break ties. The first algorithm determines if we must decide between two or more areas, and only passes the moves that lead to the larger area. Then the agent checks if we can reach the opponent, if that’s not possible, we can just fill the remaining area with a filler algorithm. In all other cases it’s almost always optimal to go to the center of the board. If the agent is about to go to the center of the board, it first checks if the opponent can reach the center too. If he can, then the agent can possibly cut off the opponent by moving slightly to the left or slightly to the right, but only if the start positions were at the edge of the board and if cutting off results in a larger area than the area of the opponent. If none of the above special cases occurred, the agent falls back on its general flooding algorithm, which makes the move with results in the most cells that it can reach first. If the opponent can reach a cell at the same time as the agent, it counts as half a cell. If the flooding results in equal scores for several moves, it passes those moves to the multi ray casting algorithm, which is a rather old algorithm (v6) that casts rays from the position of both players and determines which move results in the largest area. The biggest difference between v8 and v10 lies in the filler algorithm. While v8 only casts single rays from the players position to determine the largest possible area, v10 composes a graph from the grid. This is done by mapping every position in the grid to a number from 0 till 126. Because ray casting could still be useful, I had to define a direction for the nodes in the graph, so I defined a 127x5 grid where get_next_nodes()[node][direction % 6] would give me the node the agent would reach if it went in that direction. Then a rather complex convert function would turn the grid into an adjacency list. Instead of ray casting, the agent could now determine articulation points in the graph. The agent can now fill the area by making the move that results in the least articulation points in the next two moves. This results in a perfect fill of any area. IMPORTANT: Maxim published the code on his GitHub. Be sure to check out the winning solution of the competition. You can even simulate games between mine and his agent! All code for the agent discussed within this blog post is available on GitHub. I did my best to clean and optimize the code as much as possible, but it is definitely not yet perfect. Therefore, submitting a pull request or opening issues is more than welcome! Moreover, as always, if anything in this blog post was unclear or requires further clarification, feel free to leave a comment, or contact me! If you have any cool suggestions for a game for next year, please feel free to leave a comment as well! Wow, you reached the end of this blog post! Kudos to you. See you next year for the third AI competition ;),Gilles
[ { "code": null, "e": 665, "s": 171, "text": "A new academic year, which means a new batch of bright students taking their first steps in their engineering career. As last year, three of my fellow course assistants (Elias, Pieter and Ozan) and I created a platform for an AI bot competition, to be hosted during the course of Informatics (in which they learn to program in Python), given by prof. Dhoedt at Ghent University. This year, we decided to host the game of Tron (sometimes called continuous snake or Lightriders), as shown below." }, { "code": null, "e": 1035, "s": 665, "text": "Since both Riddles.io and CodinGame (which you should definitely check out if you are interested in AI bots!) host an AI competition for Tron as well, we decided to slightly adapt the game to be played on a hexagonal grid, instead of a square. This to avoid students just copy-pasting available solutions of those platforms. A screenshot of the game can be found below." }, { "code": null, "e": 1321, "s": 1035, "text": "As last year, I decided to compete in the competition myself, but did not find that much spare time. Hence, my solution wasn’t a very strong one. Nevertheless, I ended up pretty high on the leaderboard (5th spot), with a minimal code base and a simple heuristic, based on path finding." }, { "code": null, "e": 1492, "s": 1321, "text": "To discuss my solution, I will not need as much time/lines as last year, and therefore I decided to add some extra content. I split this blog post up in several sections:" }, { "code": null, "e": 1682, "s": 1492, "text": "Game and competition rulesA detailed overview of my strong heuristic (with code)A write-up by some of the top competitorsAn overview of how the competition platform was made (separate post)" }, { "code": null, "e": 1709, "s": 1682, "text": "Game and competition rules" }, { "code": null, "e": 1764, "s": 1709, "text": "A detailed overview of my strong heuristic (with code)" }, { "code": null, "e": 1806, "s": 1764, "text": "A write-up by some of the top competitors" }, { "code": null, "e": 1875, "s": 1806, "text": "An overview of how the competition platform was made (separate post)" }, { "code": null, "e": 2369, "s": 1875, "text": "The rules of the game are rather straight-forward. Both players start at a random position (mirrored around the center of the map) and with a random orientation (there are 6 orientations in total). Each player must then decide if they want to rotate their snake (120° or 60° CW/CCW or 0°), before making a move forward (as depicted in the figure below). Each snake leaves behind an impenetrable trail. The first snake that crashes into a wall or a trail of himself or opponent, loses the game." }, { "code": null, "e": 2429, "s": 2369, "text": "The submitted agents have to follow a predefined interface:" }, { "code": null, "e": 2748, "s": 2429, "text": "def generate_move(board, positions, orientations): \"\"\"Generate a move. Args: board (np.array): playing field positions (list): list of positions `(x, y)` orientations (list): list of orientations (int in [0,5]) Returns: move (int): integer in [-2,2] \"\"\" return 0" }, { "code": null, "e": 2811, "s": 2748, "text": "Moreover, each agent must comply to the following constraints:" }, { "code": null, "e": 2946, "s": 2811, "text": "It contains no import statements, with the exception of: numpy, functools, itertools, collections, operator, heapq, math, random, time" }, { "code": null, "e": 2995, "s": 2946, "text": "The file size must not be larger than 1 Megabyte" }, { "code": null, "e": 3055, "s": 2995, "text": "The execution time of generate_move may not exceed 1 second" }, { "code": null, "e": 3397, "s": 3055, "text": "After submitting your first agent to our platform, you will be matched up with another player every 30 minutes. After each match, rankings (TrueSkill or ELO) of both players are adjusted according to the match result, and these rankings are used for the leaderboard. For more information on the ranking systems, please refer to my next post." }, { "code": null, "e": 3978, "s": 3397, "text": "The competition lasted for about 1 month. We noticed that luck had a significant impact on your final rank (due to the matchmaking algorithm). To combat this, and to end up with an as objective ranking as possible, we took the top-competitors from the leaderboard after a certain amount of time (first-year students only). These competitors were chosen to compete in the “play-offs”, where each agent played all other agents four times. For each win, an agent was assigned three points, while a draw (of which there were many) resulted in both agents being awarded a single point." }, { "code": null, "e": 4547, "s": 3978, "text": "Before implementing more complex techniques, such as reinforcement learning, genetic algorithms and alpha-beta pruning, it is always good practice to first implement an agent based on a heuristic. These can be used to test the strengths of your opponents, but more importantly the strength of later versions of your agent. Unfortunately, I did not manage to implement more complex techniques this year due to a lack of time and only uploaded my baseline agent, based on a heuristic (which turned out to be very strong). I will now discuss my implementation thoroughly." }, { "code": null, "e": 5117, "s": 4547, "text": "The main reasoning behind my agent is rather simple: “always pick the move which results in a maximal difference between the number of tiles you can reach first, and the number of tiles your opponent can reach first.” Obviously, there will be many situations in which each possible move results in the same score (especially in the beginning of the game). We break ties by minimizing the number of remaining legal moves after making a certain move and by minimizing the distance towards the middle (if it still can be reached). The main game loop thus looks as follows:" }, { "code": null, "e": 5701, "s": 5117, "text": "Now let’s break everything down, starting from (probably) the most simple part in the code: getting all legal moves (get_legal_moves). In this function, we iterate over each integer in the interval [-2, 2] which are the five possible moves. We map each integer to a tuple of offsets (get_steps) that correspond to our move and update our positions and orientations hypothetically (_update_pos_orient) according to these offsets. Then, we calculate whether we still reside in the hexagonal grid (_valid_position) and whether we did not crash into an already occupied cell (_no_crash):" }, { "code": null, "e": 6295, "s": 5701, "text": "The code is rather straight-forward and probably does not need a lot of elaboration. To check whether we still reside in the hexagonal grid, we have to ensure that we do not get an IndexError by checking if our x and y coordinates do not go out of the bounds of our playing fields. Moreover, since the board representation is a square with some cells that are not reachable, we need to ensure that our agent does not move onto one of these cells. By inspecting the smaller (7x7) playing field depicted on the homepage we notice that the sum of x and y of the legal cells is bounded by 3 and 9." }, { "code": null, "e": 6365, "s": 6295, "text": "This generalizes to all playing field sizes and we can thus say that:" }, { "code": null, "e": 7035, "s": 6365, "text": "with k the size of the playing field. Moreover, to check whether we are not moving on an already occupied cell, we can just take the sum along the final axis of our playing board (remember that the final axis of this board contains a bitmap for each player) and check whether the value at the coordinate we want to move to is equal to 0. Further, the order of the offsets in _get_steps is order specifically such that we can directly index them using our newly calculated orientation, which is equal to (orientation + action) % 6. Using this new orientation, we can get the corresponding offsets and add these to our current coordinates to calculate our new coordinate." }, { "code": null, "e": 7536, "s": 7035, "text": "Now that we have a list of all the moves that will not result in us immediately losing, we can calculate a score for each of these moves, based on a heuristic. The heuristic we used is based on distances to each possible tile in the game field. We want to maximize the number of tiles we can reach in less moves than our opponent while minimizing the number of tiles he or she can reach first. A nice GIF, taken from the winning solution’s write-up in the Google Tron AI Challenge is displayed below." }, { "code": null, "e": 8289, "s": 7536, "text": "To calculate the minimal distance from a certain coordinate to another cell, we can use the A* path-finding algorithm or Dijkstra. But since we need to calculate a distance to all cells in our grid, we use a slightly adapted version. We keep track of a list of cells that still need to be visited (and the distances to each of these cells), called a frontier. For each cell in our frontier, we expand in all possible directions and add these new cells to our frontier (with a distance equal to our old distance + 1) if they have not yet been explored or if we discovered a path with a smaller amount of moves. Once we have calculated the distances to all cells for both players, we can easily calculate the number of tiles both players can reach first:" }, { "code": null, "e": 8989, "s": 8289, "text": "And that’s it! It’s that simple. In summary, we retrieve a list of all possible legal moves we can make, we then iterate over these legal moves and calculate a score for each of them. The score is based on the number of tiles we can reach first from the new position after making that move and the number of tiles our opponent can reach first. There are a few extra details, such as subtracting a penalty term from the score if we are too close to our opponent to avoid head-to-head crashes and the handling in case of ties (which are broken based on the number of legal moves remaining to fill up the board and based on the distance to the middle, since that is important in the start of the game)." }, { "code": null, "e": 9168, "s": 8989, "text": "As mentioned, only a limited amount of time was spent this year on writing my agent. Therefore, many possible improvements are left open. The most important ones are listed here:" }, { "code": null, "e": 9550, "s": 9168, "text": "An adaptation of the heuristic function could result in significant gains. According to the write-up of the Google Tron AI Challenge this resulted in the author winning the competition. In his blog post, a nice example game state is provided, where the heuristic function used for my agent would assign a negative score while we (again we are red) are actually on the winning hand:" }, { "code": null, "e": 10187, "s": 9550, "text": "Instead of calculating a score for each possible move, we could calculate a score for each possible sequence of moves, thus looking ahead more than 1 move. To solve this, we usually apply techniques such as alpha-beta pruning, but a few extra considerations will need to made since both players move simultaneously. One simple hack is to first retrieve all legal moves for your opponent, before iterating over all your legal moves (changing the game state) and then recursively call your opponent, passing along those moves. This ensures that both players can calculate their legal moves, using the same game state during the recursion." }, { "code": null, "e": 10744, "s": 10187, "text": "Calculating the score for each possible move (or sequence of moves) using Monte Carlo simulations, instead of using a heuristic function. Here, we would simulate a large number of games starting from a certain game state where each agent would make a random, but legal, move. The fraction of games we win from these simulations could be a good indication of the strength of a certain game state. Of course, it should be noted that the maximum time to make a move is only one second. I have not tested how many simulations one could make within that second." }, { "code": null, "e": 11239, "s": 10744, "text": "Evolving neural networks to play the game for you, is a very generic strategy that requires no knowledge of the game itself. It would require quite a lot of work to write a framework for this (or configure an already existing one), but once it is written (or get the hang of the existing framework), it could easily be adapted for other games. I found a lot of examples for the single-player snake game (e.g. here and here) but only a very small amount for continuous snake or tron (e.g. here)." }, { "code": null, "e": 11364, "s": 11239, "text": "Reading the write-ups of the other top competitors, and combining the most important insights from all to create a superbot." }, { "code": null, "e": 11471, "s": 11364, "text": "Below are write-ups of some of the solutions of students that were ranked higher than my agent in the end:" }, { "code": null, "e": 11888, "s": 11471, "text": "The bot is a result of all its predecessors. Instead of writing new code all over again each time I made a lot of meta-functions. A lot of smaller functions can always be recycled to the next generation. These functions range from determining whether a move is legal, to calculating the number of available cells and distances to these cells. But combining all these functions can turn into something rather complex." }, { "code": null, "e": 12651, "s": 11888, "text": "The code first calculates if the opponent is in the same field as him, if he isn’t he takes the most left moves with the maximal number of available cells (floodfill). If they are in the same field it’s all about having the best floodfill in the future. It starts by going to the center (6, 6). If the snakes start at the border he goes as wide as possible to try and trick the opponent, otherwise it takes the most central route to try to cut the field in equal halves. The center of the playing field is a very important position. I made a special function for this move. He looks which positions could give him advantage without giving the opponent advantage. If he doesn’t find a such position he moves towards the center, resulting in many possible options." }, { "code": null, "e": 13361, "s": 12651, "text": "Once the bots are done fighting for center, I’ve defined a functions that simulates the field if my snake goes straight in every possible direction. It analyses if my bot can take advantage from there (bigger floodfill) and if distances to that spot is shorter. It analyses situations as ‘success’, ‘maybe draw’ or ‘success but longer distance’. For the moves I could make he also runs that function as if he was to opponent and doesn’t do moves that could result in advantage for the opponent. This can take a while, so it stops doing this after 0.7 seconds and it just assumes the opponent won’t have advantage. If no success moves are possible he tries to stay as close to center and the enemy as possible." }, { "code": null, "e": 13837, "s": 13361, "text": "At the beginning of every turn, the agent generates several variables based on the data it receives, some of them being 2D arrays with their length and width equal to the length and width of the playing board, others being single-element integers or Booleans. These variables serve as input for eventually deciding which hexagon adjacent to the agent is the most suitable to go to next, and consequently how the agent should rotate to reach that hexagon, which is the output." }, { "code": null, "e": 13898, "s": 13837, "text": "The aforementioned variables generated by the agent include:" }, { "code": null, "e": 14062, "s": 13898, "text": "* a 2D array where each element that corresponds to a hexagon refers to the number of adjacent hexagons that are not occupied by one of both agents or their trails" }, { "code": null, "e": 14240, "s": 14062, "text": "* a 2D array where each element that corresponds to a hexagon refers to the shortest possible distance from that hexagon to the edge of the playing board (expressed in hexagons)" }, { "code": null, "e": 14314, "s": 14240, "text": "* a Boolean that indicates whether both agents can still reach each other" }, { "code": null, "e": 15057, "s": 14314, "text": "After calculating these variables, the agent assigns weights to the 2D arrays based on the values of the single-element variables. The 2D arrays are multiplied by their respective weights, and subsequently added together to construct a final 2D array. Each element in this final array that corresponds to a hexagon on the board has been assigned a value that is comparatively high if the agent estimates a comparatively high chance of winning the game by moving to that hexagon, and comparatively low if it estimates a comparatively low chance. Finally, the agent will check every hexagon around its position for the hexagon with the highest corresponding value in the final array and will output the rotation necessary to reach that hexagon." }, { "code": null, "e": 15255, "s": 15057, "text": "The final agent has two major versions, v8 and v10, where v10 has almost the exact same strategy as v8 except it’s much faster because it represents the board as a graph (which I’ll explain later)." }, { "code": null, "e": 15613, "s": 15255, "text": "Both agents have a large set of utility functions that allow to write code much faster because these can be copied between versions since their implementation stays the same (e.g. is position x playable? How many cells can the agent reach from position x? What is the distance between position x and y? What is the closest position in set s to position x?)." }, { "code": null, "e": 16069, "s": 15613, "text": "The rest of the code consists of algorithms to determine the best move. Most of these algorithms filter the moves that are playable and passes them on to another algorithm to break ties. The first algorithm determines if we must decide between two or more areas, and only passes the moves that lead to the larger area. Then the agent checks if we can reach the opponent, if that’s not possible, we can just fill the remaining area with a filler algorithm." }, { "code": null, "e": 16517, "s": 16069, "text": "In all other cases it’s almost always optimal to go to the center of the board. If the agent is about to go to the center of the board, it first checks if the opponent can reach the center too. If he can, then the agent can possibly cut off the opponent by moving slightly to the left or slightly to the right, but only if the start positions were at the edge of the board and if cutting off results in a larger area than the area of the opponent." }, { "code": null, "e": 16785, "s": 16517, "text": "If none of the above special cases occurred, the agent falls back on its general flooding algorithm, which makes the move with results in the most cells that it can reach first. If the opponent can reach a cell at the same time as the agent, it counts as half a cell." }, { "code": null, "e": 17044, "s": 16785, "text": "If the flooding results in equal scores for several moves, it passes those moves to the multi ray casting algorithm, which is a rather old algorithm (v6) that casts rays from the position of both players and determines which move results in the largest area." }, { "code": null, "e": 17909, "s": 17044, "text": "The biggest difference between v8 and v10 lies in the filler algorithm. While v8 only casts single rays from the players position to determine the largest possible area, v10 composes a graph from the grid. This is done by mapping every position in the grid to a number from 0 till 126. Because ray casting could still be useful, I had to define a direction for the nodes in the graph, so I defined a 127x5 grid where get_next_nodes()[node][direction % 6] would give me the node the agent would reach if it went in that direction. Then a rather complex convert function would turn the grid into an adjacency list. Instead of ray casting, the agent could now determine articulation points in the graph. The agent can now fill the area by making the move that results in the least articulation points in the next two moves. This results in a perfect fill of any area." }, { "code": null, "e": 18078, "s": 17909, "text": "IMPORTANT: Maxim published the code on his GitHub. Be sure to check out the winning solution of the competition. You can even simulate games between mine and his agent!" }, { "code": null, "e": 18338, "s": 18078, "text": "All code for the agent discussed within this blog post is available on GitHub. I did my best to clean and optimize the code as much as possible, but it is definitely not yet perfect. Therefore, submitting a pull request or opening issues is more than welcome!" }, { "code": null, "e": 18585, "s": 18338, "text": "Moreover, as always, if anything in this blog post was unclear or requires further clarification, feel free to leave a comment, or contact me! If you have any cool suggestions for a game for next year, please feel free to leave a comment as well!" } ]
Minimum K such that sum of array elements after division by K does not exceed S
01 Feb, 2022 Given an array arr[] of N elements and an integer S. The task is to find the minimum number K such that the sum of the array elements does not exceed S after dividing all the elements by K. Note: Consider integer division.Examples: Input: arr[] = {10, 7, 8, 10, 12, 19}, S = 27 Output: 3 After dividing by 3, the array becomes {3, 2, 2, 3, 4, 6} and the new sum is 20.Input: arr[] = {19, 17, 11, 10}, S = 40 Output: 2 Naive approach: Iterate for all values of K from 1 to the maximum element in the array plus one not maximum element because if we put k as maximum element then the sum will be one and what if the S is given to us as zero. So we iterate from k=1 to max element in the array plus one. and then sum up the array elements by dividing with K, if the sum does not exceed S then the current value will be the answer. The time complexity of this approach will be O(M * N) where M is the maximum element in the array.Efficient approach: An efficient approach is to find the value of K by performing a binary search on the answer. Initiate a binary search on the value of K and a check is done inside it to see if the sum exceeds K then the binary search is performed on the second half or the first half accordingly.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum value of k// that satisfies the given conditionint findMinimumK(int a[], int n, int s){ // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = min(ans, mid); high = mid - 1; } } return ans;} // Driver codeint main(){ int a[] = { 10, 7, 8, 10, 12, 19 }; int n = sizeof(a) / sizeof(a[0]); int s = 27; cout << findMinimumK(a, n, s); return 0;} // Java implementation of the approachclass GFG{ // Function to return the minimum value of k // that satisfies the given condition static int findMinimumK(int a[], int n, int s) { // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = Math.max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.min(ans, mid); high = mid - 1; } } return ans; } // Driver code public static void main (String[] args) { int a[] = { 10, 7, 8, 10, 12, 19 }; int n = a.length; int s = 27; System.out.println(findMinimumK(a, n, s)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the minimum value of k# that satisfies the given conditiondef findMinimumK(a, n, s): # Find the maximum element maximum = a[0] for i in range(n): maximum = max(maximum, a[i]) # Lowest answer can be 1 and the # highest answer can be (maximum + 1) low = 1 high = maximum + 1 ans = high # Binary search while (low <= high): # Get the mid element mid = (low + high) // 2 sum = 0 # Calculate the sum after dividing # the array by new K which is mid for i in range(n): sum += (a[i] // mid) # Search in the second half if (sum > s): low = mid + 1 # First half else: ans = min(ans, mid) high = mid - 1 return ans # Driver codea = [10, 7, 8, 10, 12, 19]n = len(a)s = 27 print(findMinimumK(a, n, s)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ // Function to return the minimum value of k // that satisfies the given condition static int findMinimumK(int []a, int n, int s) { // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = Math.Max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.Min(ans, mid); high = mid - 1; } } return ans; } // Driver code public static void Main () { int []a = { 10, 7, 8, 10, 12, 19 }; int n = a.Length; int s = 27; Console.WriteLine(findMinimumK(a, n, s)); }} // This code is contributed by AnkitRai01 <script>// javascript implementation of the approach // Function to return the minimum value of k // that satisfies the given condition function findMinimumK(a , n , s) { // Find the maximum element var maximum = a[0]; for (i = 0; i < n; i++) { maximum = Math.max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) var low = 1, high = maximum + 1; var ans = high; // Binary search while (low <= high) { // Get the mid element var mid = parseInt((low + high) / 2); var sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (i = 0; i < n; i++) { sum += parseInt( (a[i] / mid)); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.min(ans, mid); high = mid - 1; } } return ans; } // Driver code var a = [ 10, 7, 8, 10, 12, 19 ]; var n = a.length; var s = 27; document.write(findMinimumK(a, n, s)); // This code is contributed by todaysgaurav</script> 3 Time Complexity: O(N*(log N)), N=Array length Auxiliary Space: O(1) mohit kumar 29 ankthon aditya7409 todaysgaurav _bhupesh sumitgumber28 Binary Search Arrays Divide and Conquer Searching Arrays Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Merge Sort QuickSort Binary Search Median of two sorted arrays of different sizes Program for Tower of Hanoi
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2022" }, { "code": null, "e": 287, "s": 54, "text": "Given an array arr[] of N elements and an integer S. The task is to find the minimum number K such that the sum of the array elements does not exceed S after dividing all the elements by K. Note: Consider integer division.Examples: " }, { "code": null, "e": 474, "s": 287, "text": "Input: arr[] = {10, 7, 8, 10, 12, 19}, S = 27 Output: 3 After dividing by 3, the array becomes {3, 2, 2, 3, 4, 6} and the new sum is 20.Input: arr[] = {19, 17, 11, 10}, S = 40 Output: 2 " }, { "code": null, "e": 1334, "s": 474, "text": "Naive approach: Iterate for all values of K from 1 to the maximum element in the array plus one not maximum element because if we put k as maximum element then the sum will be one and what if the S is given to us as zero. So we iterate from k=1 to max element in the array plus one. and then sum up the array elements by dividing with K, if the sum does not exceed S then the current value will be the answer. The time complexity of this approach will be O(M * N) where M is the maximum element in the array.Efficient approach: An efficient approach is to find the value of K by performing a binary search on the answer. Initiate a binary search on the value of K and a check is done inside it to see if the sum exceeds K then the binary search is performed on the second half or the first half accordingly.Below is the implementation of the above approach: " }, { "code": null, "e": 1338, "s": 1334, "text": "C++" }, { "code": null, "e": 1343, "s": 1338, "text": "Java" }, { "code": null, "e": 1351, "s": 1343, "text": "Python3" }, { "code": null, "e": 1354, "s": 1351, "text": "C#" }, { "code": null, "e": 1365, "s": 1354, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum value of k// that satisfies the given conditionint findMinimumK(int a[], int n, int s){ // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = min(ans, mid); high = mid - 1; } } return ans;} // Driver codeint main(){ int a[] = { 10, 7, 8, 10, 12, 19 }; int n = sizeof(a) / sizeof(a[0]); int s = 27; cout << findMinimumK(a, n, s); return 0;}", "e": 2511, "s": 1365, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the minimum value of k // that satisfies the given condition static int findMinimumK(int a[], int n, int s) { // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = Math.max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.min(ans, mid); high = mid - 1; } } return ans; } // Driver code public static void main (String[] args) { int a[] = { 10, 7, 8, 10, 12, 19 }; int n = a.length; int s = 27; System.out.println(findMinimumK(a, n, s)); }} // This code is contributed by AnkitRai01", "e": 3977, "s": 2511, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum value of k# that satisfies the given conditiondef findMinimumK(a, n, s): # Find the maximum element maximum = a[0] for i in range(n): maximum = max(maximum, a[i]) # Lowest answer can be 1 and the # highest answer can be (maximum + 1) low = 1 high = maximum + 1 ans = high # Binary search while (low <= high): # Get the mid element mid = (low + high) // 2 sum = 0 # Calculate the sum after dividing # the array by new K which is mid for i in range(n): sum += (a[i] // mid) # Search in the second half if (sum > s): low = mid + 1 # First half else: ans = min(ans, mid) high = mid - 1 return ans # Driver codea = [10, 7, 8, 10, 12, 19]n = len(a)s = 27 print(findMinimumK(a, n, s)) # This code is contributed by Mohit Kumar", "e": 4938, "s": 3977, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum value of k // that satisfies the given condition static int findMinimumK(int []a, int n, int s) { // Find the maximum element int maximum = a[0]; for (int i = 0; i < n; i++) { maximum = Math.Max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) int low = 1, high = maximum + 1; int ans = high; // Binary search while (low <= high) { // Get the mid element int mid = (low + high) / 2; int sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (int i = 0; i < n; i++) { sum += (int)(a[i] / mid); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.Min(ans, mid); high = mid - 1; } } return ans; } // Driver code public static void Main () { int []a = { 10, 7, 8, 10, 12, 19 }; int n = a.Length; int s = 27; Console.WriteLine(findMinimumK(a, n, s)); }} // This code is contributed by AnkitRai01", "e": 6399, "s": 4938, "text": null }, { "code": "<script>// javascript implementation of the approach // Function to return the minimum value of k // that satisfies the given condition function findMinimumK(a , n , s) { // Find the maximum element var maximum = a[0]; for (i = 0; i < n; i++) { maximum = Math.max(maximum, a[i]); } // Lowest answer can be 1 and the // highest answer can be (maximum + 1) var low = 1, high = maximum + 1; var ans = high; // Binary search while (low <= high) { // Get the mid element var mid = parseInt((low + high) / 2); var sum = 0; // Calculate the sum after dividing // the array by new K which is mid for (i = 0; i < n; i++) { sum += parseInt( (a[i] / mid)); } // Search in the second half if (sum > s) low = mid + 1; // First half else { ans = Math.min(ans, mid); high = mid - 1; } } return ans; } // Driver code var a = [ 10, 7, 8, 10, 12, 19 ]; var n = a.length; var s = 27; document.write(findMinimumK(a, n, s)); // This code is contributed by todaysgaurav</script>", "e": 7701, "s": 6399, "text": null }, { "code": null, "e": 7703, "s": 7701, "text": "3" }, { "code": null, "e": 7751, "s": 7705, "text": "Time Complexity: O(N*(log N)), N=Array length" }, { "code": null, "e": 7773, "s": 7751, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7788, "s": 7773, "text": "mohit kumar 29" }, { "code": null, "e": 7796, "s": 7788, "text": "ankthon" }, { "code": null, "e": 7807, "s": 7796, "text": "aditya7409" }, { "code": null, "e": 7820, "s": 7807, "text": "todaysgaurav" }, { "code": null, "e": 7829, "s": 7820, "text": "_bhupesh" }, { "code": null, "e": 7843, "s": 7829, "text": "sumitgumber28" }, { "code": null, "e": 7857, "s": 7843, "text": "Binary Search" }, { "code": null, "e": 7864, "s": 7857, "text": "Arrays" }, { "code": null, "e": 7883, "s": 7864, "text": "Divide and Conquer" }, { "code": null, "e": 7893, "s": 7883, "text": "Searching" }, { "code": null, "e": 7900, "s": 7893, "text": "Arrays" }, { "code": null, "e": 7910, "s": 7900, "text": "Searching" }, { "code": null, "e": 7929, "s": 7910, "text": "Divide and Conquer" }, { "code": null, "e": 7943, "s": 7929, "text": "Binary Search" }, { "code": null, "e": 8041, "s": 7943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8073, "s": 8041, "text": "Introduction to Data Structures" }, { "code": null, "e": 8120, "s": 8073, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8145, "s": 8120, "text": "Window Sliding Technique" }, { "code": null, "e": 8176, "s": 8145, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8234, "s": 8176, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 8245, "s": 8234, "text": "Merge Sort" }, { "code": null, "e": 8255, "s": 8245, "text": "QuickSort" }, { "code": null, "e": 8269, "s": 8255, "text": "Binary Search" }, { "code": null, "e": 8316, "s": 8269, "text": "Median of two sorted arrays of different sizes" } ]
How to Serialize HashMap in Java?
08 Dec, 2020 Serialization is the process by which we convert an object into a stream of bytes and store these bytes in file systems/databases or put them on the network to move from one location to another. Deserialization is the reverse process of serialization. Deserialization consists of retrieving the objects from the byte stream. Hashmap: A HashMap stores items in key/value pairs, and we can access them by an index of another type (such as a string). Now to serialize anything, you have to implement the java.io.Serializable interface and HashMap also implements the Serializable interface. Then after serializing the HashMap, we will learn how to deserialize the hashmap in Java. Example 1: Serializing HashMap of String keys and String values In this example, we are serializing HashMap, where keys and values are the strings. We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program. Java // Java program on how to Serialize HashMap in Java import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.HashMap; public class HashMapExample1 { public static void main(String[] args) { HashMap<String, String> foodType = new HashMap<>(); // storing data in HashMap foodType.put("Burger", "Fastfood"); foodType.put("Cherries", "Fruit"); foodType.put("Fish", "Seafood"); foodType.put("Spinach", "Vegetables"); foodType.put("Chicken", "Protein-Rich"); // try catch block try { FileOutputStream myFileOutStream = new FileOutputStream( "/Users/piyushkumar/Downloads/Java/newHashMap.txt"); ObjectOutputStream myObjectOutStream = new ObjectOutputStream(myFileOutStream); myObjectOutStream.writeObject(foodType); // closing FileOutputStream and // ObjectOutputStream myObjectOutStream.close(); myFileOutStream.close(); } catch (IOException e) { e.printStackTrace(); } }} Output In the example above, we serialized the HashMap of foodType using the writeObject () method. Run this program and see in your file system that a file called “newHashMap.txt” is created and the entire HashMap (in encoded form) is saved. Now, we will learn how to read this file and deserialize the HashMap. Example 2: Deserializing HashMap of string keys and values It’s important to note that we can only store the deserialized HashMap into the reference variable of HashMap or any of its parent class. Other than that java.lang.ClassCastException Exception will occur. Java // Deserializing HashMap in Java import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class HashMapExample2 { public static void main(String[] args) { HashMap<String, String> newHashMap = null; try { FileInputStream fileInput = new FileInputStream( "/Users/piyushkumar/Downloads/Java/newHashMap.txt"); ObjectInputStream objectInput = new ObjectInputStream(fileInput); newHashMap = (HashMap)objectInput.readObject(); objectInput.close(); fileInput.close(); } catch (IOException obj1) { obj1.printStackTrace(); return; } catch (ClassNotFoundException obj2) { System.out.println("Class not found"); obj2.printStackTrace(); return; } System.out.println("Deserializing HashMap.."); // Displaying content in "newHashMap.txt" using // Iterator Set set = newHashMap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry)iterator.next(); System.out.print("key : " + entry.getKey() + " & Value : "); System.out.println(entry.getValue()); } }}} Output Java-HashMap Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Dec, 2020" }, { "code": null, "e": 247, "s": 52, "text": "Serialization is the process by which we convert an object into a stream of bytes and store these bytes in file systems/databases or put them on the network to move from one location to another." }, { "code": null, "e": 377, "s": 247, "text": "Deserialization is the reverse process of serialization. Deserialization consists of retrieving the objects from the byte stream." }, { "code": null, "e": 500, "s": 377, "text": "Hashmap: A HashMap stores items in key/value pairs, and we can access them by an index of another type (such as a string)." }, { "code": null, "e": 730, "s": 500, "text": "Now to serialize anything, you have to implement the java.io.Serializable interface and HashMap also implements the Serializable interface. Then after serializing the HashMap, we will learn how to deserialize the hashmap in Java." }, { "code": null, "e": 794, "s": 730, "text": "Example 1: Serializing HashMap of String keys and String values" }, { "code": null, "e": 1187, "s": 794, "text": "In this example, we are serializing HashMap, where keys and values are the strings. We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program." }, { "code": null, "e": 1192, "s": 1187, "text": "Java" }, { "code": "// Java program on how to Serialize HashMap in Java import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.HashMap; public class HashMapExample1 { public static void main(String[] args) { HashMap<String, String> foodType = new HashMap<>(); // storing data in HashMap foodType.put(\"Burger\", \"Fastfood\"); foodType.put(\"Cherries\", \"Fruit\"); foodType.put(\"Fish\", \"Seafood\"); foodType.put(\"Spinach\", \"Vegetables\"); foodType.put(\"Chicken\", \"Protein-Rich\"); // try catch block try { FileOutputStream myFileOutStream = new FileOutputStream( \"/Users/piyushkumar/Downloads/Java/newHashMap.txt\"); ObjectOutputStream myObjectOutStream = new ObjectOutputStream(myFileOutStream); myObjectOutStream.writeObject(foodType); // closing FileOutputStream and // ObjectOutputStream myObjectOutStream.close(); myFileOutStream.close(); } catch (IOException e) { e.printStackTrace(); } }}", "e": 2354, "s": 1192, "text": null }, { "code": null, "e": 2361, "s": 2354, "text": "Output" }, { "code": null, "e": 2455, "s": 2361, "text": "In the example above, we serialized the HashMap of foodType using the writeObject () method. " }, { "code": null, "e": 2668, "s": 2455, "text": "Run this program and see in your file system that a file called “newHashMap.txt” is created and the entire HashMap (in encoded form) is saved. Now, we will learn how to read this file and deserialize the HashMap." }, { "code": null, "e": 2727, "s": 2668, "text": "Example 2: Deserializing HashMap of string keys and values" }, { "code": null, "e": 2932, "s": 2727, "text": "It’s important to note that we can only store the deserialized HashMap into the reference variable of HashMap or any of its parent class. Other than that java.lang.ClassCastException Exception will occur." }, { "code": null, "e": 2937, "s": 2932, "text": "Java" }, { "code": "// Deserializing HashMap in Java import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class HashMapExample2 { public static void main(String[] args) { HashMap<String, String> newHashMap = null; try { FileInputStream fileInput = new FileInputStream( \"/Users/piyushkumar/Downloads/Java/newHashMap.txt\"); ObjectInputStream objectInput = new ObjectInputStream(fileInput); newHashMap = (HashMap)objectInput.readObject(); objectInput.close(); fileInput.close(); } catch (IOException obj1) { obj1.printStackTrace(); return; } catch (ClassNotFoundException obj2) { System.out.println(\"Class not found\"); obj2.printStackTrace(); return; } System.out.println(\"Deserializing HashMap..\"); // Displaying content in \"newHashMap.txt\" using // Iterator Set set = newHashMap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry)iterator.next(); System.out.print(\"key : \" + entry.getKey() + \" & Value : \"); System.out.println(entry.getValue()); } }}}", "e": 4393, "s": 2937, "text": null }, { "code": null, "e": 4400, "s": 4393, "text": "Output" }, { "code": null, "e": 4413, "s": 4400, "text": "Java-HashMap" }, { "code": null, "e": 4420, "s": 4413, "text": "Picked" }, { "code": null, "e": 4425, "s": 4420, "text": "Java" }, { "code": null, "e": 4439, "s": 4425, "text": "Java Programs" }, { "code": null, "e": 4444, "s": 4439, "text": "Java" }, { "code": null, "e": 4542, "s": 4444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4557, "s": 4542, "text": "Stream In Java" }, { "code": null, "e": 4578, "s": 4557, "text": "Introduction to Java" }, { "code": null, "e": 4599, "s": 4578, "text": "Constructors in Java" }, { "code": null, "e": 4618, "s": 4599, "text": "Exceptions in Java" }, { "code": null, "e": 4635, "s": 4618, "text": "Generics in Java" }, { "code": null, "e": 4661, "s": 4635, "text": "Java Programming Examples" }, { "code": null, "e": 4695, "s": 4661, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4742, "s": 4695, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4780, "s": 4742, "text": "Factory method design pattern in Java" } ]
Check if a given number is factorial of any number
26 May, 2022 Given a number n, the task is to determine whether n can be a factorial of some number xExamples: Input: N = 24 Output: Yes Explanation: 4! = 24 Input: N = 25 Output: No Approach: Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ implementation for// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if// the given number is a// factorial of any numberbool isFactorial(int n){ for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver Codeint main(){ int n = 24; bool ans = isFactorial(n); if (ans == 1) { cout << "Yes\n"; } else { cout << "No\n"; } return 0;} // C implementation for// the above approach#include <stdio.h>#include<stdbool.h> // Function to check if// the given number is a// factorial of any numberbool isFactorial(int n){ for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver codeint main(){ int n = 24; bool ans = isFactorial(n); if (ans == 1) { printf("Yes\n"); } else { printf("No\n"); }} // Thiss code is contributed by allwink45. // Java implementation for the above approachclass GFG{ // Function to check if the given number // is a factorial of any number static boolean isFactorial(int n) { for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; } } // Driver Code public static void main (String[] args) { int n = 24; boolean ans = isFactorial(n); if (ans == true) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to check if# the given number is a# factorial of any numberdef isFactorial(n) : i = 1; while(True) : if (n % i == 0) : n //= i; else : break; i += 1; if (n == 1) : return True; else : return False; # Driver Codeif __name__ == "__main__" : n = 24; ans = isFactorial(n); if (ans == 1) : print("Yes"); else : print("No"); # This code is contributed by kanugargng // C# implementation for the above approachusing System; class GFG{ // Function to check if the given number // is a factorial of any number static Boolean isFactorial(int n) { for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; } } // Driver Code public static void Main (String[] args) { int n = 24; Boolean ans = isFactorial(n); if (ans == true) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by 29AjayKumar <script> // Javascript implementation for// the above approach // Function to check if// the given number is a// factorial of any numberfunction isFactorial(n){ for (var i = 1;; i++) { if (n % i == 0) { n = parseInt(n/i); } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver Codevar n = 24;var ans = isFactorial(n);if (ans == 1){ document.write("Yes");}else{ document.write("No");} // This code is contributed by noob2000.</script> Yes Time Complexity: O(log10n) Auxiliary Space: O(1) kanugargng ankthon 29AjayKumar noob2000 subhammahato348 allwink45 factorial Numbers Mathematical School Programming Mathematical Numbers factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2022" }, { "code": null, "e": 152, "s": 52, "text": "Given a number n, the task is to determine whether n can be a factorial of some number xExamples: " }, { "code": null, "e": 225, "s": 152, "text": "Input: N = 24\nOutput: Yes\nExplanation: 4! = 24\n\nInput: N = 25\nOutput: No" }, { "code": null, "e": 289, "s": 227, "text": "Approach: Below is the implementation of the above approach: " }, { "code": null, "e": 293, "s": 289, "text": "C++" }, { "code": null, "e": 295, "s": 293, "text": "C" }, { "code": null, "e": 300, "s": 295, "text": "Java" }, { "code": null, "e": 308, "s": 300, "text": "Python3" }, { "code": null, "e": 311, "s": 308, "text": "C#" }, { "code": null, "e": 322, "s": 311, "text": "Javascript" }, { "code": "// C++ implementation for// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if// the given number is a// factorial of any numberbool isFactorial(int n){ for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver Codeint main(){ int n = 24; bool ans = isFactorial(n); if (ans == 1) { cout << \"Yes\\n\"; } else { cout << \"No\\n\"; } return 0;}", "e": 820, "s": 322, "text": null }, { "code": "// C implementation for// the above approach#include <stdio.h>#include<stdbool.h> // Function to check if// the given number is a// factorial of any numberbool isFactorial(int n){ for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver codeint main(){ int n = 24; bool ans = isFactorial(n); if (ans == 1) { printf(\"Yes\\n\"); } else { printf(\"No\\n\"); }} // Thiss code is contributed by allwink45.", "e": 1344, "s": 820, "text": null }, { "code": "// Java implementation for the above approachclass GFG{ // Function to check if the given number // is a factorial of any number static boolean isFactorial(int n) { for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; } } // Driver Code public static void main (String[] args) { int n = 24; boolean ans = isFactorial(n); if (ans == true) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by AnkitRai01", "e": 2166, "s": 1344, "text": null }, { "code": "# Python3 implementation of the approach # Function to check if# the given number is a# factorial of any numberdef isFactorial(n) : i = 1; while(True) : if (n % i == 0) : n //= i; else : break; i += 1; if (n == 1) : return True; else : return False; # Driver Codeif __name__ == \"__main__\" : n = 24; ans = isFactorial(n); if (ans == 1) : print(\"Yes\"); else : print(\"No\"); # This code is contributed by kanugargng", "e": 2720, "s": 2166, "text": null }, { "code": "// C# implementation for the above approachusing System; class GFG{ // Function to check if the given number // is a factorial of any number static Boolean isFactorial(int n) { for (int i = 1;; i++) { if (n % i == 0) { n /= i; } else { break; } } if (n == 1) { return true; } else { return false; } } // Driver Code public static void Main (String[] args) { int n = 24; Boolean ans = isFactorial(n); if (ans == true) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by 29AjayKumar", "e": 3557, "s": 2720, "text": null }, { "code": "<script> // Javascript implementation for// the above approach // Function to check if// the given number is a// factorial of any numberfunction isFactorial(n){ for (var i = 1;; i++) { if (n % i == 0) { n = parseInt(n/i); } else { break; } } if (n == 1) { return true; } else { return false; }} // Driver Codevar n = 24;var ans = isFactorial(n);if (ans == 1){ document.write(\"Yes\");}else{ document.write(\"No\");} // This code is contributed by noob2000.</script>", "e": 4131, "s": 3557, "text": null }, { "code": null, "e": 4135, "s": 4131, "text": "Yes" }, { "code": null, "e": 4162, "s": 4135, "text": "Time Complexity: O(log10n)" }, { "code": null, "e": 4184, "s": 4162, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4195, "s": 4184, "text": "kanugargng" }, { "code": null, "e": 4203, "s": 4195, "text": "ankthon" }, { "code": null, "e": 4215, "s": 4203, "text": "29AjayKumar" }, { "code": null, "e": 4224, "s": 4215, "text": "noob2000" }, { "code": null, "e": 4240, "s": 4224, "text": "subhammahato348" }, { "code": null, "e": 4250, "s": 4240, "text": "allwink45" }, { "code": null, "e": 4260, "s": 4250, "text": "factorial" }, { "code": null, "e": 4268, "s": 4260, "text": "Numbers" }, { "code": null, "e": 4281, "s": 4268, "text": "Mathematical" }, { "code": null, "e": 4300, "s": 4281, "text": "School Programming" }, { "code": null, "e": 4313, "s": 4300, "text": "Mathematical" }, { "code": null, "e": 4321, "s": 4313, "text": "Numbers" }, { "code": null, "e": 4331, "s": 4321, "text": "factorial" } ]
How to Add Fade and Shrink Animation in RecyclerView in Android?
12 Apr, 2021 In this article, we are going to show the fade and shrink animation in RecyclerView. When we move downward then the item at the top will be fading out and then it will shrink. In the output, we can see how it is happening. We will be implementing this Java programming language. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add this into build.gradle file implementation 'com.stone.vega.library:VegaLayoutManager:1.0.6' Step 3: Working with the items.xml file Go to the app > res > layout > New > Layout Resource File and name the file as item. Go to the item.xml file and refer to the following code. Below is the code for the item.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:id="@+id/itemclick" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click Here" /> </LinearLayout> Step 4: Working with the RecyclerViewAdapter.java file Create a new java class in android studio and name the class as RecyclerViewAdapter. Go to the RecyclerViewAdapter.java file and refer to the following code. Below is the code for the RecyclerViewAdapter.java file. Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private int mcount; public RecyclerViewAdapter(int mcount) { this.mcount = mcount; } @NonNull @Override public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final RecyclerViewAdapter.ViewHolder holder, final int position) { holder.itemclick.setText("Button" + position); holder.itemclick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(holder.itemView.getContext(), "Clicked : " + position, Toast.LENGTH_LONG).show(); } }); } @Override public int getItemCount() { return mcount; } public class ViewHolder extends RecyclerView.ViewHolder { Button itemclick; public ViewHolder(@NonNull View itemView) { super(itemView); itemclick = itemView.findViewById(R.id.itemclick); } }} Step 5: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rcv" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.RecyclerView; import com.pluscubed.recyclerfastscroll.RecyclerFastScroller;import com.stone.vega.library.VegaLayoutManager; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; RecyclerFastScroller fastScroller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.rcv); // We have used this to add fade and shrink method recyclerView.setLayoutManager(new VegaLayoutManager()); recyclerView.setAdapter(new RecyclerViewAdapter(50)); }} Output: Android-Animation Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2021" }, { "code": null, "e": 307, "s": 28, "text": "In this article, we are going to show the fade and shrink animation in RecyclerView. When we move downward then the item at the top will be fading out and then it will shrink. In the output, we can see how it is happening. We will be implementing this Java programming language." }, { "code": null, "e": 336, "s": 307, "text": "Step 1: Create a new Project" }, { "code": null, "e": 500, "s": 336, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 540, "s": 500, "text": "Step 2: Add this into build.gradle file" }, { "code": null, "e": 604, "s": 540, "text": "implementation 'com.stone.vega.library:VegaLayoutManager:1.0.6'" }, { "code": null, "e": 644, "s": 604, "text": "Step 3: Working with the items.xml file" }, { "code": null, "e": 827, "s": 644, "text": "Go to the app > res > layout > New > Layout Resource File and name the file as item. Go to the item.xml file and refer to the following code. Below is the code for the item.xml file." }, { "code": null, "e": 831, "s": 827, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <Button android:id=\"@+id/itemclick\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Click Here\" /> </LinearLayout>", "e": 1252, "s": 831, "text": null }, { "code": null, "e": 1307, "s": 1252, "text": "Step 4: Working with the RecyclerViewAdapter.java file" }, { "code": null, "e": 1523, "s": 1307, "text": "Create a new java class in android studio and name the class as RecyclerViewAdapter. Go to the RecyclerViewAdapter.java file and refer to the following code. Below is the code for the RecyclerViewAdapter.java file. " }, { "code": null, "e": 1528, "s": 1523, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private int mcount; public RecyclerViewAdapter(int mcount) { this.mcount = mcount; } @NonNull @Override public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final RecyclerViewAdapter.ViewHolder holder, final int position) { holder.itemclick.setText(\"Button\" + position); holder.itemclick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(holder.itemView.getContext(), \"Clicked : \" + position, Toast.LENGTH_LONG).show(); } }); } @Override public int getItemCount() { return mcount; } public class ViewHolder extends RecyclerView.ViewHolder { Button itemclick; public ViewHolder(@NonNull View itemView) { super(itemView); itemclick = itemView.findViewById(R.id.itemclick); } }}", "e": 3010, "s": 1528, "text": null }, { "code": null, "e": 3058, "s": 3010, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 3201, "s": 3058, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 3205, "s": 3201, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/rcv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>", "e": 3705, "s": 3205, "text": null }, { "code": null, "e": 3753, "s": 3705, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 3943, "s": 3753, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3948, "s": 3943, "text": "Java" }, { "code": "import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.RecyclerView; import com.pluscubed.recyclerfastscroll.RecyclerFastScroller;import com.stone.vega.library.VegaLayoutManager; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; RecyclerFastScroller fastScroller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.rcv); // We have used this to add fade and shrink method recyclerView.setLayoutManager(new VegaLayoutManager()); recyclerView.setAdapter(new RecyclerViewAdapter(50)); }}", "e": 4714, "s": 3948, "text": null }, { "code": null, "e": 4722, "s": 4714, "text": "Output:" }, { "code": null, "e": 4740, "s": 4722, "text": "Android-Animation" }, { "code": null, "e": 4748, "s": 4740, "text": "Android" }, { "code": null, "e": 4753, "s": 4748, "text": "Java" }, { "code": null, "e": 4758, "s": 4753, "text": "Java" }, { "code": null, "e": 4766, "s": 4758, "text": "Android" }, { "code": null, "e": 4864, "s": 4766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4933, "s": 4864, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4965, "s": 4933, "text": "Android SDK and it's Components" }, { "code": null, "e": 5014, "s": 4965, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5053, "s": 5014, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5095, "s": 5053, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5110, "s": 5095, "text": "Arrays in Java" }, { "code": null, "e": 5154, "s": 5110, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5190, "s": 5154, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5215, "s": 5190, "text": "Reverse a string in Java" } ]
\d vs \D in JavaScript?
There is a lot of difference between \d and \D in which the former results in the digits and the latter results in the non-digits such as e,^, etc. These are used along with global object "g" so that all the digits and non-digits across a text will be displayed in the output. Let's discuss it in detail. new RegExp("\\d", "g"); new RegExp("\\D", "g") In the following example, '\d' is used along with the global object "g" to get all the digits from the provided text. If the global object is not used, then only the first digit will be displayed in the output. Live Demo <html> <body> <script> var text = "one has to score 760+ in gmat to get into ivy colleges"; var regpat = /\d/g; var result = text.match(regpat); document.write(result); </script> </body> </html> 7,6,0 In the following example, \D\ is used along with global object 'g' to get all the non-digit characters such as t, y, ^, &, etc. Non-digit characters can include -, ^, &, etc and also can include spaces. Live Demo <html> <body> <script> var text = "one has to score 760+ in gmat to get into ivy colleges"; var regpat = /\D/g; var result = text.match(regpat); document.write(result); </script> </body> </html> o,n,e, ,h,a,s, ,t,o, ,s,c,o,r,e, ,+, ,i,n, ,g,m,a,t, ,t,o, ,g,e,t, ,i,n,t,o, ,i,v,y, ,c,o,l,l,e,g,e,s
[ { "code": null, "e": 1367, "s": 1062, "text": "There is a lot of difference between \\d and \\D in which the former results in the digits and the latter results in the non-digits such as e,^, etc. These are used along with global object \"g\" so that all the digits and non-digits across a text will be displayed in the output. Let's discuss it in detail." }, { "code": null, "e": 1391, "s": 1367, "text": "new RegExp(\"\\\\d\", \"g\");" }, { "code": null, "e": 1414, "s": 1391, "text": "new RegExp(\"\\\\D\", \"g\")" }, { "code": null, "e": 1626, "s": 1414, "text": "In the following example, '\\d' is used along with the global object \"g\" to get all the digits from the provided text. If the global object is not used, then only the first digit will be displayed in the output. " }, { "code": null, "e": 1637, "s": 1626, "text": " Live Demo" }, { "code": null, "e": 1844, "s": 1637, "text": "<html>\n<body>\n<script>\n var text = \"one has to score 760+ in gmat to get into ivy colleges\";\n var regpat = /\\d/g;\n var result = text.match(regpat);\n document.write(result);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1850, "s": 1844, "text": "7,6,0" }, { "code": null, "e": 2054, "s": 1850, "text": "In the following example, \\D\\ is used along with global object 'g' to get all the non-digit characters such as t, y, ^, &, etc. Non-digit characters can include -, ^, &, etc and also can include spaces. " }, { "code": null, "e": 2064, "s": 2054, "text": "Live Demo" }, { "code": null, "e": 2271, "s": 2064, "text": "<html>\n<body>\n<script>\n var text = \"one has to score 760+ in gmat to get into ivy colleges\";\n var regpat = /\\D/g;\n var result = text.match(regpat);\n document.write(result);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2373, "s": 2271, "text": "o,n,e, ,h,a,s, ,t,o, ,s,c,o,r,e, ,+, ,i,n, ,g,m,a,t, ,t,o, ,g,e,t, ,i,n,t,o, ,i,v,y, ,c,o,l,l,e,g,e,s" } ]
Connect Django Project to MongoDB - GeeksforGeeks
26 Nov, 2021 Djongo is a SQL to mongodb query transpiler. Using djongo we can use MongoDB as a backend database for our Django project. We don’t even need to change the Django ORM. The best part is that we can setup Django with MongoDB by adding just one line of code. There is no need to change serializers, views, or any other modules. Official Docs – https://pypi.org/project/djongo/ Working – Djongo translates a SQL query string into a MongoDB query document. Therefore, there is no need to change models, serializers, views or any Django features. Djongo supports all django contrib libraries which make it an easy to use connector. Requirements – 1. Python 3.6 or higher. 2. MongoDB 3.4 or higher. (If you are using nested queries then MongoDB 3.6 or higher is required.) Features : Reuse Django Models/ORM – As Django Models are compatible with Djongo, we can use reuse them. Integrity checks Djongo allows integrity checks like missing values before they are saved to the database.For eg- Missing values are never stored if we set null=False, blank=False in EmbeddedField Validators We can apply validation checks like URLValidator, EmailValidator, RegexValidator etc. before each fields are saved to the database. Usage : Step 1: Setup Virtual Environment virtualenv myenv myenv\Scripts\activate Step 2: Install Django pip install django Step 3: Install Djongo pip install djongo Step 4: Start Django Project django-admin startproject geeks_project Your project structure will look like this : Step 5: Make changes to settings.py file Now, open settings.py file. Comment out or remove previous SQL Database configuration and add the following code in settings.py file :settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'your-database-name', } } That’s it. Now you can Use Mongodb as a backend database for your django project, without changing a single django model! yuvraj_chandra MongoDB Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 23985, "s": 23957, "text": "\n26 Nov, 2021" }, { "code": null, "e": 24310, "s": 23985, "text": "Djongo is a SQL to mongodb query transpiler. Using djongo we can use MongoDB as a backend database for our Django project. We don’t even need to change the Django ORM. The best part is that we can setup Django with MongoDB by adding just one line of code. There is no need to change serializers, views, or any other modules." }, { "code": null, "e": 24360, "s": 24310, "text": "Official Docs – https://pypi.org/project/djongo/ " }, { "code": null, "e": 24613, "s": 24360, "text": "Working – Djongo translates a SQL query string into a MongoDB query document. Therefore, there is no need to change models, serializers, views or any Django features. Djongo supports all django contrib libraries which make it an easy to use connector. " }, { "code": null, "e": 24629, "s": 24613, "text": "Requirements – " }, { "code": null, "e": 24654, "s": 24629, "text": "1. Python 3.6 or higher." }, { "code": null, "e": 24754, "s": 24654, "text": "2. MongoDB 3.4 or higher. (If you are using nested queries then MongoDB 3.6 or higher is required.)" }, { "code": null, "e": 24767, "s": 24754, "text": "Features : " }, { "code": null, "e": 24861, "s": 24767, "text": "Reuse Django Models/ORM – As Django Models are compatible with Djongo, we can use reuse them." }, { "code": null, "e": 25058, "s": 24861, "text": "Integrity checks Djongo allows integrity checks like missing values before they are saved to the database.For eg- Missing values are never stored if we set null=False, blank=False in EmbeddedField" }, { "code": null, "e": 25202, "s": 25058, "text": "Validators We can apply validation checks like URLValidator, EmailValidator, RegexValidator etc. before each fields are saved to the database. " }, { "code": null, "e": 25211, "s": 25202, "text": "Usage : " }, { "code": null, "e": 25246, "s": 25211, "text": "Step 1: Setup Virtual Environment " }, { "code": null, "e": 25286, "s": 25246, "text": "virtualenv myenv\nmyenv\\Scripts\\activate" }, { "code": null, "e": 25311, "s": 25286, "text": "Step 2: Install Django " }, { "code": null, "e": 25330, "s": 25311, "text": "pip install django" }, { "code": null, "e": 25354, "s": 25330, "text": "Step 3: Install Djongo " }, { "code": null, "e": 25373, "s": 25354, "text": "pip install djongo" }, { "code": null, "e": 25403, "s": 25373, "text": "Step 4: Start Django Project " }, { "code": null, "e": 25443, "s": 25403, "text": "django-admin startproject geeks_project" }, { "code": null, "e": 25488, "s": 25443, "text": "Your project structure will look like this :" }, { "code": null, "e": 25531, "s": 25488, "text": "Step 5: Make changes to settings.py file " }, { "code": null, "e": 25677, "s": 25531, "text": "Now, open settings.py file. Comment out or remove previous SQL Database configuration and add the following code in settings.py file :settings.py" }, { "code": null, "e": 25795, "s": 25677, "text": " DATABASES = {\n 'default': {\n 'ENGINE': 'djongo',\n 'NAME': 'your-database-name',\n }\n }" }, { "code": null, "e": 25917, "s": 25795, "text": "That’s it. Now you can Use Mongodb as a backend database for your django project, without changing a single django model!" }, { "code": null, "e": 25932, "s": 25917, "text": "yuvraj_chandra" }, { "code": null, "e": 25940, "s": 25932, "text": "MongoDB" }, { "code": null, "e": 25954, "s": 25940, "text": "Python Django" }, { "code": null, "e": 25961, "s": 25954, "text": "Python" }, { "code": null, "e": 26059, "s": 25961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26068, "s": 26059, "text": "Comments" }, { "code": null, "e": 26081, "s": 26068, "text": "Old Comments" }, { "code": null, "e": 26099, "s": 26081, "text": "Python Dictionary" }, { "code": null, "e": 26134, "s": 26099, "text": "Read a file line by line in Python" }, { "code": null, "e": 26156, "s": 26134, "text": "Enumerate() in Python" }, { "code": null, "e": 26188, "s": 26156, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26230, "s": 26188, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26256, "s": 26230, "text": "Python String | replace()" }, { "code": null, "e": 26300, "s": 26256, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26325, "s": 26300, "text": "sum() function in Python" }, { "code": null, "e": 26362, "s": 26325, "text": "Create a Pandas DataFrame from Lists" } ]
Add a new column in Pandas Data Frame Using a Dictionary - GeeksforGeeks
09 Nov, 2018 Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary. Let’s take Example! # Python program to illustrate# Add a new column in Pandas # Importing the pandas Libraryimport pandas as pd # creating a data frame with some data values.data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data']) print (data_frame) Output: data 0 0 1 1 2 2 3 3 4 4 5 5 6 6 Now Using the above-written method lets try to add a new column to it. Let’s add the New columns named as “new_data_1”.Map Function : Adding column “new_data_1” by giving the functionality of getting week name for the column named “data”. Call map and pass the dict, this will perform a lookup and return the associated value for that key. Let’s Introduce variable week data typed as Dictionary that includes the name of days in the week. # Python program to illustrate# Add a new column in Pandas # Data Frame Using a Dictionary import pandas as pd data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data']) # Introducing weeks as dictionaryweeks = {0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday'} # Mapping the dictionary keys to the data frame.data_frame['new_data_1'] = data_frame['data'].map(weeks)print (data_frame) Output: data new_data_1 0 0 Sunday 1 1 Monday 2 2 Tuesday 3 3 Wednesday 4 4 Thursday 5 5 Friday 6 6 Saturday And, we have successfully added a column (Sunday, Monday....) at the end. Picked Python dictionary-programs Python pandas-dataFrame Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe sum() function in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24928, "s": 24900, "text": "\n09 Nov, 2018" }, { "code": null, "e": 25165, "s": 24928, "text": "Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary." }, { "code": null, "e": 25185, "s": 25165, "text": "Let’s take Example!" }, { "code": "# Python program to illustrate# Add a new column in Pandas # Importing the pandas Libraryimport pandas as pd # creating a data frame with some data values.data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data']) print (data_frame)", "e": 25434, "s": 25185, "text": null }, { "code": null, "e": 25442, "s": 25434, "text": "Output:" }, { "code": null, "e": 25487, "s": 25442, "text": " data \n0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n\n" }, { "code": null, "e": 25827, "s": 25487, "text": "Now Using the above-written method lets try to add a new column to it. Let’s add the New columns named as “new_data_1”.Map Function : Adding column “new_data_1” by giving the functionality of getting week name for the column named “data”. Call map and pass the dict, this will perform a lookup and return the associated value for that key." }, { "code": null, "e": 25926, "s": 25827, "text": "Let’s Introduce variable week data typed as Dictionary that includes the name of days in the week." }, { "code": "# Python program to illustrate# Add a new column in Pandas # Data Frame Using a Dictionary import pandas as pd data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data']) # Introducing weeks as dictionaryweeks = {0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday'} # Mapping the dictionary keys to the data frame.data_frame['new_data_1'] = data_frame['data'].map(weeks)print (data_frame)", "e": 26369, "s": 25926, "text": null }, { "code": null, "e": 26377, "s": 26369, "text": "Output:" }, { "code": null, "e": 26497, "s": 26377, "text": " data new_data_1\n0 0 Sunday\n1 1 Monday\n2 2 Tuesday\n3 3 Wednesday\n4 4 Thursday\n5 5 Friday\n6 6 Saturday\n\n" }, { "code": null, "e": 26571, "s": 26497, "text": "And, we have successfully added a column (Sunday, Monday....) at the end." }, { "code": null, "e": 26578, "s": 26571, "text": "Picked" }, { "code": null, "e": 26605, "s": 26578, "text": "Python dictionary-programs" }, { "code": null, "e": 26629, "s": 26605, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26653, "s": 26629, "text": "Technical Scripter 2018" }, { "code": null, "e": 26660, "s": 26653, "text": "Python" }, { "code": null, "e": 26679, "s": 26660, "text": "Technical Scripter" }, { "code": null, "e": 26777, "s": 26679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26786, "s": 26777, "text": "Comments" }, { "code": null, "e": 26799, "s": 26786, "text": "Old Comments" }, { "code": null, "e": 26817, "s": 26799, "text": "Python Dictionary" }, { "code": null, "e": 26839, "s": 26817, "text": "Enumerate() in Python" }, { "code": null, "e": 26871, "s": 26839, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26913, "s": 26871, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26950, "s": 26913, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26994, "s": 26950, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27023, "s": 26994, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27079, "s": 27023, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27104, "s": 27079, "text": "sum() function in Python" } ]
Deadlock with mutex locks
Deadlock can be occurred in a multithreaded Pthread program using mutex locks. Let’s see how it can be occurred. An unlocked mutex is initialized by the pthread_mutex_init() function. Using pthread_mutex_lock() and pthread_mutex_unlock() Mutex locks are acquired and released. If a thread try to acquire a locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner of the mutex lock invokes pthread_mutex_unlock(). Let’s take an example, two Mutex locks are created in the following Code − /* Create and initialize the mutex locks */ pthread mutex t mutex1; pthread mutex t mutex2; pthread mutex init(&mutex1,NULL); pthread mutex init(&mutex2,NULL); Next, two threads - thread1 and thread2 - are created, and both these threads have access to both mutex locks. Thread1 and thread2 run in the functions dosomework_1 and dosomework_2, respectively, as shown below − /* thread1 runs in this function */ void *dosomework_1(void *param) { pthread mutex lock(&mutex1); pthread mutex lock(&mutex2); /** * Do some work */ pthread mutex unlock(& mutex2); pthread mutex unlock(& mutex2); pthread exit(0); } /* thread2 runs in this function */ void *dosomework_2(void *param) { pthread mutex lock(&mutex2); pthread mutex lock(&mutex1); /** * Do some work */ pthread mutex unlock(&mutex1); pthread mutex unlock(&mutex2); pthread exit(0); } In this example, thread1 tries to acquire the mutex locks in the order mutex1, mutex2, while thread two tries to acquire the mutex locks in the order mutex2, mutex1, Deadlock is possible if thread1 acquires mutex1 while thread2 acquires mutex2. Even though deadlock is possible, it will not occur if thread1 can acquire and release the mutex locks for mutex1 and mutex2 before thread2 tries to acquire the locks. Of course, CPU scheduler scheduled the order in which the threads run. The above example illustrates a problem with handling deadlocks: it is difficult to identify and test for deadlocks that may occur only under certain scheduling circumstances.
[ { "code": null, "e": 1246, "s": 1062, "text": "Deadlock can be occurred in a multithreaded Pthread program using mutex locks. Let’s see how it can be occurred. An unlocked mutex is initialized by the pthread_mutex_init() function." }, { "code": null, "e": 1499, "s": 1246, "text": "Using pthread_mutex_lock() and pthread_mutex_unlock() Mutex locks are acquired and released. If a thread try to acquire a locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner of the mutex lock invokes pthread_mutex_unlock()." }, { "code": null, "e": 1574, "s": 1499, "text": "Let’s take an example, two Mutex locks are created in the following Code −" }, { "code": null, "e": 1734, "s": 1574, "text": "/* Create and initialize the mutex locks */\npthread mutex t mutex1;\npthread mutex t mutex2; pthread mutex init(&mutex1,NULL);\npthread mutex init(&mutex2,NULL);" }, { "code": null, "e": 1948, "s": 1734, "text": "Next, two threads - thread1 and thread2 - are created, and both these threads have access to both mutex locks. Thread1 and thread2 run in the functions dosomework_1 and dosomework_2, respectively, as shown below −" }, { "code": null, "e": 2466, "s": 1948, "text": "/* thread1 runs in this function */\nvoid *dosomework_1(void *param) {\n pthread mutex lock(&mutex1);\n pthread mutex lock(&mutex2);\n /**\n * Do some work */\n pthread mutex unlock(& mutex2);\n pthread mutex unlock(& mutex2);\n pthread exit(0); } /*\n thread2 runs in this function\n */ void *dosomework_2(void *param) {\n pthread mutex lock(&mutex2);\n pthread mutex lock(&mutex1);\n /**\n * Do some work */\n pthread mutex unlock(&mutex1);\n pthread mutex unlock(&mutex2);\n pthread exit(0);\n}" }, { "code": null, "e": 2537, "s": 2466, "text": "In this example, thread1 tries to acquire the mutex locks in the order" }, { "code": null, "e": 2545, "s": 2537, "text": "mutex1," }, { "code": null, "e": 2553, "s": 2545, "text": "mutex2," }, { "code": null, "e": 2616, "s": 2553, "text": "while thread two tries to acquire the mutex locks in the order" }, { "code": null, "e": 2624, "s": 2616, "text": "mutex2," }, { "code": null, "e": 2632, "s": 2624, "text": "mutex1," }, { "code": null, "e": 3126, "s": 2632, "text": "Deadlock is possible if thread1 acquires mutex1 while thread2 acquires mutex2. Even though deadlock is possible, it will not occur if thread1 can acquire and release the mutex locks for mutex1 and mutex2 before thread2 tries to acquire the locks. Of course, CPU scheduler scheduled the order in which the threads run. The above example illustrates a problem with handling deadlocks: it is difficult to identify and test for deadlocks that may occur only under certain scheduling circumstances." } ]
Puppet - Classes
Puppet classes are defined as a collection of resources, which are grouped together in order to get a target node or machine in a desired state. These classes are defined inside Puppet manifest files which is located inside Puppet modules. The main purpose of using a class is to reduce the same code repetition inside any manifest file or any other Puppet code. Following is an example of Puppet class. [root@puppetmaster manifests]# cat site.pp class f3backup ( $backup_home = '/backup', $backup_server = 'default', $myname = $::fqdn, $ensure = 'directory', ) { include '::f3backup::common' if ( $myname == '' or $myname == undef ) { fail('myname must not be empty') } @@file { "${backup_home}/f3backup/${myname}": # To support 'absent', though force will be needed ensure => $ensure, owner => 'backup', group => 'backup', mode => '0644', tag => "f3backup-${backup_server}", } } In the above example, we have two clients where the user needs to exist. As can be noticed we have repeated the same resource twice. One way of not doing the same task in combining the two nodes. [root@puppetmaster manifests]# cat site.pp node 'Brcleprod001','Brcleprod002' { user { 'vipin': ensure => present, uid => '101', shell => '/bin/bash', home => '/home/homer', } } Merging nodes in this fashion to perform the configuration is not a good practice. This can be simply achieved by creating a class and including the created class in nodes which is shown as follows. class vipin_g01063908 { user { 'g01063908': ensure => present, uid => '101', shell => '/bin/bash', home => '/home/g01063908', } } node 'Brcleprod001' { class {vipin_g01063908:} } node 'Brcleprod002' { class {vipin_g01063908:} } The point to be noticed is how the class structure looks like and how we added a new resource using the class keyword. Each syntax in Puppet has its own feature. Hence, the syntax one picks depend on the conditions. As in the above example, we have seen how to create a class and include it in a node. Now there are situations when we need to have different configurations on each node such as when one needs to have different users on each node using the same class. This feature is provided in Puppet using parameterized class. The configuration for a new class will look as shown in the following example. [root@puppetmaster ~]# cat /etc/puppet/manifests/site.pp class user_account ($username){ user { $username: ensure => present, uid => '101', shell => '/bin/bash', home => "/home/$username", } } node 'Brcleprod002' { class { user_account: username => "G01063908", } } node 'Brcleprod002' { class {user_account: username => "G01063909", } } When we apply the above site.pp manifest on nodes, then the output for each node will look like the following. [root@puppetagent1 ~]# puppet agent --test Info: Retrieving pluginfacts Info: Retrieving plugin Info: Caching catalog for puppetagent1.testing.dyndns.org Info: Applying configuration version '1419452655' Notice: /Stage[main]/User_account/User[homer]/ensure: created Notice: Finished catalog run in 0.15 seconds [root@brcleprod001 ~]# cat /etc/passwd | grep "vipin" G01063908:x:101:501::/home/G01063909:/bin/bash [root@Brcleprod002 ~]# puppet agent --test Info: Retrieving pluginfacts Info: Retrieving plugin Info: Caching catalog for puppetagent2.testing.dyndns.org Info: Applying configuration version '1419452725' Notice: /Stage[main]/User_account/User[bart]/ensure: created Notice: Finished catalog run in 0.19 seconds [root@puppetagent2 ~]# cat /etc/passwd | grep "varsha" G01063909:x:101:501::/home/G01063909:/bin/bash One can also set the default value of a class parameter as shown in the following code. [root@puppetmaster ~]# cat /etc/puppet/manifests/site.pp class user_account ($username = ‘g01063908'){ user { $username: ensure => present, uid => '101', shell => '/bin/bash', home => "/home/$username", } } node 'Brcleprod001' { class {user_account:} } node 'Brcleprod002' { class {user_account: username => "g01063909", } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2536, "s": 2173, "text": "Puppet classes are defined as a collection of resources, which are grouped together in order to get a target node or machine in a desired state. These classes are defined inside Puppet manifest files which is located inside Puppet modules. The main purpose of using a class is to reduce the same code repetition inside any manifest file or any other Puppet code." }, { "code": null, "e": 2577, "s": 2536, "text": "Following is an example of Puppet class." }, { "code": null, "e": 3169, "s": 2577, "text": "[root@puppetmaster manifests]# cat site.pp \nclass f3backup ( \n $backup_home = '/backup', \n $backup_server = 'default', \n $myname = $::fqdn, \n $ensure = 'directory', \n) { \n include '::f3backup::common' \n if ( $myname == '' or $myname == undef ) { \n fail('myname must not be empty') \n } \n @@file { \"${backup_home}/f3backup/${myname}\": \n # To support 'absent', though force will be needed \n ensure => $ensure, \n owner => 'backup', \n group => 'backup', \n mode => '0644', \n tag => \"f3backup-${backup_server}\", \n }\n} " }, { "code": null, "e": 3365, "s": 3169, "text": "In the above example, we have two clients where the user needs to exist. As can be noticed we have repeated the same resource twice. One way of not doing the same task in combining the two nodes." }, { "code": null, "e": 3587, "s": 3365, "text": "[root@puppetmaster manifests]# cat site.pp \nnode 'Brcleprod001','Brcleprod002' { \n user { 'vipin': \n ensure => present, \n uid => '101', \n shell => '/bin/bash', \n home => '/home/homer', \n } \n}" }, { "code": null, "e": 3786, "s": 3587, "text": "Merging nodes in this fashion to perform the configuration is not a good practice. This can be simply achieved by creating a class and including the created class in nodes which is shown as follows." }, { "code": null, "e": 4071, "s": 3786, "text": "class vipin_g01063908 { \n user { 'g01063908': \n ensure => present, \n uid => '101', \n shell => '/bin/bash', \n home => '/home/g01063908', \n } \n} \nnode 'Brcleprod001' { \n class {vipin_g01063908:} \n} \nnode 'Brcleprod002' { \n class {vipin_g01063908:} \n}" }, { "code": null, "e": 4287, "s": 4071, "text": "The point to be noticed is how the class structure looks like and how we added a new resource using the class keyword. Each syntax in Puppet has its own feature. Hence, the syntax one picks depend on the conditions." }, { "code": null, "e": 4680, "s": 4287, "text": "As in the above example, we have seen how to create a class and include it in a node. Now there are situations when we need to have different configurations on each node such as when one needs to have different users on each node using the same class. This feature is provided in Puppet using parameterized class. The configuration for a new class will look as shown in the following example." }, { "code": null, "e": 5098, "s": 4680, "text": "[root@puppetmaster ~]# cat /etc/puppet/manifests/site.pp \nclass user_account ($username){ \n user { $username: \n ensure => present, \n uid => '101', \n shell => '/bin/bash', \n home => \"/home/$username\", \n } \n} \nnode 'Brcleprod002' { \n class { user_account: \n username => \"G01063908\", \n } \n} \nnode 'Brcleprod002' { \n class {user_account: \n username => \"G01063909\", \n } \n} " }, { "code": null, "e": 5209, "s": 5098, "text": "When we apply the above site.pp manifest on nodes, then the output for each node will look like the following." }, { "code": null, "e": 5631, "s": 5209, "text": "[root@puppetagent1 ~]# puppet agent --test \nInfo: Retrieving pluginfacts \nInfo: Retrieving plugin \nInfo: Caching catalog for puppetagent1.testing.dyndns.org \nInfo: Applying configuration version '1419452655' \n\nNotice: /Stage[main]/User_account/User[homer]/ensure: created \nNotice: Finished catalog run in 0.15 seconds \n[root@brcleprod001 ~]# cat /etc/passwd | grep \"vipin\" \nG01063908:x:101:501::/home/G01063909:/bin/bash " }, { "code": null, "e": 6052, "s": 5631, "text": "[root@Brcleprod002 ~]# puppet agent --test \nInfo: Retrieving pluginfacts \nInfo: Retrieving plugin \nInfo: Caching catalog for puppetagent2.testing.dyndns.org \nInfo: Applying configuration version '1419452725' \n\nNotice: /Stage[main]/User_account/User[bart]/ensure: created \nNotice: Finished catalog run in 0.19 seconds \n[root@puppetagent2 ~]# cat /etc/passwd | grep \"varsha\" \nG01063909:x:101:501::/home/G01063909:/bin/bash" }, { "code": null, "e": 6140, "s": 6052, "text": "One can also set the default value of a class parameter as shown in the following code." }, { "code": null, "e": 6535, "s": 6140, "text": "[root@puppetmaster ~]# cat /etc/puppet/manifests/site.pp \nclass user_account ($username = ‘g01063908'){ \n user { $username: \n ensure => present, \n uid => '101', \n shell => '/bin/bash', \n home => \"/home/$username\", \n } \n} \nnode 'Brcleprod001' { \n class {user_account:} \n} \nnode 'Brcleprod002' { \n class {user_account: \n username => \"g01063909\", \n } \n} " }, { "code": null, "e": 6542, "s": 6535, "text": " Print" }, { "code": null, "e": 6553, "s": 6542, "text": " Add Notes" } ]
Fastest Way to multiply two Numbers
Two numbers are given as a binary string, our task is to find the result of multiplication for those numbers in a faster and efficient way. Using the Divide and Conquer strategy, we can solve the problem, in a very efficient manner. We will split the numbers into two halves. let Xleft and Xright are two parts of first number X, and Yleft, Yright are two parts of second number Y. So the product; To make it simple, we can perform this operation Input: Two binary numbers: 1101 and 0111 Output: The result is: 91 addBitString(num1, num2) Input: Two numbers to add. Output: The result after addition. Begin adjust num1 and num2 lengths length := length of num1 carry := 0 for i := length -1 down to 0, do num1Bit := num1[i] num2Bit := num2[i] sum := num1Bit XOR num2Bit XOR carry finalSum := sum + finalSum carry := (num1Bit AND num2Bit) OR (num2Bit AND carry) OR (num1Bit AND carry) done if carry ≠ 0, then finalSum := 1 + finalSum return finalSum End multiply(num1, num2) Input: Two numbers to multiply. Output: The result after multiplication. Begin adjust num1 and num2 lengths length := length of num1 if n = 0, then return 0 if n = 1, then return (num1[0] * num2[0]) firstHalf := n/2 secondHalf := (n - firstHalf) n1Left := substring of (0 to firstHalf) from num1 n1Right := substring of (firstHalf to secondHalf) from num1 n2Left := substring of (0 to firstHalf) from num2 n2Right := substring of (firstHalf to secondHalf) from num2 p1 := multiply(n1Left, n2Left) p2 := multiply(n1Right, n2Right) add1 := addBitString(n1Left, n1Right) add2 := addBitString(n2Left, n2Right) p3 := multiply(add1, add2) mask1 := shift 1 to left for 2*secondHalf bits mask2 := shift 1 to left for secondHalf bits return P1*mask2 + (p3 – p1 – p2)*mask2 + p2 End #include<iostream> using namespace std; int lengthAdjust(string &num1, string &num2) { //adjust length of binary string and send length of string int len1 = num1.size(); int len2 = num2.size(); if (len1 < len2) { for (int i = 0 ; i < len2 - len1 ; i++) num1 = '0' + num1; //add 0 before the first string } else if (len1 > len2) { for (int i = 0 ; i < len1 - len2 ; i++) num2 = '0' + num2; //add 0 before the second string } return num1.size(); } string addBitStrings(string num1, string num2) { string finalSum; int length = lengthAdjust(num1, num2); //adjust and update number lengths and store length int carry = 0; // Initialize carry for (int i = length-1 ; i >= 0 ; i--) { int num1Bit = num1[i] - '0'; int num2Bit = num2[i] - '0'; int sum = (num1Bit ^ num2Bit ^ carry)+'0'; //we know sum = A XOR B XOR C finalSum = (char)sum + finalSum; //the carry = (A AND B) OR (B AND C) OR (C AND A) carry = (num1Bit&num2Bit) | (num2Bit&carry) | (num1Bit&carry); } if (carry) //when carry is present finalSum = '1' + finalSum; //add carry as MSb return finalSum; } long int multiply(string num1, string num2) { int n = lengthAdjust(num1, num2); //find length after adjusting them if (n == 0) //when there is 0 length string, return 0 return 0; if (n == 1) return (num1[0] - '0')*(num2[0] - '0'); //perform single bit muliplication int firstHalf = n/2; // First half range int secondHalf = (n-firstHalf); // Second half range string num1Left = num1.substr(0, firstHalf); //first half of number 1 string num1Right = num1.substr(firstHalf, secondHalf); //second half of number 1 string num2Left = num2.substr(0, firstHalf); string num2Right = num2.substr(firstHalf, secondHalf); // find left right multiplication, and multiply after adding left and right part long int P1 = multiply(num1Left, num2Left); long int P2 = multiply(num1Right, num2Right); long int P3 = multiply(addBitStrings(num1Left, num1Right), addBitStrings(num2Left, num2Right)); return P1*(1<<(2*secondHalf)) + (P3 - P1 - P2)*(1<<secondHalf) + P2; } int main() { string num1, num2; cout << "Enter First number in Binary: "; cin >>num1; cout << "Enter Second number in Binary: "; cin >>num2; cout << "The result is: " << multiply(num1, num2); } Enter First number in Binary: 1101 Enter Second number in Binary: 0111 The result is: 91
[ { "code": null, "e": 1202, "s": 1062, "text": "Two numbers are given as a binary string, our task is to find the result of multiplication for those numbers in a faster and efficient way." }, { "code": null, "e": 1338, "s": 1202, "text": "Using the Divide and Conquer strategy, we can solve the problem, in a very efficient manner. We will split the numbers into two halves." }, { "code": null, "e": 1460, "s": 1338, "text": "let Xleft and Xright are two parts of first number X, and Yleft, Yright are two parts of second number Y. So the product;" }, { "code": null, "e": 1509, "s": 1460, "text": "To make it simple, we can perform this operation" }, { "code": null, "e": 1576, "s": 1509, "text": "Input:\nTwo binary numbers: 1101 and 0111\nOutput:\nThe result is: 91" }, { "code": null, "e": 1601, "s": 1576, "text": "addBitString(num1, num2)" }, { "code": null, "e": 1628, "s": 1601, "text": "Input: Two numbers to add." }, { "code": null, "e": 1663, "s": 1628, "text": "Output: The result after addition." }, { "code": null, "e": 2075, "s": 1663, "text": "Begin\n adjust num1 and num2 lengths\n length := length of num1\n carry := 0\n\n for i := length -1 down to 0, do\n num1Bit := num1[i]\n num2Bit := num2[i]\n sum := num1Bit XOR num2Bit XOR carry\n finalSum := sum + finalSum\n carry := (num1Bit AND num2Bit) OR (num2Bit AND carry) OR (num1Bit AND carry)\n done\n\n if carry ≠ 0, then\n finalSum := 1 + finalSum\n return finalSum\nEnd" }, { "code": null, "e": 2096, "s": 2075, "text": "multiply(num1, num2)" }, { "code": null, "e": 2128, "s": 2096, "text": "Input: Two numbers to multiply." }, { "code": null, "e": 2169, "s": 2128, "text": "Output: The result after multiplication." }, { "code": null, "e": 2939, "s": 2169, "text": "Begin\n adjust num1 and num2 lengths\n length := length of num1\n if n = 0, then\n return 0\n if n = 1, then\n return (num1[0] * num2[0])\n firstHalf := n/2\n secondHalf := (n - firstHalf)\n\n n1Left := substring of (0 to firstHalf) from num1\n n1Right := substring of (firstHalf to secondHalf) from num1\n n2Left := substring of (0 to firstHalf) from num2\n n2Right := substring of (firstHalf to secondHalf) from num2\n\n p1 := multiply(n1Left, n2Left)\n p2 := multiply(n1Right, n2Right)\n\n add1 := addBitString(n1Left, n1Right)\n add2 := addBitString(n2Left, n2Right)\n p3 := multiply(add1, add2)\n\n mask1 := shift 1 to left for 2*secondHalf bits\n mask2 := shift 1 to left for secondHalf bits\n return P1*mask2 + (p3 – p1 – p2)*mask2 + p2\nEnd" }, { "code": null, "e": 5365, "s": 2939, "text": "#include<iostream>\nusing namespace std;\n\nint lengthAdjust(string &num1, string &num2) { //adjust length of binary string and send length of string\n int len1 = num1.size();\n int len2 = num2.size();\n\n if (len1 < len2) {\n for (int i = 0 ; i < len2 - len1 ; i++)\n num1 = '0' + num1; //add 0 before the first string\n } else if (len1 > len2) {\n for (int i = 0 ; i < len1 - len2 ; i++)\n num2 = '0' + num2; //add 0 before the second string\n }\n return num1.size();\n}\n\nstring addBitStrings(string num1, string num2) {\n string finalSum;\n\n int length = lengthAdjust(num1, num2); //adjust and update number lengths and store length\n int carry = 0; // Initialize carry\n\n for (int i = length-1 ; i >= 0 ; i--) {\n int num1Bit = num1[i] - '0';\n int num2Bit = num2[i] - '0';\n\n int sum = (num1Bit ^ num2Bit ^ carry)+'0'; //we know sum = A XOR B XOR C\n\n finalSum = (char)sum + finalSum;\n //the carry = (A AND B) OR (B AND C) OR (C AND A)\n carry = (num1Bit&num2Bit) | (num2Bit&carry) | (num1Bit&carry);\n }\n\n if (carry) //when carry is present\n finalSum = '1' + finalSum; //add carry as MSb\n return finalSum;\n}\n\nlong int multiply(string num1, string num2) {\n int n = lengthAdjust(num1, num2); //find length after adjusting them\n if (n == 0) //when there is 0 length string, return 0\n return 0;\n if (n == 1)\n return (num1[0] - '0')*(num2[0] - '0'); //perform single bit muliplication\n\n int firstHalf = n/2; // First half range\n int secondHalf = (n-firstHalf); // Second half range\n\n string num1Left = num1.substr(0, firstHalf); //first half of number 1\n string num1Right = num1.substr(firstHalf, secondHalf); //second half of number 1\n string num2Left = num2.substr(0, firstHalf);\n string num2Right = num2.substr(firstHalf, secondHalf);\n\n // find left right multiplication, and multiply after adding left and right part\n long int P1 = multiply(num1Left, num2Left);\n long int P2 = multiply(num1Right, num2Right);\n long int P3 = multiply(addBitStrings(num1Left, num1Right), addBitStrings(num2Left, num2Right));\n\n return P1*(1<<(2*secondHalf)) + (P3 - P1 - P2)*(1<<secondHalf) + P2;\n}\n\nint main() {\n string num1, num2;\n cout << \"Enter First number in Binary: \"; cin >>num1;\n cout << \"Enter Second number in Binary: \"; cin >>num2;\n cout << \"The result is: \" << multiply(num1, num2);\n}" }, { "code": null, "e": 5454, "s": 5365, "text": "Enter First number in Binary: 1101\nEnter Second number in Binary: 0111\nThe result is: 91" } ]
Python Number floor() Method
Python number method floor() returns floor of x - the largest integer not greater than x. Following is the syntax for floor() method − import math math.floor( x ) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This is a numeric expression. x − This is a numeric expression. This method returns largest integer not greater than x. The following example shows the usage of floor() method. #!/usr/bin/python import math # This will import math module print "math.floor(-45.17) : ", math.floor(-45.17) print "math.floor(100.12) : ", math.floor(100.12) print "math.floor(100.72) : ", math.floor(100.72) print "math.floor(119L) : ", math.floor(119L) print "math.floor(math.pi) : ", math.floor(math.pi) When we run above program, it produces following result − math.floor(-45.17) : -46.0 math.floor(100.12) : 100.0 math.floor(100.72) : 100.0 math.floor(119L) : 119.0 math.floor(math.pi) : 3.0 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2244, "text": "Python number method floor() returns floor of x - the largest integer not greater than x." }, { "code": null, "e": 2380, "s": 2335, "text": "Following is the syntax for floor() method −" }, { "code": null, "e": 2409, "s": 2380, "text": "import math\n\nmath.floor( x )" }, { "code": null, "e": 2556, "s": 2409, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2590, "s": 2556, "text": "x − This is a numeric expression." }, { "code": null, "e": 2624, "s": 2590, "text": "x − This is a numeric expression." }, { "code": null, "e": 2680, "s": 2624, "text": "This method returns largest integer not greater than x." }, { "code": null, "e": 2737, "s": 2680, "text": "The following example shows the usage of floor() method." }, { "code": null, "e": 3049, "s": 2737, "text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.floor(-45.17) : \", math.floor(-45.17)\nprint \"math.floor(100.12) : \", math.floor(100.12)\nprint \"math.floor(100.72) : \", math.floor(100.72)\nprint \"math.floor(119L) : \", math.floor(119L)\nprint \"math.floor(math.pi) : \", math.floor(math.pi)" }, { "code": null, "e": 3107, "s": 3049, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3245, "s": 3107, "text": "math.floor(-45.17) : -46.0\nmath.floor(100.12) : 100.0\nmath.floor(100.72) : 100.0\nmath.floor(119L) : 119.0\nmath.floor(math.pi) : 3.0\n" }, { "code": null, "e": 3282, "s": 3245, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3298, "s": 3282, "text": " Malhar Lathkar" }, { "code": null, "e": 3331, "s": 3298, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3350, "s": 3331, "text": " Arnab Chakraborty" }, { "code": null, "e": 3385, "s": 3350, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3407, "s": 3385, "text": " In28Minutes Official" }, { "code": null, "e": 3441, "s": 3407, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3469, "s": 3441, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3504, "s": 3469, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3518, "s": 3504, "text": " Lets Kode It" }, { "code": null, "e": 3551, "s": 3518, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3568, "s": 3551, "text": " Abhilash Nelson" }, { "code": null, "e": 3575, "s": 3568, "text": " Print" }, { "code": null, "e": 3586, "s": 3575, "text": " Add Notes" } ]
Allowed Functional Dependencies (FD) in Various Normal Forms (NF) - GeeksforGeeks
18 May, 2021 Prerequisite – Functional Dependency and Attribute Closure We all know the following: 2 NF does not allow partial dependency. 3NF does not allow transitive dependency. BCNF does not allow anything other than super key as determinant. Let’s check all possible functional dependencies to find out what is allowed and what’s not. Please note: prime attribute is an attribute that is part of any candidate key. Non prime attribute is an attribute that is not part of any candidate key. So, its advisable that you find out all possible candidate keys from the given functional dependencies and mark the prime and non prime attributes. 1. Second Normal Form (2NF) : Not allowed FDs – prime -> non prime If say your functional dependency is of the form A->X where ‘A’ is a prime attribute but not a key and ‘X’ is a non prime attribute, then such an FD is not allowed in 2NF. Allowed FDs – Prime -> Prime Non prime -> Prime/Non prime Key -> Prime/Non prime Prime + Non prime combination -> Prime/Non Prime If ‘A’ is a prime attribute (though not a key) it can determine another prime attribute If ‘A’ is a non prime attribute, it can determine a prime/non prime attribute. If ‘A’ is a key, it can determine a prime/non prime attribute. 2. Third Normal Form (3NF) : Not allowed FDs – Prime -> Non prime (2NF requirement) Non prime -> Non prime (3NF special) Allowed FDs – Prime -> Prime Non prime -> Prime Key -> Prime/Non prime Prime + Non Prime -> Prime/Non prime 3. Boyce-Codd Normal Form (BCNF) : Not allowed FDs – Prime -> Non prime Non prime -> Non prime Prime -> Prime Non prime -> Prime Allowed – Key -> Prime/Non prime clintra DBMS-Normalization DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS KDD Process in Data Mining Conflict Serializability in DBMS Two Phase Locking Protocol Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 25575, "s": 25547, "text": "\n18 May, 2021" }, { "code": null, "e": 25635, "s": 25575, "text": "Prerequisite – Functional Dependency and Attribute Closure " }, { "code": null, "e": 25663, "s": 25635, "text": "We all know the following: " }, { "code": null, "e": 25703, "s": 25663, "text": "2 NF does not allow partial dependency." }, { "code": null, "e": 25745, "s": 25703, "text": "3NF does not allow transitive dependency." }, { "code": null, "e": 25811, "s": 25745, "text": "BCNF does not allow anything other than super key as determinant." }, { "code": null, "e": 26208, "s": 25811, "text": "Let’s check all possible functional dependencies to find out what is allowed and what’s not. Please note: prime attribute is an attribute that is part of any candidate key. Non prime attribute is an attribute that is not part of any candidate key. So, its advisable that you find out all possible candidate keys from the given functional dependencies and mark the prime and non prime attributes. " }, { "code": null, "e": 26239, "s": 26208, "text": "1. Second Normal Form (2NF) : " }, { "code": null, "e": 26258, "s": 26239, "text": "Not allowed FDs – " }, { "code": null, "e": 26278, "s": 26258, "text": "prime -> non prime " }, { "code": null, "e": 26451, "s": 26278, "text": "If say your functional dependency is of the form A->X where ‘A’ is a prime attribute but not a key and ‘X’ is a non prime attribute, then such an FD is not allowed in 2NF. " }, { "code": null, "e": 26467, "s": 26451, "text": "Allowed FDs – " }, { "code": null, "e": 26584, "s": 26467, "text": "Prime -> Prime\nNon prime -> Prime/Non prime\nKey -> Prime/Non prime\nPrime + Non prime combination -> Prime/Non Prime " }, { "code": null, "e": 26673, "s": 26584, "text": "If ‘A’ is a prime attribute (though not a key) it can determine another prime attribute " }, { "code": null, "e": 26753, "s": 26673, "text": "If ‘A’ is a non prime attribute, it can determine a prime/non prime attribute. " }, { "code": null, "e": 26817, "s": 26753, "text": "If ‘A’ is a key, it can determine a prime/non prime attribute. " }, { "code": null, "e": 26847, "s": 26817, "text": "2. Third Normal Form (3NF) : " }, { "code": null, "e": 26866, "s": 26847, "text": "Not allowed FDs – " }, { "code": null, "e": 26943, "s": 26866, "text": "Prime -> Non prime (2NF requirement)\nNon prime -> Non prime (3NF special) " }, { "code": null, "e": 26959, "s": 26943, "text": "Allowed FDs – " }, { "code": null, "e": 27056, "s": 26959, "text": "Prime -> Prime\nNon prime -> Prime \nKey -> Prime/Non prime \nPrime + Non Prime -> Prime/Non prime " }, { "code": null, "e": 27092, "s": 27056, "text": "3. Boyce-Codd Normal Form (BCNF) : " }, { "code": null, "e": 27112, "s": 27092, "text": "Not allowed FDs – " }, { "code": null, "e": 27193, "s": 27112, "text": "Prime -> Non prime \nNon prime -> Non prime \nPrime -> Prime \nNon prime -> Prime" }, { "code": null, "e": 27205, "s": 27193, "text": "Allowed – " }, { "code": null, "e": 27229, "s": 27205, "text": "Key -> Prime/Non prime " }, { "code": null, "e": 27239, "s": 27231, "text": "clintra" }, { "code": null, "e": 27258, "s": 27239, "text": "DBMS-Normalization" }, { "code": null, "e": 27263, "s": 27258, "text": "DBMS" }, { "code": null, "e": 27271, "s": 27263, "text": "GATE CS" }, { "code": null, "e": 27276, "s": 27271, "text": "DBMS" }, { "code": null, "e": 27374, "s": 27276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27391, "s": 27374, "text": "Deadlock in DBMS" }, { "code": null, "e": 27432, "s": 27391, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27459, "s": 27432, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27492, "s": 27459, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 27519, "s": 27492, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 27539, "s": 27519, "text": "Layers of OSI Model" }, { "code": null, "e": 27552, "s": 27539, "text": "TCP/IP Model" }, { "code": null, "e": 27579, "s": 27552, "text": "Types of Operating Systems" }, { "code": null, "e": 27628, "s": 27579, "text": "Page Replacement Algorithms in Operating Systems" } ]
Static and non static blank final variables in Java - GeeksforGeeks
08 Nov, 2017 A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class:Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. They are property of an object so they can be accessed using object only. Static variables : Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. They are property of a class not of an object so they can be used directly using class name as well as using object. // Java code to illustrate use of instance and static variablespublic class Emp { String name; int salary; static String company; public void printDetails() { System.out.println("Name: " + name); System.out.println("Company: " + company); System.out.println("Salary: " + salary); } public static void main(String s[]) { Emp.company = "GeeksForGeeks"; Emp g = new Emp(); g.name = "Shubham"; g.salary = 100000; Emp sp = new Emp(); sp.name = "Chirag"; sp.salary = 200000; g.printDetails(); sp.printDetails(); g.company = "Google"; g.salary = 200000; System.out.println("\nAfter change\n"); g.printDetails(); sp.printDetails(); }} Output: Name: Shubham Company: GeeksForGeeks Salary: 100000 Name: Chirag Company: GeeksForGeeks Salary: 200000 After change Name: Shubham Company: Google Salary: 200000 Name: Chirag Company: Google Salary: 200000 In the above example, by changing the company name it is reflected in all other objects as it is a static variable. But changing the salary of g doesn’t change the salary of s because salary is an instance variable. Blank final variable : A final variable declared but not assigned is known as a blank final variable. It can be initialized within a constructor only. It raises compilation error if it is not initialized because it should be given a value somewhere in the program and that too from a constructor only. Static blank final variable : It is a blank final variable declared as static. That is, a final static variable declared but not given a value or not initialized is known as static blank final variable.It can be initialized through a static block only.Here is an example illustrating initialization of blank final variables- // Java program to illustrate initialization // of blank final variablespublic class GFG { private static final int a; private final int b; static { a = 1; } GFG(int c) { b = c; } public static void main(String s[]) { GFG g1 = new GFG(10); GFG g2 = new GFG(20); System.out.println(GFG.a); System.out.println(g1.b); System.out.println(g1.b); }} Output: 1 10 10 In the above example, b is initialized using constructor while a using static block. Predict the output of the following program : // Java program to illustrate // static blank final variablepublic class UserLogin { public static final long GUEST_ID = -1; private static final long USER_ID; static { try { USER_ID = getID(); } catch (IdNotFound e) { USER_ID = GUEST_ID; System.out.println("Logging in as guest"); } } private static long getID() throws IdNotFound { throw new IdNotFound(); } public static void main(String[] args) { System.out.println("User ID: " + USER_ID); }}class IdNotFound extends Exception { IdNotFound() {}} Output: prog.java:8: error: variable USER_ID might already have been assigned USER_ID = GUEST_ID; ^ 1 error The USER_ID field is a static blank final. It is clear that the exception can be thrown in the try block only if the assignment to USER_ID fails, so it is perfectly safe to assign to USER_ID in the catch block. Any execution of the static initializer block will cause exactly one assignment to USER_ID, which is just what is required for blank finals. But this program fails because, A blank final field can be assigned only at points in the program where it is definitely unassigned. Here, compiler is not sure whether its been assigned in try block or not, so the program doesn’t compile. We can solve this by removing the static block and initializing the USER_ID at the time of declaration. // Java program to illustrate // static blank final variablepublic class UserLogin { public static final long GUEST_ID = -1; private static final long USER_ID = getUserIdOrGuest(); private static long getUserIdOrGuest() { try { return getID(); } catch (IdNotFound e) { System.out.println("Logging in as guest"); return GUEST_ID; } } private static long getID() throws IdNotFound { throw new IdNotFound(); } public static void main(String[] args) { System.out.println("User ID: " + USER_ID); }}class IdNotFound extends Exception { IdNotFound() {}} Output: Logging in as guest User ID: -1 This article is contributed by Shubham Juneja. 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. final keyword Java-final keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25671, "s": 25643, "text": "\n08 Nov, 2017" }, { "code": null, "e": 26223, "s": 25671, "text": "A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class:Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed. They are property of an object so they can be accessed using object only." }, { "code": null, "e": 26616, "s": 26223, "text": "Static variables : Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. They are property of a class not of an object so they can be used directly using class name as well as using object." }, { "code": "// Java code to illustrate use of instance and static variablespublic class Emp { String name; int salary; static String company; public void printDetails() { System.out.println(\"Name: \" + name); System.out.println(\"Company: \" + company); System.out.println(\"Salary: \" + salary); } public static void main(String s[]) { Emp.company = \"GeeksForGeeks\"; Emp g = new Emp(); g.name = \"Shubham\"; g.salary = 100000; Emp sp = new Emp(); sp.name = \"Chirag\"; sp.salary = 200000; g.printDetails(); sp.printDetails(); g.company = \"Google\"; g.salary = 200000; System.out.println(\"\\nAfter change\\n\"); g.printDetails(); sp.printDetails(); }}", "e": 27395, "s": 26616, "text": null }, { "code": null, "e": 27403, "s": 27395, "text": "Output:" }, { "code": null, "e": 27611, "s": 27403, "text": "Name: Shubham\nCompany: GeeksForGeeks\nSalary: 100000\nName: Chirag\nCompany: GeeksForGeeks\nSalary: 200000\n\nAfter change\n\nName: Shubham\nCompany: Google\nSalary: 200000\nName: Chirag\nCompany: Google\nSalary: 200000\n" }, { "code": null, "e": 27827, "s": 27611, "text": "In the above example, by changing the company name it is reflected in all other objects as it is a static variable. But changing the salary of g doesn’t change the salary of s because salary is an instance variable." }, { "code": null, "e": 28129, "s": 27827, "text": "Blank final variable : A final variable declared but not assigned is known as a blank final variable. It can be initialized within a constructor only. It raises compilation error if it is not initialized because it should be given a value somewhere in the program and that too from a constructor only." }, { "code": null, "e": 28454, "s": 28129, "text": "Static blank final variable : It is a blank final variable declared as static. That is, a final static variable declared but not given a value or not initialized is known as static blank final variable.It can be initialized through a static block only.Here is an example illustrating initialization of blank final variables-" }, { "code": "// Java program to illustrate initialization // of blank final variablespublic class GFG { private static final int a; private final int b; static { a = 1; } GFG(int c) { b = c; } public static void main(String s[]) { GFG g1 = new GFG(10); GFG g2 = new GFG(20); System.out.println(GFG.a); System.out.println(g1.b); System.out.println(g1.b); }}", "e": 28880, "s": 28454, "text": null }, { "code": null, "e": 28888, "s": 28880, "text": "Output:" }, { "code": null, "e": 28897, "s": 28888, "text": "1\n10\n10\n" }, { "code": null, "e": 28982, "s": 28897, "text": "In the above example, b is initialized using constructor while a using static block." }, { "code": null, "e": 29028, "s": 28982, "text": "Predict the output of the following program :" }, { "code": "// Java program to illustrate // static blank final variablepublic class UserLogin { public static final long GUEST_ID = -1; private static final long USER_ID; static { try { USER_ID = getID(); } catch (IdNotFound e) { USER_ID = GUEST_ID; System.out.println(\"Logging in as guest\"); } } private static long getID() throws IdNotFound { throw new IdNotFound(); } public static void main(String[] args) { System.out.println(\"User ID: \" + USER_ID); }}class IdNotFound extends Exception { IdNotFound() {}}", "e": 29646, "s": 29028, "text": null }, { "code": null, "e": 29654, "s": 29646, "text": "Output:" }, { "code": null, "e": 29755, "s": 29654, "text": "prog.java:8: error: variable USER_ID might already have been assigned\nUSER_ID = GUEST_ID;\n^\n1 error\n" }, { "code": null, "e": 30240, "s": 29755, "text": "The USER_ID field is a static blank final. It is clear that the exception can be thrown in the try block only if the assignment to USER_ID fails, so it is perfectly safe to assign to USER_ID in the catch block. Any execution of the static initializer block will cause exactly one assignment to USER_ID, which is just what is required for blank finals. But this program fails because, A blank final field can be assigned only at points in the program where it is definitely unassigned." }, { "code": null, "e": 30450, "s": 30240, "text": "Here, compiler is not sure whether its been assigned in try block or not, so the program doesn’t compile. We can solve this by removing the static block and initializing the USER_ID at the time of declaration." }, { "code": "// Java program to illustrate // static blank final variablepublic class UserLogin { public static final long GUEST_ID = -1; private static final long USER_ID = getUserIdOrGuest(); private static long getUserIdOrGuest() { try { return getID(); } catch (IdNotFound e) { System.out.println(\"Logging in as guest\"); return GUEST_ID; } } private static long getID() throws IdNotFound { throw new IdNotFound(); } public static void main(String[] args) { System.out.println(\"User ID: \" + USER_ID); }}class IdNotFound extends Exception { IdNotFound() {}}", "e": 31115, "s": 30450, "text": null }, { "code": null, "e": 31123, "s": 31115, "text": "Output:" }, { "code": null, "e": 31156, "s": 31123, "text": "Logging in as guest\nUser ID: -1\n" }, { "code": null, "e": 31458, "s": 31156, "text": "This article is contributed by Shubham Juneja. 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." }, { "code": null, "e": 31583, "s": 31458, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31597, "s": 31583, "text": "final keyword" }, { "code": null, "e": 31616, "s": 31597, "text": "Java-final keyword" }, { "code": null, "e": 31621, "s": 31616, "text": "Java" }, { "code": null, "e": 31626, "s": 31621, "text": "Java" }, { "code": null, "e": 31724, "s": 31626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31775, "s": 31724, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31805, "s": 31775, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31820, "s": 31805, "text": "Stream In Java" }, { "code": null, "e": 31839, "s": 31820, "text": "Interfaces in Java" }, { "code": null, "e": 31870, "s": 31839, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31888, "s": 31870, "text": "ArrayList in Java" }, { "code": null, "e": 31920, "s": 31888, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31940, "s": 31920, "text": "Stack Class in Java" }, { "code": null, "e": 31972, "s": 31940, "text": "Multidimensional Arrays in Java" } ]
Node.js Stream readable.setEncoding() Method - GeeksforGeeks
12 Oct, 2021 The readable.setEncoding() method in a Readable Stream is used to set the encoding of the data read. Syntax: readable.setEncoding( encoding ) Parameters: This method accepts single parameter encoding which holds the encoding type. Return Value: It returns the data in the encoded form. Below examples illustrate the use of readable.setEncoding() method in Node.js: Example 1: // Node.js program to demonstrate the // readable.setEncoding() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream("input.txt"); // Calling setEncoding methodreadable.setEncoding('hex'); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`);}); // Displays that program // is endedconsole.log("Program ends!!"); Output: Program ends!! 48656c6c6f Example 2: // Node.js program to demonstrate the // readable.setEncoding() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream("input.txt"); // Calling setEncoding methodreadable.setEncoding('base64'); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`);}); // Displays that program // is endedconsole.log("Program ends!!"); Output: Program ends!! SGVs bG8= Reference: https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding Node.js-Stream-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.redirect() Function How to read and write Excel file in Node.js ? Express.js res.send() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25869, "s": 25841, "text": "\n12 Oct, 2021" }, { "code": null, "e": 25970, "s": 25869, "text": "The readable.setEncoding() method in a Readable Stream is used to set the encoding of the data read." }, { "code": null, "e": 25978, "s": 25970, "text": "Syntax:" }, { "code": null, "e": 26011, "s": 25978, "text": "readable.setEncoding( encoding )" }, { "code": null, "e": 26100, "s": 26011, "text": "Parameters: This method accepts single parameter encoding which holds the encoding type." }, { "code": null, "e": 26155, "s": 26100, "text": "Return Value: It returns the data in the encoded form." }, { "code": null, "e": 26234, "s": 26155, "text": "Below examples illustrate the use of readable.setEncoding() method in Node.js:" }, { "code": null, "e": 26245, "s": 26234, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // readable.setEncoding() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream(\"input.txt\"); // Calling setEncoding methodreadable.setEncoding('hex'); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`);}); // Displays that program // is endedconsole.log(\"Program ends!!\");", "e": 26658, "s": 26245, "text": null }, { "code": null, "e": 26666, "s": 26658, "text": "Output:" }, { "code": null, "e": 26693, "s": 26666, "text": "Program ends!!\n48656c6c6f\n" }, { "code": null, "e": 26704, "s": 26693, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // readable.setEncoding() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream(\"input.txt\"); // Calling setEncoding methodreadable.setEncoding('base64'); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`);}); // Displays that program // is endedconsole.log(\"Program ends!!\");", "e": 27120, "s": 26704, "text": null }, { "code": null, "e": 27128, "s": 27120, "text": "Output:" }, { "code": null, "e": 27154, "s": 27128, "text": "Program ends!!\nSGVs\nbG8=\n" }, { "code": null, "e": 27237, "s": 27154, "text": "Reference: https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding" }, { "code": null, "e": 27259, "s": 27237, "text": "Node.js-Stream-module" }, { "code": null, "e": 27267, "s": 27259, "text": "Node.js" }, { "code": null, "e": 27284, "s": 27267, "text": "Web Technologies" }, { "code": null, "e": 27382, "s": 27284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27436, "s": 27382, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27473, "s": 27436, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27508, "s": 27473, "text": "Express.js res.redirect() Function" }, { "code": null, "e": 27554, "s": 27508, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 27585, "s": 27554, "text": "Express.js res.send() Function" }, { "code": null, "e": 27625, "s": 27585, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27670, "s": 27625, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27713, "s": 27670, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27775, "s": 27713, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Random sampling in numpy | random() function - GeeksforGeeks
26 Feb, 2019 numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters :size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned. Return : Array of random floats in the interval [0.0, 1.0). or a single such random float if size not provided. Code #1 : # Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random(size = 3)print ("Output 1D Array filled with random floats : ", out_arr) Output 1D Array filled with random floats : [ 0.21698734 0.01617363 0.70382199] Code #2 : # Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random(size =(2, 4))print ("Output 2D Array filled with random floats : ", out_arr) Output 2D Array filled with random floats : [[ 0.95423066 0.35595927 0.76048569 0.90163066] [ 0.41903408 0.85596254 0.21666156 0.05734769]] Code #3 : # Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random((2, 3, 2))print ("Output 3D Array filled with random floats : ", out_arr) Output 3D Array filled with random floats : [[[ 0.07861816 0.79132387] [ 0.9112629 0.98162851] [ 0.0727613 0.03480279]] [[ 0.11267727 0.07631742] [ 0.47554553 0.83625053] [ 0.67781339 0.37856642]]] Python numpy-Random sampling Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26185, "s": 26157, "text": "\n26 Feb, 2019" }, { "code": null, "e": 26375, "s": 26185, "text": "numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0)." }, { "code": null, "e": 26415, "s": 26375, "text": "Syntax : numpy.random.random(size=None)" }, { "code": null, "e": 26614, "s": 26415, "text": "Parameters :size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned." }, { "code": null, "e": 26726, "s": 26614, "text": "Return : Array of random floats in the interval [0.0, 1.0). or a single such random float if size not provided." }, { "code": null, "e": 26736, "s": 26726, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random(size = 3)print (\"Output 1D Array filled with random floats : \", out_arr) ", "e": 26955, "s": 26736, "text": null }, { "code": null, "e": 27039, "s": 26955, "text": "Output 1D Array filled with random floats : [ 0.21698734 0.01617363 0.70382199]\n" }, { "code": null, "e": 27051, "s": 27041, "text": "Code #2 :" }, { "code": "# Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random(size =(2, 4))print (\"Output 2D Array filled with random floats : \", out_arr) ", "e": 27274, "s": 27051, "text": null }, { "code": null, "e": 27423, "s": 27274, "text": "Output 2D Array filled with random floats : [[ 0.95423066 0.35595927 0.76048569 0.90163066]\n [ 0.41903408 0.85596254 0.21666156 0.05734769]]\n" }, { "code": null, "e": 27434, "s": 27423, "text": " Code #3 :" }, { "code": "# Python program explaining# numpy.random.random() function # importing numpyimport numpy as geek # output arrayout_arr = geek.random.random((2, 3, 2))print (\"Output 3D Array filled with random floats : \", out_arr) ", "e": 27652, "s": 27434, "text": null }, { "code": null, "e": 27870, "s": 27652, "text": "Output 3D Array filled with random floats : [[[ 0.07861816 0.79132387]\n [ 0.9112629 0.98162851]\n [ 0.0727613 0.03480279]]\n\n [[ 0.11267727 0.07631742]\n [ 0.47554553 0.83625053]\n [ 0.67781339 0.37856642]]]\n" }, { "code": null, "e": 27899, "s": 27870, "text": "Python numpy-Random sampling" }, { "code": null, "e": 27912, "s": 27899, "text": "Python-numpy" }, { "code": null, "e": 27919, "s": 27912, "text": "Python" }, { "code": null, "e": 28017, "s": 27919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28035, "s": 28017, "text": "Python Dictionary" }, { "code": null, "e": 28070, "s": 28035, "text": "Read a file line by line in Python" }, { "code": null, "e": 28102, "s": 28070, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28124, "s": 28102, "text": "Enumerate() in Python" }, { "code": null, "e": 28166, "s": 28124, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28196, "s": 28166, "text": "Iterate over a list in Python" }, { "code": null, "e": 28222, "s": 28196, "text": "Python String | replace()" }, { "code": null, "e": 28251, "s": 28222, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28295, "s": 28251, "text": "Reading and Writing to text files in Python" } ]
Selection Sort - GeeksforGeeks
09 May, 2022 The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which is already sorted. Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11} First pass: For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value. Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to appear in the first position of the sorted list. Second Pass: For the second position, where 25 is present, again traverse the rest of the array in a sequential manner. After traversing, we found that 12 is the second lowest value in the array and it should appear at the second place in the array, thus swap these values. Third Pass: Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array. While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position. Fourth pass: Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array As 25 is the 4th lowest value hence, it will place at the fourth position. Fifth Pass: At last the largest value present in the array automatically get placed at the last position in the array The resulted array is the sorted array. Initialize minimum value(min_idx) to location 0 Traverse the array to find the minimum element in the array While traversing if any element smaller than min_idx is found then swap both the values. Then, increment min_idx to point to next element Repeat until array is sorted Below is the implementation of the above approach: C++ C Python3 Java C# PHP Javascript // C++ program for implementation of// selection sort#include <bits/stdc++.h>using namespace std; //Swap functionvoid swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in // unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element swap(&arr[min_idx], &arr[i]); }} //Function to print an arrayvoid printArray(int arr[], int size){ int i; for (i=0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); cout << "Sorted array: \n"; printArray(arr, n); return 0;}// This is code is contributed by rathbhupendra // C program for implementation of selection sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;} # Python program for implementation of Selection# Sortimport sysA = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint ("Sorted array")for i in range(len(A)): print("%d" %A[i],end=" ") // Java program for implementation of Selection Sortclass SelectionSort{ void sort(int arr[]) { int n = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i]+" "); System.out.println(); } // Driver code to test above public static void main(String args[]) { SelectionSort ob = new SelectionSort(); int arr[] = {64,25,12,22,11}; ob.sort(arr); System.out.println("Sorted array"); ob.printArray(arr); }}/* This code is contributed by Rajat Mishra*/ // C# program for implementation// of Selection Sortusing System; class GFG{ static void sort(int []arr) { int n = arr.Length; // One by one move boundary of unsorted subarray for (int i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array static void printArray(int []arr) { int n = arr.Length; for (int i=0; i<n; ++i) Console.Write(arr[i]+" "); Console.WriteLine(); } // Driver code public static void Main() { int []arr = {64,25,12,22,11}; sort(arr); Console.WriteLine("Sorted array"); printArray(arr); } }// This code is contributed by Sam007 <?php// PHP program for implementation// of selection sortfunction selection_sort(&$arr, $n){ for($i = 0; $i < $n ; $i++) { $low = $i; for($j = $i + 1; $j < $n ; $j++) { if ($arr[$j] < $arr[$low]) { $low = $j; } } // swap the minimum value to $ith node if ($arr[$i] > $arr[$low]) { $tmp = $arr[$i]; $arr[$i] = $arr[$low]; $arr[$low] = $tmp; } }} // Driver Code$arr = array(64, 25, 12, 22, 11);$len = count($arr);selection_sort($arr, $len);echo "Sorted array : \n"; for ($i = 0; $i < $len; $i++) echo $arr[$i] . " "; // This code is contributed// by Deepika Gupta.?> <script>// Javascript program for implementation of selection sortfunction swap(arr,xp, yp){ var temp = arr[xp]; arr[xp] = arr[yp]; arr[yp] = temp;} function selectionSort(arr, n){ var i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(arr,min_idx, i); }} function printArray( arr, size){ var i; for (i = 0; i < size; i++) document.write(arr[i] + " "); document.write(" <br>");} var arr = [64, 25, 12, 22, 11]; var n = 5; selectionSort(arr, n); document.write("Sorted array: <br>"); printArray(arr, n); // This code is contributed by akshitsaxenaa09.</script> Sorted array: 11 12 22 25 64 Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested loops: One loop to select an element of Array one by one = O(N) Another loop to compare that element with every other Array element = O(N) Therefore overall complexity = O(N)*O(N) = O(N*N) = O(N2) Auxiliary Space: O(1) as the only extra memory used is for temporary variable while swapping two values in Array. The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. Stability : The default implementation is not stable. However it can be made stable. Please see stable selection sort for details. Yes, it does not require extra space. YouTubeGeeksforGeeks507K subscribersSelection Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xWBP4lzkoyM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Snapshots: Quiz on Selection SortOther Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Coding practice for sorting Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above DeepikaPathak RishiAdvani rathbhupendra navyab4u247 akshitsaxenaa09 amartyaghoshgfg kashishkumar2 Medlife Sorting Medlife Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Radix Sort Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array sort() in Python Bucket Sort Merge Sort for Linked Lists Python List sort() method
[ { "code": null, "e": 25105, "s": 25077, "text": "\n09 May, 2022" }, { "code": null, "e": 25329, "s": 25105, "text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array." }, { "code": null, "e": 25368, "s": 25329, "text": "The subarray which is already sorted. " }, { "code": null, "e": 25406, "s": 25368, "text": "Remaining subarray which is unsorted." }, { "code": null, "e": 25566, "s": 25406, "text": "In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. " }, { "code": null, "e": 25644, "s": 25566, "text": "Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}" }, { "code": null, "e": 25656, "s": 25644, "text": "First pass:" }, { "code": null, "e": 25880, "s": 25656, "text": "For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value." }, { "code": null, "e": 26038, "s": 25880, "text": "Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to appear in the first position of the sorted list." }, { "code": null, "e": 26051, "s": 26038, "text": "Second Pass:" }, { "code": null, "e": 26158, "s": 26051, "text": "For the second position, where 25 is present, again traverse the rest of the array in a sequential manner." }, { "code": null, "e": 26312, "s": 26158, "text": "After traversing, we found that 12 is the second lowest value in the array and it should appear at the second place in the array, thus swap these values." }, { "code": null, "e": 26324, "s": 26312, "text": "Third Pass:" }, { "code": null, "e": 26456, "s": 26324, "text": "Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array." }, { "code": null, "e": 26621, "s": 26456, "text": "While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position." }, { "code": null, "e": 26634, "s": 26621, "text": "Fourth pass:" }, { "code": null, "e": 26744, "s": 26634, "text": "Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array " }, { "code": null, "e": 26819, "s": 26744, "text": "As 25 is the 4th lowest value hence, it will place at the fourth position." }, { "code": null, "e": 26831, "s": 26819, "text": "Fifth Pass:" }, { "code": null, "e": 26937, "s": 26831, "text": "At last the largest value present in the array automatically get placed at the last position in the array" }, { "code": null, "e": 26977, "s": 26937, "text": "The resulted array is the sorted array." }, { "code": null, "e": 27025, "s": 26977, "text": "Initialize minimum value(min_idx) to location 0" }, { "code": null, "e": 27085, "s": 27025, "text": "Traverse the array to find the minimum element in the array" }, { "code": null, "e": 27174, "s": 27085, "text": "While traversing if any element smaller than min_idx is found then swap both the values." }, { "code": null, "e": 27223, "s": 27174, "text": "Then, increment min_idx to point to next element" }, { "code": null, "e": 27252, "s": 27223, "text": "Repeat until array is sorted" }, { "code": null, "e": 27303, "s": 27252, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27307, "s": 27303, "text": "C++" }, { "code": null, "e": 27309, "s": 27307, "text": "C" }, { "code": null, "e": 27317, "s": 27309, "text": "Python3" }, { "code": null, "e": 27322, "s": 27317, "text": "Java" }, { "code": null, "e": 27325, "s": 27322, "text": "C#" }, { "code": null, "e": 27329, "s": 27325, "text": "PHP" }, { "code": null, "e": 27340, "s": 27329, "text": "Javascript" }, { "code": "// C++ program for implementation of// selection sort#include <bits/stdc++.h>using namespace std; //Swap functionvoid swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in // unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element swap(&arr[min_idx], &arr[i]); }} //Function to print an arrayvoid printArray(int arr[], int size){ int i; for (i=0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); cout << \"Sorted array: \\n\"; printArray(arr, n); return 0;}// This is code is contributed by rathbhupendra", "e": 28405, "s": 27340, "text": null }, { "code": "// C program for implementation of selection sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}", "e": 29351, "s": 28405, "text": null }, { "code": "# Python program for implementation of Selection# Sortimport sysA = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint (\"Sorted array\")for i in range(len(A)): print(\"%d\" %A[i],end=\" \")", "e": 29893, "s": 29351, "text": null }, { "code": "// Java program for implementation of Selection Sortclass SelectionSort{ void sort(int arr[]) { int n = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i]+\" \"); System.out.println(); } // Driver code to test above public static void main(String args[]) { SelectionSort ob = new SelectionSort(); int arr[] = {64,25,12,22,11}; ob.sort(arr); System.out.println(\"Sorted array\"); ob.printArray(arr); }}/* This code is contributed by Rajat Mishra*/", "e": 31016, "s": 29893, "text": null }, { "code": "// C# program for implementation// of Selection Sortusing System; class GFG{ static void sort(int []arr) { int n = arr.Length; // One by one move boundary of unsorted subarray for (int i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array static void printArray(int []arr) { int n = arr.Length; for (int i=0; i<n; ++i) Console.Write(arr[i]+\" \"); Console.WriteLine(); } // Driver code public static void Main() { int []arr = {64,25,12,22,11}; sort(arr); Console.WriteLine(\"Sorted array\"); printArray(arr); } }// This code is contributed by Sam007", "e": 32069, "s": 31016, "text": null }, { "code": "<?php// PHP program for implementation// of selection sortfunction selection_sort(&$arr, $n){ for($i = 0; $i < $n ; $i++) { $low = $i; for($j = $i + 1; $j < $n ; $j++) { if ($arr[$j] < $arr[$low]) { $low = $j; } } // swap the minimum value to $ith node if ($arr[$i] > $arr[$low]) { $tmp = $arr[$i]; $arr[$i] = $arr[$low]; $arr[$low] = $tmp; } }} // Driver Code$arr = array(64, 25, 12, 22, 11);$len = count($arr);selection_sort($arr, $len);echo \"Sorted array : \\n\"; for ($i = 0; $i < $len; $i++) echo $arr[$i] . \" \"; // This code is contributed// by Deepika Gupta.?>", "e": 32793, "s": 32069, "text": null }, { "code": "<script>// Javascript program for implementation of selection sortfunction swap(arr,xp, yp){ var temp = arr[xp]; arr[xp] = arr[yp]; arr[yp] = temp;} function selectionSort(arr, n){ var i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(arr,min_idx, i); }} function printArray( arr, size){ var i; for (i = 0; i < size; i++) document.write(arr[i] + \" \"); document.write(\" <br>\");} var arr = [64, 25, 12, 22, 11]; var n = 5; selectionSort(arr, n); document.write(\"Sorted array: <br>\"); printArray(arr, n); // This code is contributed by akshitsaxenaa09.</script>", "e": 33692, "s": 32793, "text": null }, { "code": null, "e": 33723, "s": 33692, "text": "Sorted array: \n11 12 22 25 64 " }, { "code": null, "e": 33818, "s": 33723, "text": "Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested loops:" }, { "code": null, "e": 33875, "s": 33818, "text": "One loop to select an element of Array one by one = O(N)" }, { "code": null, "e": 33950, "s": 33875, "text": "Another loop to compare that element with every other Array element = O(N)" }, { "code": null, "e": 34008, "s": 33950, "text": "Therefore overall complexity = O(N)*O(N) = O(N*N) = O(N2)" }, { "code": null, "e": 34257, "s": 34008, "text": "Auxiliary Space: O(1) as the only extra memory used is for temporary variable while swapping two values in Array. The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. " }, { "code": null, "e": 34388, "s": 34257, "text": "Stability : The default implementation is not stable. However it can be made stable. Please see stable selection sort for details." }, { "code": null, "e": 34427, "s": 34388, "text": "Yes, it does not require extra space. " }, { "code": null, "e": 35240, "s": 34427, "text": "YouTubeGeeksforGeeks507K subscribersSelection Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xWBP4lzkoyM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35354, "s": 35240, "text": "Snapshots: Quiz on Selection SortOther Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Coding practice for sorting" }, { "code": null, "e": 35479, "s": 35354, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 35493, "s": 35479, "text": "DeepikaPathak" }, { "code": null, "e": 35505, "s": 35493, "text": "RishiAdvani" }, { "code": null, "e": 35519, "s": 35505, "text": "rathbhupendra" }, { "code": null, "e": 35531, "s": 35519, "text": "navyab4u247" }, { "code": null, "e": 35547, "s": 35531, "text": "akshitsaxenaa09" }, { "code": null, "e": 35563, "s": 35547, "text": "amartyaghoshgfg" }, { "code": null, "e": 35577, "s": 35563, "text": "kashishkumar2" }, { "code": null, "e": 35585, "s": 35577, "text": "Medlife" }, { "code": null, "e": 35593, "s": 35585, "text": "Sorting" }, { "code": null, "e": 35601, "s": 35593, "text": "Medlife" }, { "code": null, "e": 35609, "s": 35601, "text": "Sorting" }, { "code": null, "e": 35707, "s": 35609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35718, "s": 35707, "text": "Radix Sort" }, { "code": null, "e": 35742, "s": 35718, "text": "Merge two sorted arrays" }, { "code": null, "e": 35773, "s": 35742, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35829, "s": 35773, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 35860, "s": 35829, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 35904, "s": 35860, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 35921, "s": 35904, "text": "sort() in Python" }, { "code": null, "e": 35933, "s": 35921, "text": "Bucket Sort" }, { "code": null, "e": 35961, "s": 35933, "text": "Merge Sort for Linked Lists" } ]
AngularJS | angular.isNumber() Function - GeeksforGeeks
12 Apr, 2019 The angular.isNumber() function in AngularJS is used to determine the parameter inside isNumber function is a number or not. It returns true if the reference is a number otherwise returns false. Syntax: angular.isNumber( value ) Return Value: It returns true if the passed value is a number else false. Example: This example uses angular.isNumber() function to determine the given input is number or not. <!DOCTYPE html><html> <head> <title>angular.isNumber()</title> <script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.isNumber()</h2> <div ng-controller="geek"> <b>Input1: </b> <span><code> 123 </code></span> <br> <b>IsNumber: </b>{{isNumber1}}<br /><br><br> <b>Input2: </b> <code> "geeksforgeeks" </code> <br> <b>IsNumber:</b> {{isNumber2}} </div> <!-- Script to uses angular.isNumber() Function --> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { var obj1 = 123; var obj2 = "geeksforgeeks"; $scope.isNumber1 = angular.isNumber(obj1); $scope.isNumber2 = angular.isNumber(obj2); }]); </script> </body></html> Output: AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular PrimeNG Dropdown Component Angular | keyup event Auth Guards in Angular 9/10/11 How to Display Spinner on the Screen till the data from the API loads using Angular 8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 29516, "s": 29488, "text": "\n12 Apr, 2019" }, { "code": null, "e": 29711, "s": 29516, "text": "The angular.isNumber() function in AngularJS is used to determine the parameter inside isNumber function is a number or not. It returns true if the reference is a number otherwise returns false." }, { "code": null, "e": 29719, "s": 29711, "text": "Syntax:" }, { "code": null, "e": 29745, "s": 29719, "text": "angular.isNumber( value )" }, { "code": null, "e": 29819, "s": 29745, "text": "Return Value: It returns true if the passed value is a number else false." }, { "code": null, "e": 29921, "s": 29819, "text": "Example: This example uses angular.isNumber() function to determine the given input is number or not." }, { "code": "<!DOCTYPE html><html> <head> <title>angular.isNumber()</title> <script src= \"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.isNumber()</h2> <div ng-controller=\"geek\"> <b>Input1: </b> <span><code> 123 </code></span> <br> <b>IsNumber: </b>{{isNumber1}}<br /><br><br> <b>Input2: </b> <code> \"geeksforgeeks\" </code> <br> <b>IsNumber:</b> {{isNumber2}} </div> <!-- Script to uses angular.isNumber() Function --> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { var obj1 = 123; var obj2 = \"geeksforgeeks\"; $scope.isNumber1 = angular.isNumber(obj1); $scope.isNumber2 = angular.isNumber(obj2); }]); </script> </body></html> ", "e": 31126, "s": 29921, "text": null }, { "code": null, "e": 31134, "s": 31126, "text": "Output:" }, { "code": null, "e": 31144, "s": 31134, "text": "AngularJS" }, { "code": null, "e": 31161, "s": 31144, "text": "Web Technologies" }, { "code": null, "e": 31259, "s": 31161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31279, "s": 31259, "text": "Angular File Upload" }, { "code": null, "e": 31314, "s": 31279, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31336, "s": 31314, "text": "Angular | keyup event" }, { "code": null, "e": 31367, "s": 31336, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31455, "s": 31367, "text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?" }, { "code": null, "e": 31495, "s": 31455, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31528, "s": 31495, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31573, "s": 31528, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31616, "s": 31573, "text": "How to fetch data from an API in ReactJS ?" } ]
Java.io.PushbackInputStream class in Java - GeeksforGeeks
14 Mar, 2022 Pushback is used on an input stream to allow a byte to be read and then returned (i.e, “pushed back”) to the stream. The PushbackInputStream class implements this idea. It provides a mechanism “peek” at what is coming from an input stream without disrupting it. It extends FilterInputStream.Fields: protected byte[] buf:This is the pushback buffer. protected int pos – This is the position within the pushback buffer from which the next byte will be read. protected InputStream in – This is the input stream to be filtered. Constructors: PushbackInputStream(InputStream in): This creates a stream object that allows one byte to be returned to the input stream. PushbackInputStream(InputStream in, int numBytes): This creates a stream that has a pushback buffer that is numBytes long. This allows multiple bytes to be returned to the input stream. Methods: int available(): Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block but may read or skip fewer bytes. Syntax: public int available() Returns: the number of bytes that can be read (or skipped over) from the input stream without blocking. Exception: IOException - if this input stream has been closed by invoking its close() method, or an I/O error occurs. void close(): Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), unread(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect. Syntax: public void close() Returns: NA Exception: IOException - if an I/O error occurs. boolean markSupported(): Tests if this input stream supports the mark and reset methods, which it does not. Syntax: public boolean markSupported() Returns: false, since this class does not support the mark and reset methods. Exception: NA Java // Java code illustrating available(), close()// and markSupported() methods import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws IOException { PrintWriter pw = new PrintWriter(System.out, true); String str = "Hey geeks "; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); // checking no. of bytes available pw.println("available bytes: " + push.available()); // checking if mark is supported pw.println("mark supported? :" + push.markSupported()); pw.close(); }} Output: available bytes: 10 mark supported? :false int read(): Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. Syntax: public int read() Returns: the next byte of data, or -1 if the end of the stream has been reached. Exception: IOException - if this input stream has been closed by invoking its close() method, or an I/O error occurs. int read(byte[] b, int off, int len): Reads up to len bytes of data from this input stream into an array of bytes. This method first reads any pushed-back bytes; after that, if fewer than len bytes have been read then it reads from the underlying input stream. If len is not zero, the method blocks until at least 1 byte of input is available; otherwise, no bytes are read and 0 is returned. Syntax: public int read(byte[] b, int off, int len). Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. Exception: NullPointerException - If b is null. IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than b.length - off IOException - if this input stream has been closed by invoking its close() method, or an I/O error occurs. Java // Java code illustrating read() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws IOException { PrintWriter pw = new PrintWriter(System.out, true); String str = "GeeksforGeeks a computer science portal "; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); push.read(b, 0, 13); for(int i=0; i<13; i++) { pw.print((char)b[i]); } pw.println(); pw.close(); }} Output: GeeksforGeeks a computer science portal GeeksforGeeks void mark(int readlimit): Marks the current position in this input stream. The mark method of PushbackInputStream does nothing. Syntax: public void mark(int readlimit) Returns: NA Exception: NA void reset(): Repositions this stream to the position at the time the mark method was last called on this input stream. The method reset for class PushbackInputStream does nothing except throw an IOException. Syntax: public void reset() Returns: NA Exception: IOException - if this method is invoked. Java // Java code illustrating mark() and reset() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = "GeeksforGeeks a computer science portal "; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); // marking the position push.mark(5); // resetting is not supported throw exception push.reset(); pw.close(); }} Output: GeeksforGeeks a computer science portal Exception in thread "main" java.io.IOException: mark/reset not supported at java.io.PushbackInputStream.reset(PushbackInputStream.java:364) at PushbackInputStreamDemo.main(PushbackInputStreamDemo.java:29) void unread(byte[] b): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. Syntax: public void unread(byte[] b) returns: NA Exception: IOException - If there is not enough room in the pushback buffer for the specified number of bytes, or this input stream has been closed by invoking its close() method. void unread(byte[] b,int off,int len): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. Syntax: public void unread(byte[] b,int off,int len) Returns: NA Exception: IOException - If there is not enough room in the pushback buffer for the specified number of bytes, or this input stream has been closed by invoking its close() method. Java // Java code illustrating unread() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = "GeeksforGeeks a computer science portal "; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); // unread method push.unread(b); push.unread(b, 0, 6); while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); pw.close(); }} Output: GeeksforGeeks a computer science portal orGeeks a computer science portal void unread(int b): Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b. Syntax: public void unread(int b) Returns: NA Exception: IOException - If there is not enough room in the pushback buffer for the byte, or this input stream has been closed by invoking its close() method. Java // java code illustrating unread() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = "GeeksforGeeks a computer science portal "; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); // unread method push.unread('A'); b[1] = (byte)push.read(); pw.println((char)b[1]); }} Output: A This article is contributed by Abhishek Verma. 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. adnanirshad158 simmytarika5 Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Overriding in Java Stack Class in Java Collections in Java Set in Java
[ { "code": null, "e": 24204, "s": 24176, "text": "\n14 Mar, 2022" }, { "code": null, "e": 24504, "s": 24204, "text": "Pushback is used on an input stream to allow a byte to be read and then returned (i.e, “pushed back”) to the stream. The PushbackInputStream class implements this idea. It provides a mechanism “peek” at what is coming from an input stream without disrupting it. It extends FilterInputStream.Fields: " }, { "code": null, "e": 24556, "s": 24504, "text": "protected byte[] buf:This is the pushback buffer. " }, { "code": null, "e": 24665, "s": 24556, "text": "protected int pos – This is the position within the pushback buffer from which the next byte will be read. " }, { "code": null, "e": 24734, "s": 24665, "text": "protected InputStream in – This is the input stream to be filtered. " }, { "code": null, "e": 24749, "s": 24734, "text": "Constructors: " }, { "code": null, "e": 24874, "s": 24749, "text": "PushbackInputStream(InputStream in): This creates a stream object that allows one byte to be returned to the input stream. " }, { "code": null, "e": 25061, "s": 24874, "text": "PushbackInputStream(InputStream in, int numBytes): This creates a stream that has a pushback buffer that is numBytes long. This allows multiple bytes to be returned to the input stream. " }, { "code": null, "e": 25071, "s": 25061, "text": "Methods: " }, { "code": null, "e": 25420, "s": 25071, "text": "int available(): Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block but may read or skip fewer bytes. " }, { "code": null, "e": 25675, "s": 25420, "text": "Syntax: public int available()\nReturns: the number of bytes that can be read\n (or skipped over) from the input stream without blocking.\nException: IOException - if this input stream has \nbeen closed by invoking its close() method, or an I/O error occurs." }, { "code": null, "e": 25957, "s": 25675, "text": "void close(): Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), unread(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect. " }, { "code": null, "e": 26046, "s": 25957, "text": "Syntax: public void close()\nReturns: NA\nException: IOException - if an I/O error occurs." }, { "code": null, "e": 26155, "s": 26046, "text": "boolean markSupported(): Tests if this input stream supports the mark and reset methods, which it does not. " }, { "code": null, "e": 26286, "s": 26155, "text": "Syntax: public boolean markSupported()\nReturns: false, since this class does not support the mark and reset methods.\nException: NA" }, { "code": null, "e": 26291, "s": 26286, "text": "Java" }, { "code": "// Java code illustrating available(), close()// and markSupported() methods import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws IOException { PrintWriter pw = new PrintWriter(System.out, true); String str = \"Hey geeks \"; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); // checking no. of bytes available pw.println(\"available bytes: \" + push.available()); // checking if mark is supported pw.println(\"mark supported? :\" + push.markSupported()); pw.close(); }}", "e": 27110, "s": 26291, "text": null }, { "code": null, "e": 27119, "s": 27110, "text": "Output: " }, { "code": null, "e": 27162, "s": 27119, "text": "available bytes: 10\nmark supported? :false" }, { "code": null, "e": 27497, "s": 27162, "text": "int read(): Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. " }, { "code": null, "e": 27724, "s": 27497, "text": "Syntax: public int read()\nReturns: the next byte of data, or -1 if \nthe end of the stream has been reached.\nException: IOException - if this input stream \nhas been closed by invoking its close() method, or an I/O error occurs." }, { "code": null, "e": 28117, "s": 27724, "text": "int read(byte[] b, int off, int len): Reads up to len bytes of data from this input stream into an array of bytes. This method first reads any pushed-back bytes; after that, if fewer than len bytes have been read then it reads from the underlying input stream. If len is not zero, the method blocks until at least 1 byte of input is available; otherwise, no bytes are read and 0 is returned. " }, { "code": null, "e": 28569, "s": 28117, "text": "Syntax: public int read(byte[] b, int off, int len).\nReturns: the total number of bytes read into \nthe buffer, or -1 if there is no more data because the end of \nthe stream has been reached.\nException: NullPointerException - If b is null.\nIndexOutOfBoundsException - If off is negative, len is negative, or \nlen is greater than b.length - off\nIOException - if this input stream has been closed by invoking its \nclose() method, or an I/O error occurs." }, { "code": null, "e": 28574, "s": 28569, "text": "Java" }, { "code": "// Java code illustrating read() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws IOException { PrintWriter pw = new PrintWriter(System.out, true); String str = \"GeeksforGeeks a computer science portal \"; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); push.read(b, 0, 13); for(int i=0; i<13; i++) { pw.print((char)b[i]); } pw.println(); pw.close(); }}", "e": 29412, "s": 28574, "text": null }, { "code": null, "e": 29421, "s": 29412, "text": "Output: " }, { "code": null, "e": 29476, "s": 29421, "text": "GeeksforGeeks a computer science portal \nGeeksforGeeks" }, { "code": null, "e": 29605, "s": 29476, "text": "void mark(int readlimit): Marks the current position in this input stream. The mark method of PushbackInputStream does nothing. " }, { "code": null, "e": 29671, "s": 29605, "text": "Syntax: public void mark(int readlimit)\nReturns: NA\nException: NA" }, { "code": null, "e": 29881, "s": 29671, "text": "void reset(): Repositions this stream to the position at the time the mark method was last called on this input stream. The method reset for class PushbackInputStream does nothing except throw an IOException. " }, { "code": null, "e": 29973, "s": 29881, "text": "Syntax: public void reset()\nReturns: NA\nException: IOException - if this method is invoked." }, { "code": null, "e": 29978, "s": 29973, "text": "Java" }, { "code": "// Java code illustrating mark() and reset() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = \"GeeksforGeeks a computer science portal \"; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); // marking the position push.mark(5); // resetting is not supported throw exception push.reset(); pw.close(); }}", "e": 30848, "s": 29978, "text": null }, { "code": null, "e": 30857, "s": 30848, "text": "Output: " }, { "code": null, "e": 31111, "s": 30857, "text": "GeeksforGeeks a computer science portal \nException in thread \"main\" java.io.IOException: mark/reset not supported\n at java.io.PushbackInputStream.reset(PushbackInputStream.java:364)\n at PushbackInputStreamDemo.main(PushbackInputStreamDemo.java:29)" }, { "code": null, "e": 31354, "s": 31111, "text": "void unread(byte[] b): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. " }, { "code": null, "e": 31585, "s": 31354, "text": "Syntax: public void unread(byte[] b)\nreturns: NA\nException: IOException - If there is not enough room in \nthe pushback buffer for the specified number of bytes, or this input \nstream has been closed by invoking its close() method." }, { "code": null, "e": 31844, "s": 31585, "text": "void unread(byte[] b,int off,int len): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. " }, { "code": null, "e": 32091, "s": 31844, "text": "Syntax: public void unread(byte[] b,int off,int len)\nReturns: NA\nException: IOException - If there is not enough room \nin the pushback buffer for the specified number of bytes, or this input \nstream has been closed by invoking its close() method." }, { "code": null, "e": 32096, "s": 32091, "text": "Java" }, { "code": "// Java code illustrating unread() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = \"GeeksforGeeks a computer science portal \"; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); int c; while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); // unread method push.unread(b); push.unread(b, 0, 6); while((c=push.read())!=-1) { pw.print((char)c); } pw.println(); pw.close(); }}", "e": 32982, "s": 32096, "text": null }, { "code": null, "e": 32991, "s": 32982, "text": "Output: " }, { "code": null, "e": 33065, "s": 32991, "text": "GeeksforGeeks a computer science portal\norGeeks a computer science portal" }, { "code": null, "e": 33237, "s": 33065, "text": "void unread(int b): Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b. " }, { "code": null, "e": 33444, "s": 33237, "text": "Syntax: public void unread(int b)\nReturns: NA\nException: IOException - If there is not enough \nroom in the pushback buffer for the byte, or this input stream \nhas been closed by invoking its close() method." }, { "code": null, "e": 33449, "s": 33444, "text": "Java" }, { "code": "// java code illustrating unread() method import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.PushbackInputStream; public class PushbackInputStreamDemo{ public static void main(String arg[]) throws Exception { PrintWriter pw = new PrintWriter(System.out, true); String str = \"GeeksforGeeks a computer science portal \"; byte b[] = str.getBytes(); ByteArrayInputStream bout = new ByteArrayInputStream(b); PushbackInputStream push = new PushbackInputStream(bout); // unread method push.unread('A'); b[1] = (byte)push.read(); pw.println((char)b[1]); }}", "e": 34132, "s": 33449, "text": null }, { "code": null, "e": 34141, "s": 34132, "text": "Output: " }, { "code": null, "e": 34143, "s": 34141, "text": "A" }, { "code": null, "e": 34565, "s": 34143, "text": "This article is contributed by Abhishek Verma. 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." }, { "code": null, "e": 34580, "s": 34565, "text": "adnanirshad158" }, { "code": null, "e": 34593, "s": 34580, "text": "simmytarika5" }, { "code": null, "e": 34602, "s": 34593, "text": "Java-I/O" }, { "code": null, "e": 34607, "s": 34602, "text": "Java" }, { "code": null, "e": 34612, "s": 34607, "text": "Java" }, { "code": null, "e": 34710, "s": 34612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34719, "s": 34710, "text": "Comments" }, { "code": null, "e": 34732, "s": 34719, "text": "Old Comments" }, { "code": null, "e": 34762, "s": 34732, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34794, "s": 34762, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34845, "s": 34794, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34863, "s": 34845, "text": "ArrayList in Java" }, { "code": null, "e": 34894, "s": 34863, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34926, "s": 34894, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34945, "s": 34926, "text": "Overriding in Java" }, { "code": null, "e": 34965, "s": 34945, "text": "Stack Class in Java" }, { "code": null, "e": 34985, "s": 34965, "text": "Collections in Java" } ]
C# | Adding an element into the Hashtable - GeeksforGeeks
01 Feb, 2019 The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable. Syntax: public virtual void Add(object key, object value); Parameters: key: It is the specified key of the element to add of type System.Object. value: It is the specified value of the element to add of type System.Object. The value can be null. Exceptions: ArgumentNullException : If the key is null. ArgumentException : If an element with the same key already exists in the Hashtable. NotSupportedException : Either Hashtable is read-only or Hashtable has a fixed size. Below given are some examples to understand the implementation in a better way : Example 1 : // C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("g", "geeks"); myTable.Add("c", "c++"); myTable.Add("d", "data structures"); myTable.Add("q", "quiz"); // Get a collection of the keys. ICollection c = myTable.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + myTable[str]); }} d: data structures c: c++ q: quiz g: geeks Example 2: // C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("4", "Even"); myTable.Add("9", "Odd"); myTable.Add("5", "Odd and Prime"); myTable.Add("2", "Even and Prime"); // Get a collection of the keys. ICollection c = myTable.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + ": " + myTable[str]); }} 5: Odd and Prime 9: Odd 2: Even and Prime 4: Even Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.add?view=netframework-4.7.2 CSharp-Collections-Hashtable CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 24333, "s": 24305, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24626, "s": 24333, "text": "The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable." }, { "code": null, "e": 24634, "s": 24626, "text": "Syntax:" }, { "code": null, "e": 24686, "s": 24634, "text": "public virtual void Add(object key, object value);\n" }, { "code": null, "e": 24698, "s": 24686, "text": "Parameters:" }, { "code": null, "e": 24772, "s": 24698, "text": "key: It is the specified key of the element to add of type System.Object." }, { "code": null, "e": 24873, "s": 24772, "text": "value: It is the specified value of the element to add of type System.Object. The value can be null." }, { "code": null, "e": 24885, "s": 24873, "text": "Exceptions:" }, { "code": null, "e": 24929, "s": 24885, "text": "ArgumentNullException : If the key is null." }, { "code": null, "e": 25014, "s": 24929, "text": "ArgumentException : If an element with the same key already exists in the Hashtable." }, { "code": null, "e": 25099, "s": 25014, "text": "NotSupportedException : Either Hashtable is read-only or Hashtable has a fixed size." }, { "code": null, "e": 25180, "s": 25099, "text": "Below given are some examples to understand the implementation in a better way :" }, { "code": null, "e": 25192, "s": 25180, "text": "Example 1 :" }, { "code": "// C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"g\", \"geeks\"); myTable.Add(\"c\", \"c++\"); myTable.Add(\"d\", \"data structures\"); myTable.Add(\"q\", \"quiz\"); // Get a collection of the keys. ICollection c = myTable.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + myTable[str]); }}", "e": 25855, "s": 25192, "text": null }, { "code": null, "e": 25899, "s": 25855, "text": "d: data structures\nc: c++\nq: quiz\ng: geeks\n" }, { "code": null, "e": 25910, "s": 25899, "text": "Example 2:" }, { "code": "// C# code for adding an element with the// specified key and value into the Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"4\", \"Even\"); myTable.Add(\"9\", \"Odd\"); myTable.Add(\"5\", \"Odd and Prime\"); myTable.Add(\"2\", \"Even and Prime\"); // Get a collection of the keys. ICollection c = myTable.Keys; // Displaying the contents foreach(string str in c) Console.WriteLine(str + \": \" + myTable[str]); }}", "e": 26580, "s": 25910, "text": null }, { "code": null, "e": 26631, "s": 26580, "text": "5: Odd and Prime\n9: Odd\n2: Even and Prime\n4: Even\n" }, { "code": null, "e": 26642, "s": 26631, "text": "Reference:" }, { "code": null, "e": 26743, "s": 26642, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.add?view=netframework-4.7.2" }, { "code": null, "e": 26772, "s": 26743, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 26801, "s": 26772, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26815, "s": 26801, "text": "CSharp-method" }, { "code": null, "e": 26818, "s": 26815, "text": "C#" }, { "code": null, "e": 26916, "s": 26818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26925, "s": 26916, "text": "Comments" }, { "code": null, "e": 26938, "s": 26925, "text": "Old Comments" }, { "code": null, "e": 26961, "s": 26938, "text": "C# | Method Overriding" }, { "code": null, "e": 27007, "s": 26961, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27022, "s": 27007, "text": "C# | Delegates" }, { "code": null, "e": 27062, "s": 27022, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27093, "s": 27062, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27111, "s": 27093, "text": "C# | Constructors" }, { "code": null, "e": 27134, "s": 27111, "text": "Extension Method in C#" }, { "code": null, "e": 27156, "s": 27134, "text": "C# | Class and Object" }, { "code": null, "e": 27178, "s": 27156, "text": "C# | Abstract Classes" } ]
File.ReadAllText(String, Encoding) Method in C# with Examples - GeeksforGeeks
09 Mar, 2021 File.ReadAllText(String, Encoding) is an inbuilt File class method that is used to open a text file then reads all the text in the file with the specified encoding and then closes the file.Syntax: public static string ReadAllText (string path, System.Text.Encoding encoding); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file to open for reading. encoding: This is applied to the contents of the file. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission. FileNotFoundException: The file specified in the path was not found. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. Return Value: Returns a string containing all the text in the file.Below are the programs to illustrate the File.ReadAllText(String, Encoding) method.Program 1: Initially, a file file.txt is created with some contents shown below- C# // C# program to illustrate the usage// of File.ReadAllText(String, Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Calling the ReadAllText(String, Encoding) // function string readText = File.ReadAllText(path, Encoding.UTF8); // Printing the file contents Console.WriteLine(readText); }} Output: GFG gfg Geeks GeeksforGeeks geeksforgeeks Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. C# // C# program to illustrate the usage// of File.ReadAllText(String, Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Adding below contents to the file string[] createText = { "GFG", "is a", "CS", "portal" }; File.WriteAllLines(path, createText, Encoding.UTF8); // Calling the ReadAllText() function string readText = File.ReadAllText(path, Encoding.UTF8); // Printing the file contents Console.WriteLine(readText); }} Output: GFG is a CS portal arorakashish0911 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n09 Mar, 2021" }, { "code": null, "e": 24110, "s": 23911, "text": "File.ReadAllText(String, Encoding) is an inbuilt File class method that is used to open a text file then reads all the text in the file with the specified encoding and then closes the file.Syntax: " }, { "code": null, "e": 24189, "s": 24110, "text": "public static string ReadAllText (string path, System.Text.Encoding encoding);" }, { "code": null, "e": 24263, "s": 24189, "text": "Parameter: This function accepts a parameter which is illustrated below: " }, { "code": null, "e": 24317, "s": 24263, "text": "path: This is the specified file to open for reading." }, { "code": null, "e": 24372, "s": 24317, "text": "encoding: This is applied to the contents of the file." }, { "code": null, "e": 24385, "s": 24372, "text": "Exceptions: " }, { "code": null, "e": 24531, "s": 24385, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 24572, "s": 24531, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 24675, "s": 24572, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 24734, "s": 24675, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 24793, "s": 24734, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 25015, "s": 24793, "text": "UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission." }, { "code": null, "e": 25084, "s": 25015, "text": "FileNotFoundException: The file specified in the path was not found." }, { "code": null, "e": 25141, "s": 25084, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 25210, "s": 25141, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 25442, "s": 25210, "text": "Return Value: Returns a string containing all the text in the file.Below are the programs to illustrate the File.ReadAllText(String, Encoding) method.Program 1: Initially, a file file.txt is created with some contents shown below- " }, { "code": null, "e": 25447, "s": 25444, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllText(String, Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Calling the ReadAllText(String, Encoding) // function string readText = File.ReadAllText(path, Encoding.UTF8); // Printing the file contents Console.WriteLine(readText); }}", "e": 25963, "s": 25447, "text": null }, { "code": null, "e": 25973, "s": 25963, "text": "Output: " }, { "code": null, "e": 26015, "s": 25973, "text": "GFG\ngfg\nGeeks\nGeeksforGeeks\ngeeksforgeeks" }, { "code": null, "e": 26130, "s": 26015, "text": "Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. " }, { "code": null, "e": 26133, "s": 26130, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllText(String, Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Adding below contents to the file string[] createText = { \"GFG\", \"is a\", \"CS\", \"portal\" }; File.WriteAllLines(path, createText, Encoding.UTF8); // Calling the ReadAllText() function string readText = File.ReadAllText(path, Encoding.UTF8); // Printing the file contents Console.WriteLine(readText); }}", "e": 26793, "s": 26133, "text": null }, { "code": null, "e": 26803, "s": 26793, "text": "Output: " }, { "code": null, "e": 26822, "s": 26803, "text": "GFG\nis a\nCS\nportal" }, { "code": null, "e": 26839, "s": 26822, "text": "arorakashish0911" }, { "code": null, "e": 26860, "s": 26839, "text": "CSharp-File-Handling" }, { "code": null, "e": 26863, "s": 26860, "text": "C#" }, { "code": null, "e": 26961, "s": 26863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26970, "s": 26961, "text": "Comments" }, { "code": null, "e": 26983, "s": 26970, "text": "Old Comments" }, { "code": null, "e": 27023, "s": 26983, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27046, "s": 27023, "text": "Extension Method in C#" }, { "code": null, "e": 27074, "s": 27046, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27091, "s": 27074, "text": "C# | Inheritance" }, { "code": null, "e": 27113, "s": 27091, "text": "Partial Classes in C#" }, { "code": null, "e": 27153, "s": 27113, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27186, "s": 27153, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27229, "s": 27186, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27245, "s": 27229, "text": "C# | List Class" } ]
atexit() function in C/C++
The function atexit() is used to call the function after the normal exit of program. The program is called without any parameters. The function atexit() is called after exit(). The termination function can be called anywhere in the program. This function is declared in “stdlib.h” header file. Here is the syntax of atexit() in C language, int atexit(void (*function_name)(void)) Here, function_name − The function is to be called at the time of termination of program. Here is an example of atexit() in C language, Live Demo #include <stdio.h> #include <stdlib.h> void func1 (void) { printf("\nExit of function 1"); } void func2 (void) { printf("\nExit of function 2"); } int main () { atexit (func1); printf("\nStarting of main()"); atexit (func2); printf("\nEnding of main()"); return 0; } Starting of main() Ending of main() Exit of function 2 Exit of function 1 In the above program, two functions func1 and func2 are defined before main() function. By using atexit(), defined functions are called. The main() function calls the functions before the exit of main() function. We called the two functions as shown below. atexit (func1); printf("\nStarting of main()"); atexit (func2); printf("\nEnding of main()");
[ { "code": null, "e": 1356, "s": 1062, "text": "The function atexit() is used to call the function after the normal exit of program. The program is called without any parameters. The function atexit() is called after exit(). The termination function can be called anywhere in the program. This function is declared in “stdlib.h” header file." }, { "code": null, "e": 1402, "s": 1356, "text": "Here is the syntax of atexit() in C language," }, { "code": null, "e": 1442, "s": 1402, "text": "int atexit(void (*function_name)(void))" }, { "code": null, "e": 1448, "s": 1442, "text": "Here," }, { "code": null, "e": 1532, "s": 1448, "text": "function_name − The function is to be called at the time of termination of program." }, { "code": null, "e": 1578, "s": 1532, "text": "Here is an example of atexit() in C language," }, { "code": null, "e": 1589, "s": 1578, "text": " Live Demo" }, { "code": null, "e": 1877, "s": 1589, "text": "#include <stdio.h>\n#include <stdlib.h>\nvoid func1 (void) {\n printf(\"\\nExit of function 1\");\n}\nvoid func2 (void) {\n printf(\"\\nExit of function 2\");\n}\nint main () {\n atexit (func1);\n printf(\"\\nStarting of main()\");\n atexit (func2);\n printf(\"\\nEnding of main()\");\n return 0;\n}" }, { "code": null, "e": 1951, "s": 1877, "text": "Starting of main()\nEnding of main()\nExit of function 2\nExit of function 1" }, { "code": null, "e": 2208, "s": 1951, "text": "In the above program, two functions func1 and func2 are defined before main() function. By using atexit(), defined functions are called. The main() function calls the functions before the exit of main() function. We called the two functions as shown below." }, { "code": null, "e": 2302, "s": 2208, "text": "atexit (func1);\nprintf(\"\\nStarting of main()\");\natexit (func2);\nprintf(\"\\nEnding of main()\");" } ]
\vartheta - Tex Command
\vartheta - Used to create vartheta symbol. { \vartheta} \vartheta command draws vartheta symbol. \vartheta θ \vartheta θ \vartheta 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8030, "s": 7986, "text": "\\vartheta - Used to create vartheta symbol." }, { "code": null, "e": 8043, "s": 8030, "text": "{ \\vartheta}" }, { "code": null, "e": 8084, "s": 8043, "text": "\\vartheta command draws vartheta symbol." }, { "code": null, "e": 8101, "s": 8084, "text": "\n\\vartheta\n\nθ\n\n\n" }, { "code": null, "e": 8116, "s": 8101, "text": "\\vartheta\n\nθ\n\n" }, { "code": null, "e": 8126, "s": 8116, "text": "\\vartheta" }, { "code": null, "e": 8158, "s": 8126, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8171, "s": 8158, "text": " Ashraf Said" }, { "code": null, "e": 8204, "s": 8171, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8217, "s": 8204, "text": " Ashraf Said" }, { "code": null, "e": 8249, "s": 8217, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8285, "s": 8249, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8320, "s": 8285, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8337, "s": 8320, "text": " Mohammad Nauman" }, { "code": null, "e": 8370, "s": 8337, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8384, "s": 8370, "text": " Daniel Stern" }, { "code": null, "e": 8416, "s": 8384, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8431, "s": 8416, "text": " Nishant Kumar" }, { "code": null, "e": 8438, "s": 8431, "text": " Print" }, { "code": null, "e": 8449, "s": 8438, "text": " Add Notes" } ]
Xstream - Quick Guide
XStream is a simple Java-based library to serialize Java objects to XML and vice versa. Easy to use − XStream API provides a high-level facade to simplify common use cases. Easy to use − XStream API provides a high-level facade to simplify common use cases. No need to create mapping − XStream API provides default mapping for most of the objects to be serialized. No need to create mapping − XStream API provides default mapping for most of the objects to be serialized. Performance − XStream is fast and is of low memory footprint, which is suitable for large object graphs or systems. Performance − XStream is fast and is of low memory footprint, which is suitable for large object graphs or systems. Clean XML − XStream produces clean and compact XML output that is easy to read. Clean XML − XStream produces clean and compact XML output that is easy to read. Object modification not required − XStream serializes internal fields like private and final fields, and supports non-public and inner classes. Default constructor is not a mandatory requirement. Object modification not required − XStream serializes internal fields like private and final fields, and supports non-public and inner classes. Default constructor is not a mandatory requirement. Full object graph support − XStream allows to maintain duplicate references encountered in the object-model and also supports circular references. Full object graph support − XStream allows to maintain duplicate references encountered in the object-model and also supports circular references. Customizable conversion strategies − Custom strategies can be registered in order to allow customization of a particular type to be represented as XML. Customizable conversion strategies − Custom strategies can be registered in order to allow customization of a particular type to be represented as XML. Security framework − XStream provides a fair control over unmarshalled types to prevent security issues with manipulated input. Security framework − XStream provides a fair control over unmarshalled types to prevent security issues with manipulated input. Error messages − When an exception occurs due to malformed XML, it provides detailed diagnostics to fix the problem. Error messages − When an exception occurs due to malformed XML, it provides detailed diagnostics to fix the problem. Alternative output format − XStream supports other output formats like JSON and morphing. Alternative output format − XStream supports other output formats like JSON and morphing. Transport − XML is a text representation of object and can be used to transport objects over the wire independent of the serialization / deserialization techniques used. Transport − XML is a text representation of object and can be used to transport objects over the wire independent of the serialization / deserialization techniques used. Persistence − Objects can be persisted as XML in databases and can be marshalled/unmarshalled as and when required. Persistence − Objects can be persisted as XML in databases and can be marshalled/unmarshalled as and when required. Configuration − XML is self-explanatory and is heavily used to define configurations. Objects can also be used for configuration purpose after converting them to XML representation. Configuration − XML is self-explanatory and is heavily used to define configurations. Objects can also be used for configuration purpose after converting them to XML representation. Unit Tests − XStream API is JUnit compatible and can be used to enhance unit testing of application modules. Unit Tests − XStream API is JUnit compatible and can be used to enhance unit testing of application modules. In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java. If you want to set up your environment for Java programming language, then this section explains how to download and set up Java on your machine. Please follow the steps given below to set up you Java environment. Java SE can be downloaded for free from the link − Download Java. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to correct installation directories − Assuming you have installed Java in c:\Program Files\java\jdk directory − Right-click on 'My Computer' and select 'Properties'. Right-click on 'My Computer' and select 'Properties'. Click the 'Environment variables' button under the 'Advanced' tab. Click the 'Environment variables' button under the 'Advanced' tab. Alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Assuming you have installed Java in c:\Program Files\java\jdk directory − Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH = %PATH%;C:\Program Files\java\jdk\bin' Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH = %PATH%;C:\Program Files\java\jdk\bin' Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your '.bashrc: export PATH=/path/to/java:$PATH' To write Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following − Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad. Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad. Netbeans − It is a Java IDE that is free and can be downloaded from https://www.netbeans.org/index.html. Netbeans − It is a Java IDE that is free and can be downloaded from https://www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Download the latest version of XStream jar file from XStream download page. At the time of writing this tutorial, we have downloaded xstream-1.4.18.jar and copied it into C:\>XStream folder. Set the XStream_HOME environment variable to point to the base directory location where xstream jar is stored on your machine. The following table shows how to set the XStream environment on Windows, Linux, and Mac, assuming we've extracted xstream-1.4.18.jar in the XStream folder. Windows Set the environment variable XStream_HOME to C:\XStream Linux export XStream_HOME=/usr/local/XStream Mac export XStream_HOME=/Library/XStream Set the CLASSPATH environment variable to point to the XStream jar location. The following table shows how to set the CLASSPATH variable on Windows, Linux, and Mac system, assuming we've stored xstream-1.4.18.jar in the XStream folder. Windows Set the environment variable CLASSPATH to %CLASSPATH%;%XStream_HOME%\xstream-1.4.18.jar; Linux export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar; Mac export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar; Before going into the details of the XStream library, let us see an application in action. In this example, we've created Student and Address classes. We will create a student object and then serialize it to an XML String. Then de-serialize the same XML string to obtain the student object back. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE. File: XStreamTester.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); //XML to Object Conversion Student student1 = (Student)xstream.fromXML(xml); System.out.println(student1); } private Student getStudentDetails() { Student student = new Student(); student.setFirstName("Mahesh"); student.setLastName("Parashar"); student.setRollNo(1); student.setClassName("1st"); Address address = new Address(); address.setArea("H.No. 16/3, Preet Vihar."); address.setCity("Delhi"); address.setState("Delhi"); address.setCountry("India"); address.setPincode(110012); student.setAddress(address); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } class Student { private int rollNo; private String firstName; private String lastName; private String className; private Address address; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Student [ "); stringBuilder.append("\nfirstName: "); stringBuilder.append(firstName); stringBuilder.append("\nlastName: "); stringBuilder.append(lastName); stringBuilder.append("\nrollNo: "); stringBuilder.append(rollNo); stringBuilder.append("\nclassName: "); stringBuilder.append(className); stringBuilder.append("\naddress: "); stringBuilder.append(address); stringBuilder.append(" ]"); return stringBuilder.toString(); } } class Address { private String area; private String city; private String state; private String country; private int pincode; public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public int getPincode() { return pincode; } public void setPincode(int pincode) { this.pincode = pincode; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\nAddress [ "); stringBuilder.append("\narea: "); stringBuilder.append(area); stringBuilder.append("\ncity: "); stringBuilder.append(city); stringBuilder.append("\nstate: "); stringBuilder.append(state); stringBuilder.append("\ncountry: "); stringBuilder.append(country); stringBuilder.append("\npincode: "); stringBuilder.append(pincode); stringBuilder.append(" ]"); return stringBuilder.toString(); } } Verify the Result Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE>java XStreamTester Verify the output as follows <?xml version = "1.0" encoding = "UTF-8"?> <Student> <firstName>Mahesh</firstName> <lastName>Parashar</lastName> <rollNo>1</rollNo> <className>1st</className> <address> <area>H.No. 16/3, Preet Vihar.</area> <city>Delhi</city> <state>Delhi</state> <country>India</country> <pincode>110012</pincode> </address> </Student> Student [ firstName: Mahesh lastName: Parashar rollNo: 1 className: 1st address: Address [ area: H.No. 16/3, Preet Vihar. city: Delhi state: Delhi country: India pincode: 110012 ] ] Following are the important steps to be considered here. Create an XStream object by passing it a StaxDriver. StaxDriver uses Stax pull parser (available from java 6) and is a fast xml parser. XStream xstream = new XStream(new StaxDriver()); Use toXML() method to get the XML string representation of the object. //Object to XML Conversion String xml = xstream.toXML(student); Use fromXML() method to get the object from the XML. //XML to Object Conversion Student student1 = (Student)xstream.fromXML(xml); Aliasing is a technique to customize the generated XML or to use a particular formatted XML using XStream. Let’s suppose the following XML format is to be used to serialize/de-serialize the Student object. <student name = "Suresh"> <note> <title>first</title> <description>My first assignment.</description> </note> <note> <title>second</title> <description>My second assignment.</description> </note> </student> Based on the above XML format, let's create model classes. class Student { private String studentName; private List<Note> notes = new ArrayList<Note>(); public Student(String name) { this.studentName = name; } public void addNote(Note note) { notes.add(note); } public String getName() { return studentName; } public List<Note> getNotes() { return notes; } } class Note { private String title; private String description; public Note(String title, String description) { this.title = title; this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } } Let's test the above objects serialization using XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. File: XStreamTester.java package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh"); student.addNote(new Note("first","My first assignment.")); student.addNote(new Note("second","My Second assignment.")); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } class Student { private String studentName; private List<Note> notes = new ArrayList<Note>(); public Student(String name) { this.studentName = name; } public void addNote(Note note) { notes.add(note); } public String getName() { return studentName; } public List<Note> getNotes() { return notes; } } class Note { private String title; private String description; public Note(String title, String description) { this.title = title; this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } } Verify the Result Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − <?xml version = "1.0" encoding = "UTF-8"?> <com.tutorialspoint.xstream.Student> <studentName>Mahesh</studentName> <notes> <com.tutorialspoint.xstream.Note> <title>first</title> <description>My first assignment.</description> </com.tutorialspoint.xstream.Note> <com.tutorialspoint.xstream.Note> <title>second</title> <description>My Second assignment.</description> </com.tutorialspoint.xstream.Note> </notes> </com.tutorialspoint.xstream.Student> In the above result, the Student object name is fully qualified. To replace it as student tag, follow the next section. Class Aliasing Class Aliasing Field Aliasing Field Aliasing Implicit Collections Aliasing Implicit Collections Aliasing Attribute Aliasing Attribute Aliasing Package Aliasing Package Aliasing XStream supports annotations similarly like automatic configuration instead of coding. In the previous chapter, we've seen the following configurations in code. xstream.alias("student", Student.class); xstream.alias("note", Note.class); xstream.useAttributeFor(Student.class, "studentName"); xstream.aliasField("name", Student.class, "studentName"); xstream.addImplicitCollection(Student.class, "notes"); The following code snippet illustrates the use of annotations to do the same work in a much easier way. @XStreamAlias("student") //define class level alias class Student { @XStreamAlias("name") //define field level alias @XStreamAsAttribute //define field as attribute private String studentName; @XStreamImplicit //define list as an implicit collection private List<Note> notes = new ArrayList<Note>(); @XStreamOmitField //omit a field to not to be a part of XML private int type; } Let us test the above annotation using XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; import com.thoughtworks.xstream.annotations.XStreamOmitField; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.processAnnotations(Student.class); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh"); student.addNote(new Note("first","My first assignment.")); student.addNote(new Note("second","My Second assignment.")); student.setType(1); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamAlias("student") class Student { @XStreamAlias("name") @XStreamAsAttribute private String studentName; @XStreamImplicit private List<Note> notes = new ArrayList<Note>(); public Student(String name) { this.studentName = name; } public void addNote(Note note) { notes.add(note); } public String getName() { return studentName; } public List<Note> getNotes() { return notes; } @XStreamOmitField private int type; public int getType() { return type; } public void setType(int type) { this.type = type; } } @XStreamAlias("note") class Note { private String title; private String description; public Note(String title, String description) { this.title = title; this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } } Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − <?xml version = "1.0" encoding = "UTF-8"?> <student name = "Mahesh"> <note> <title>first</title> <description>My first assignment.</description> </note> <note> <title>second</title> <description>My Second assignment.</description> </note> </student> In order to instruct the XStream framework to process annotation, you need to add the following command before serializing xml. xstream.processAnnotations(Student.class); Or xstream.autodetectAnnotations(true); XStream converters are the key components of the XStream library, which are responsible to convert an object to XML and vice versa. XStream provides numerous converters for common types such as primitives, String, File, Collections, arrays, and Dates. Let us use a SingleValueConvertor whose purpose is to convert an object into a single string. We will use SingleValueConvertor to write an object as attribute string. class NameConverter implements SingleValueConverter { public Object fromString(String name) { String[] nameparts = name.split(","); return new Name(nameparts[0], nameparts[1]); } public String toString(Object name) { return ((Name)name).getFirstName() + "," + ((Name)name).getLastName(); } public boolean canConvert(Class type) { return type.equals(Name.class); } } xstream.registerConverter(new NameConverter()); Let us first test the code without converter in XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. File: XStreamTester.java package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh","Parashar"); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamAlias("student") class Student { @XStreamAlias("name") @XStreamAsAttribute private Name studentName; public Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } public Name getName() { return studentName; } } class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } Verify the Result Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − <?xml version = "1.0" encoding = "UTF-8"?> <student> <name> <firstName>Mahesh</firstName> <lastName>Parashar</lastName> </name> </student> Let us now test the code with converter in XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. File: XStreamTester.java package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); xstream.registerConverter(new NameConverter()); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student("Mahesh","Parashar"); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamAlias("student") class Student { @XStreamAlias("name") @XStreamAsAttribute private Name studentName; public Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } public Name getName() { return studentName; } } class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } class NameConverter implements SingleValueConverter { public Object fromString(String name) { String[] nameparts = name.split(","); return new Name(nameparts[0], nameparts[1]); } public String toString(Object name) { return ((Name)name).getFirstName() + "," + ((Name)name).getLastName(); } public boolean canConvert(Class type) { return type.equals(Name.class); } } Verify the Result Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − <?xml version = "1.0" encoding = "UTF-8"?> <student name = "Mahesh,Parashar"/> Custom Converter XStream provides alternative implementations of java.io.ObjectInputStream and java.io.ObjectOutputStream so that streams of objects can be serialized or deserialized from XML. This is particularly useful when large sets of objects are to be processed, keeping one object in memory at a time. ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream( new FileOutputStream("test.txt")); ObjectInputStream objectInputStream = xstream.createObjectInputStream( new FileInputStream("test.txt")); Let us now test the code with object streams in XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. package com.tutorialspoint.xstream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); xstream.autodetectAnnotations(true); Student student1 = new Student("Mahesh","Parashar"); Student student2 = new Student("Suresh","Kalra"); Student student3 = new Student("Ramesh","Kumar"); Student student4 = new Student("Naresh","Sharma"); try { ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream( new FileOutputStream("test.txt")); objectOutputStream.writeObject(student1); objectOutputStream.writeObject(student2); objectOutputStream.writeObject(student3); objectOutputStream.writeObject(student4); objectOutputStream.writeObject("Hello World"); objectOutputStream.close(); ObjectInputStream objectInputStream = xstream.createObjectInputStream( new FileInputStream("test.txt")); Student student5 = (Student)objectInputStream.readObject(); Student student6 = (Student)objectInputStream.readObject(); Student student7 = (Student)objectInputStream.readObject(); Student student8 = (Student)objectInputStream.readObject(); String text = (String)objectInputStream.readObject(); System.out.println(student5); System.out.println(student6); System.out.println(student7); System.out.println(student8); System.out.println(text); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } @XStreamAlias("student") class Student { private String firstName; private String lastName; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String toString() { return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]"; } } Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − Student [ firstName: Mahesh, lastName: Parashar ] Student [ firstName: Suresh, lastName: Kalra ] Student [ firstName: Ramesh, lastName: Kumar ] Student [ firstName: Naresh, lastName: Sharma ] Hello World Look at the content of the test.txt present at C:\>XStream_WORKSPACE\com\tutorialspoint\xstream folder. <?xml version = "1.0" ?> <object-stream> <student> <firstName>Mahesh</firstName> <lastName>Parashar</lastName> </student> <student> <firstName>Suresh</firstName> <lastName>Kalra</lastName> </student> <student> <firstName>Ramesh</firstName> <lastName>Kumar</lastName> </student> <student> <firstName>Naresh</firstName> <lastName>Sharma</lastName> </student> <string>Hello World</string> </object-stream> XStream supports JSON by initializing XStream object with an appropriate driver. XStream currently supports JettisonMappedXmlDriver and JsonHierarchicalStreamDriver. Let us now test the code with json handling in XStream. Create a java class file named XStreamTester in C:\>XStream_WORKSPACE\com\tutorialspoint\xstream. package com.tutorialspoint.xstream; import java.io.Writer; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.json.JsonWriter; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE); } }); Student student = new Student("Mahesh","Parashar"); xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student", Student.class); System.out.println(xstream.toXML(student)); } } @XStreamAlias("student") class Student { private String firstName; private String lastName; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String toString() { return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]"; } } Compile the classes using javac compiler as follows − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester Verify the output as follows − { "firstName": "Mahesh", "lastName": "Parashar" } Print Add Notes Bookmark this page
[ { "code": null, "e": 1846, "s": 1758, "text": "XStream is a simple Java-based library to serialize Java objects to XML and vice versa." }, { "code": null, "e": 1931, "s": 1846, "text": "Easy to use − XStream API provides a high-level facade to simplify common use cases." }, { "code": null, "e": 2016, "s": 1931, "text": "Easy to use − XStream API provides a high-level facade to simplify common use cases." }, { "code": null, "e": 2123, "s": 2016, "text": "No need to create mapping − XStream API provides default mapping for most of the objects to be serialized." }, { "code": null, "e": 2230, "s": 2123, "text": "No need to create mapping − XStream API provides default mapping for most of the objects to be serialized." }, { "code": null, "e": 2346, "s": 2230, "text": "Performance − XStream is fast and is of low memory footprint, which is suitable for large object graphs or systems." }, { "code": null, "e": 2462, "s": 2346, "text": "Performance − XStream is fast and is of low memory footprint, which is suitable for large object graphs or systems." }, { "code": null, "e": 2542, "s": 2462, "text": "Clean XML − XStream produces clean and compact XML output that is easy to read." }, { "code": null, "e": 2622, "s": 2542, "text": "Clean XML − XStream produces clean and compact XML output that is easy to read." }, { "code": null, "e": 2818, "s": 2622, "text": "Object modification not required − XStream serializes internal fields like private and final fields, and supports non-public and inner classes. Default constructor is not a mandatory requirement." }, { "code": null, "e": 3014, "s": 2818, "text": "Object modification not required − XStream serializes internal fields like private and final fields, and supports non-public and inner classes. Default constructor is not a mandatory requirement." }, { "code": null, "e": 3161, "s": 3014, "text": "Full object graph support − XStream allows to maintain duplicate references encountered in the object-model and also supports circular references." }, { "code": null, "e": 3308, "s": 3161, "text": "Full object graph support − XStream allows to maintain duplicate references encountered in the object-model and also supports circular references." }, { "code": null, "e": 3460, "s": 3308, "text": "Customizable conversion strategies − Custom strategies can be registered in order to allow customization of a particular type to be represented as XML." }, { "code": null, "e": 3612, "s": 3460, "text": "Customizable conversion strategies − Custom strategies can be registered in order to allow customization of a particular type to be represented as XML." }, { "code": null, "e": 3740, "s": 3612, "text": "Security framework − XStream provides a fair control over unmarshalled types to prevent security issues with manipulated input." }, { "code": null, "e": 3868, "s": 3740, "text": "Security framework − XStream provides a fair control over unmarshalled types to prevent security issues with manipulated input." }, { "code": null, "e": 3985, "s": 3868, "text": "Error messages − When an exception occurs due to malformed XML, it provides detailed diagnostics to fix the problem." }, { "code": null, "e": 4102, "s": 3985, "text": "Error messages − When an exception occurs due to malformed XML, it provides detailed diagnostics to fix the problem." }, { "code": null, "e": 4192, "s": 4102, "text": "Alternative output format − XStream supports other output formats like JSON and morphing." }, { "code": null, "e": 4282, "s": 4192, "text": "Alternative output format − XStream supports other output formats like JSON and morphing." }, { "code": null, "e": 4452, "s": 4282, "text": "Transport − XML is a text representation of object and can be used to transport objects over the wire independent of the serialization / deserialization techniques used." }, { "code": null, "e": 4622, "s": 4452, "text": "Transport − XML is a text representation of object and can be used to transport objects over the wire independent of the serialization / deserialization techniques used." }, { "code": null, "e": 4738, "s": 4622, "text": "Persistence − Objects can be persisted as XML in databases and can be marshalled/unmarshalled as and when required." }, { "code": null, "e": 4854, "s": 4738, "text": "Persistence − Objects can be persisted as XML in databases and can be marshalled/unmarshalled as and when required." }, { "code": null, "e": 5036, "s": 4854, "text": "Configuration − XML is self-explanatory and is heavily used to define configurations. Objects can also be used for configuration purpose after converting them to XML representation." }, { "code": null, "e": 5218, "s": 5036, "text": "Configuration − XML is self-explanatory and is heavily used to define configurations. Objects can also be used for configuration purpose after converting them to XML representation." }, { "code": null, "e": 5327, "s": 5218, "text": "Unit Tests − XStream API is JUnit compatible and can be used to enhance unit testing of application modules." }, { "code": null, "e": 5436, "s": 5327, "text": "Unit Tests − XStream API is JUnit compatible and can be used to enhance unit testing of application modules." }, { "code": null, "e": 5542, "s": 5436, "text": "In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java." }, { "code": null, "e": 5756, "s": 5542, "text": "If you want to set up your environment for Java programming language, then this section explains how to download and set up Java on your machine. Please follow the steps given below to set up you Java environment." }, { "code": null, "e": 5807, "s": 5756, "text": "Java SE can be downloaded for free from the link −" }, { "code": null, "e": 5822, "s": 5807, "text": "Download Java." }, { "code": null, "e": 6054, "s": 5822, "text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to correct installation directories −" }, { "code": null, "e": 6128, "s": 6054, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 6182, "s": 6128, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 6236, "s": 6182, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 6303, "s": 6236, "text": "Click the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 6370, "s": 6303, "text": "Click the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 6605, "s": 6370, "text": "Alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6840, "s": 6605, "text": "Alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6914, "s": 6840, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 7036, "s": 6914, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −\n'SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 7108, "s": 7036, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −" }, { "code": null, "e": 7158, "s": 7108, "text": "'SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 7321, "s": 7158, "text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this." }, { "code": null, "e": 7465, "s": 7321, "text": "For example, if you use bash as your shell, then you would add the following line at the end of your '.bashrc: export PATH=/path/to/java:$PATH'" }, { "code": null, "e": 7635, "s": 7465, "text": "To write Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −" }, { "code": null, "e": 7749, "s": 7635, "text": "Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad." }, { "code": null, "e": 7863, "s": 7749, "text": "Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad." }, { "code": null, "e": 7968, "s": 7863, "text": "Netbeans − It is a Java IDE that is free and can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 8073, "s": 7968, "text": "Netbeans − It is a Java IDE that is free and can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 8205, "s": 8073, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 8337, "s": 8205, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 8528, "s": 8337, "text": "Download the latest version of XStream jar file from XStream download page. At the time of writing this tutorial, we have downloaded xstream-1.4.18.jar and copied it into C:\\>XStream folder." }, { "code": null, "e": 8811, "s": 8528, "text": "Set the XStream_HOME environment variable to point to the base directory location where xstream jar is stored on your machine. The following table shows how to set the XStream environment on Windows, Linux, and Mac, assuming we've extracted xstream-1.4.18.jar in the XStream folder." }, { "code": null, "e": 8819, "s": 8811, "text": "Windows" }, { "code": null, "e": 8875, "s": 8819, "text": "Set the environment variable XStream_HOME to C:\\XStream" }, { "code": null, "e": 8881, "s": 8875, "text": "Linux" }, { "code": null, "e": 8920, "s": 8881, "text": "export XStream_HOME=/usr/local/XStream" }, { "code": null, "e": 8924, "s": 8920, "text": "Mac" }, { "code": null, "e": 8961, "s": 8924, "text": "export XStream_HOME=/Library/XStream" }, { "code": null, "e": 9197, "s": 8961, "text": "Set the CLASSPATH environment variable to point to the XStream jar location. The following table shows how to set the CLASSPATH variable on Windows, Linux, and Mac system, assuming we've stored xstream-1.4.18.jar in the XStream folder." }, { "code": null, "e": 9205, "s": 9197, "text": "Windows" }, { "code": null, "e": 9294, "s": 9205, "text": "Set the environment variable CLASSPATH to %CLASSPATH%;%XStream_HOME%\\xstream-1.4.18.jar;" }, { "code": null, "e": 9300, "s": 9294, "text": "Linux" }, { "code": null, "e": 9362, "s": 9300, "text": "export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar;" }, { "code": null, "e": 9366, "s": 9362, "text": "Mac" }, { "code": null, "e": 9428, "s": 9366, "text": "export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar;" }, { "code": null, "e": 9724, "s": 9428, "text": "Before going into the details of the XStream library, let us see an application in action. In this example, we've created Student and Address classes. We will create a student object and then serialize it to an XML String. Then de-serialize the same XML string to obtain the student object back." }, { "code": null, "e": 9795, "s": 9724, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE." }, { "code": null, "e": 9820, "s": 9795, "text": "File: XStreamTester.java" }, { "code": null, "e": 14984, "s": 9820, "text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n\n public static void main(String args[]) {\n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n \n Student student = tester.getStudentDetails();\n \n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\n \n //XML to Object Conversion\n Student student1 = (Student)xstream.fromXML(xml);\n System.out.println(student1);\n }\n \n private Student getStudentDetails() {\n \n Student student = new Student();\n student.setFirstName(\"Mahesh\");\n student.setLastName(\"Parashar\");\n student.setRollNo(1);\n student.setClassName(\"1st\");\n\n Address address = new Address();\n address.setArea(\"H.No. 16/3, Preet Vihar.\");\n address.setCity(\"Delhi\");\n address.setState(\"Delhi\");\n address.setCountry(\"India\");\n address.setPincode(110012);\n\n student.setAddress(address);\n return student;\n }\n \n public static String formatXml(String xml) {\n \n try {\n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) {\n return xml;\n }\n }\n}\n\nclass Student {\n private int rollNo;\n private String firstName;\n private String lastName;\n private String className;\n private Address address;\n\n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n \n public int getRollNo() {\n return rollNo;\n }\n \n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n \n public String getClassName() {\n return className;\n }\n \n public void setClassName(String className) {\n this.className = className;\n }\n \n public Address getAddress() {\n return address;\n }\n \n public void setAddress(Address address) {\n this.address = address;\n }\n \n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n \n stringBuilder.append(\"Student [ \");\n stringBuilder.append(\"\\nfirstName: \");\n stringBuilder.append(firstName);\n stringBuilder.append(\"\\nlastName: \");\n stringBuilder.append(lastName);\n stringBuilder.append(\"\\nrollNo: \");\n stringBuilder.append(rollNo);\n stringBuilder.append(\"\\nclassName: \");\n stringBuilder.append(className);\n stringBuilder.append(\"\\naddress: \");\n stringBuilder.append(address);\n stringBuilder.append(\" ]\");\n \n return stringBuilder.toString();\n }\n}\n\nclass Address {\n private String area;\n private String city;\n private String state;\n private String country;\n private int pincode;\n\n public String getArea() {\n return area;\n }\n\n public void setArea(String area) {\n this.area = area;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public int getPincode() {\n return pincode;\n }\n\n public void setPincode(int pincode) {\n this.pincode = pincode;\n }\n\n public String toString() {\n\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"\\nAddress [ \");\n stringBuilder.append(\"\\narea: \");\n stringBuilder.append(area);\n stringBuilder.append(\"\\ncity: \");\n stringBuilder.append(city);\n stringBuilder.append(\"\\nstate: \");\n stringBuilder.append(state);\n stringBuilder.append(\"\\ncountry: \");\n stringBuilder.append(country);\n stringBuilder.append(\"\\npincode: \");\t\n stringBuilder.append(pincode);\n stringBuilder.append(\" ]\");\n\n return stringBuilder.toString();\n }\n}" }, { "code": null, "e": 15002, "s": 14984, "text": "Verify the Result" }, { "code": null, "e": 15056, "s": 15002, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 15103, "s": 15056, "text": "C:\\XStream_WORKSPACE>javac XStreamTester.java\n" }, { "code": null, "e": 15149, "s": 15103, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 15190, "s": 15149, "text": "C:\\XStream_WORKSPACE>java XStreamTester\n" }, { "code": null, "e": 15219, "s": 15190, "text": "Verify the output as follows" }, { "code": null, "e": 15826, "s": 15219, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<Student>\n <firstName>Mahesh</firstName>\n <lastName>Parashar</lastName>\n <rollNo>1</rollNo>\n <className>1st</className>\n <address>\n <area>H.No. 16/3, Preet Vihar.</area>\n <city>Delhi</city>\n <state>Delhi</state>\n <country>India</country>\n <pincode>110012</pincode>\n </address>\n</Student>\n\nStudent [ \n firstName: Mahesh\n lastName: Parashar\n rollNo: 1\n className: 1st\n address: \n Address [ \n area: H.No. 16/3, Preet Vihar.\n city: Delhi\n state: Delhi\n country: India\n pincode: 110012\n ] \n]\n" }, { "code": null, "e": 15883, "s": 15826, "text": "Following are the important steps to be considered here." }, { "code": null, "e": 16019, "s": 15883, "text": "Create an XStream object by passing it a StaxDriver. StaxDriver uses Stax pull parser (available from java 6) and is a fast xml parser." }, { "code": null, "e": 16068, "s": 16019, "text": "XStream xstream = new XStream(new StaxDriver());" }, { "code": null, "e": 16139, "s": 16068, "text": "Use toXML() method to get the XML string representation of the object." }, { "code": null, "e": 16203, "s": 16139, "text": "//Object to XML Conversion\nString xml = xstream.toXML(student);" }, { "code": null, "e": 16256, "s": 16203, "text": "Use fromXML() method to get the object from the XML." }, { "code": null, "e": 16335, "s": 16256, "text": "//XML to Object Conversion\t\t\nStudent student1 = (Student)xstream.fromXML(xml);" }, { "code": null, "e": 16541, "s": 16335, "text": "Aliasing is a technique to customize the generated XML or to use a particular formatted XML using XStream. Let’s suppose the following XML format is to be used to serialize/de-serialize the Student object." }, { "code": null, "e": 16788, "s": 16541, "text": "<student name = \"Suresh\">\n <note>\n <title>first</title>\n <description>My first assignment.</description>\n </note>\n \n <note>\n <title>second</title>\n <description>My second assignment.</description>\n </note>\n</student>" }, { "code": null, "e": 16847, "s": 16788, "text": "Based on the above XML format, let's create model classes." }, { "code": null, "e": 17539, "s": 16847, "text": "class Student {\n private String studentName;\n private List<Note> notes = new ArrayList<Note>();\n \n public Student(String name) {\n this.studentName = name;\n }\n \n public void addNote(Note note) {\n notes.add(note);\n }\n \n public String getName() {\n return studentName;\n }\n \n public List<Note> getNotes() {\n return notes;\n }\n}\n\nclass Note {\n private String title;\n private String description;\n\n public Note(String title, String description) {\n this.title = title;\n this.description = description;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getDescription() {\n return description;\n } \n}" }, { "code": null, "e": 17597, "s": 17539, "text": "Let's test the above objects serialization using XStream." }, { "code": null, "e": 17695, "s": 17597, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 17720, "s": 17695, "text": "File: XStreamTester.java" }, { "code": null, "e": 20367, "s": 17720, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n public static void main(String args[]) {\n \n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n Student student = tester.getStudentDetails();\n \n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\t\t\n }\t\n\n private Student getStudentDetails() {\n \n Student student = new Student(\"Mahesh\");\n \n student.addNote(new Note(\"first\",\"My first assignment.\"));\n student.addNote(new Note(\"second\",\"My Second assignment.\"));\n \n return student;\n }\n\n public static String formatXml(String xml) {\n \n try {\n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) {\n return xml;\n }\n }\n}\n\nclass Student {\n private String studentName;\n private List<Note> notes = new ArrayList<Note>();\n \n public Student(String name) {\n this.studentName = name;\n }\n \n public void addNote(Note note) {\n notes.add(note);\n }\n \n public String getName() {\n return studentName;\n }\n \n public List<Note> getNotes() {\n return notes;\n }\n}\n\nclass Note {\n private String title;\n private String description;\n \n public Note(String title, String description) {\n this.title = title;\n this.description = description;\n }\n \n public String getTitle() {\n return title;\n }\n \n public String getDescription() {\n return description;\n } \n}" }, { "code": null, "e": 20385, "s": 20367, "text": "Verify the Result" }, { "code": null, "e": 20439, "s": 20385, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 20513, "s": 20439, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 20559, "s": 20513, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 20627, "s": 20559, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 20658, "s": 20627, "text": "Verify the output as follows −" }, { "code": null, "e": 21181, "s": 20658, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<com.tutorialspoint.xstream.Student>\n <studentName>Mahesh</studentName>\n <notes>\n <com.tutorialspoint.xstream.Note>\n <title>first</title>\n <description>My first assignment.</description>\n </com.tutorialspoint.xstream.Note>\n \n <com.tutorialspoint.xstream.Note>\n <title>second</title>\n <description>My Second assignment.</description>\n </com.tutorialspoint.xstream.Note>\n </notes>\n</com.tutorialspoint.xstream.Student>\n" }, { "code": null, "e": 21301, "s": 21181, "text": "In the above result, the Student object name is fully qualified. To replace it as student tag, follow the next section." }, { "code": null, "e": 21316, "s": 21301, "text": "Class Aliasing" }, { "code": null, "e": 21331, "s": 21316, "text": "Class Aliasing" }, { "code": null, "e": 21346, "s": 21331, "text": "Field Aliasing" }, { "code": null, "e": 21361, "s": 21346, "text": "Field Aliasing" }, { "code": null, "e": 21391, "s": 21361, "text": "Implicit Collections Aliasing" }, { "code": null, "e": 21421, "s": 21391, "text": "Implicit Collections Aliasing" }, { "code": null, "e": 21440, "s": 21421, "text": "Attribute Aliasing" }, { "code": null, "e": 21459, "s": 21440, "text": "Attribute Aliasing" }, { "code": null, "e": 21476, "s": 21459, "text": "Package Aliasing" }, { "code": null, "e": 21493, "s": 21476, "text": "Package Aliasing" }, { "code": null, "e": 21654, "s": 21493, "text": "XStream supports annotations similarly like automatic configuration instead of coding. In the previous chapter, we've seen the following configurations in code." }, { "code": null, "e": 21899, "s": 21654, "text": "xstream.alias(\"student\", Student.class);\nxstream.alias(\"note\", Note.class);\n\nxstream.useAttributeFor(Student.class, \"studentName\");\nxstream.aliasField(\"name\", Student.class, \"studentName\");\nxstream.addImplicitCollection(Student.class, \"notes\");" }, { "code": null, "e": 22003, "s": 21899, "text": "The following code snippet illustrates the use of annotations to do the same work in a much easier way." }, { "code": null, "e": 22434, "s": 22003, "text": "@XStreamAlias(\"student\") //define class level alias\nclass Student {\n\n @XStreamAlias(\"name\") //define field level alias\n @XStreamAsAttribute //define field as attribute\n private String studentName;\n \n @XStreamImplicit //define list as an implicit collection\n private List<Note> notes = new ArrayList<Note>();\n \n @XStreamOmitField //omit a field to not to be a part of XML\n private int type;\n}" }, { "code": null, "e": 22482, "s": 22434, "text": "Let us test the above annotation using XStream." }, { "code": null, "e": 22580, "s": 22482, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 25812, "s": 22580, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.annotations.XStreamAlias;\nimport com.thoughtworks.xstream.annotations.XStreamAsAttribute;\nimport com.thoughtworks.xstream.annotations.XStreamImplicit;\nimport com.thoughtworks.xstream.annotations.XStreamOmitField;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n\n public static void main(String args[]) {\n\n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n Student student = tester.getStudentDetails();\n \n xstream.processAnnotations(Student.class);\t\t\n\n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\t\t\n }\n \n private Student getStudentDetails() {\n \n Student student = new Student(\"Mahesh\");\n \n student.addNote(new Note(\"first\",\"My first assignment.\"));\n student.addNote(new Note(\"second\",\"My Second assignment.\"));\n student.setType(1);\n \n return student;\n }\n\n public static String formatXml(String xml) {\n \n try {\n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) {\n return xml;\n }\n }\n}\n\n@XStreamAlias(\"student\")\nclass Student {\n\n @XStreamAlias(\"name\")\n @XStreamAsAttribute \n private String studentName;\n\n @XStreamImplicit\n private List<Note> notes = new ArrayList<Note>();\n\n public Student(String name) {\n this.studentName = name;\n }\n\n public void addNote(Note note) {\n notes.add(note);\n }\n\n public String getName() {\n return studentName;\n }\n\n public List<Note> getNotes() {\n return notes;\n }\n \n @XStreamOmitField\t\t\n private int type;\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n}\n\n@XStreamAlias(\"note\")\nclass Note {\n private String title;\n private String description;\n\n public Note(String title, String description) {\n this.title = title;\n this.description = description;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getDescription() {\n return description;\n } \n}" }, { "code": null, "e": 25866, "s": 25812, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 25940, "s": 25866, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 25986, "s": 25940, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 26054, "s": 25986, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 26085, "s": 26054, "text": "Verify the output as follows −" }, { "code": null, "e": 26372, "s": 26085, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<student name = \"Mahesh\">\n <note>\n <title>first</title>\n <description>My first assignment.</description>\n </note>\n\n <note>\n <title>second</title>\n <description>My Second assignment.</description>\n </note>\n</student>" }, { "code": null, "e": 26500, "s": 26372, "text": "In order to instruct the XStream framework to process annotation, you need to add the following command before serializing xml." }, { "code": null, "e": 26546, "s": 26500, "text": "xstream.processAnnotations(Student.class);\t\t\n" }, { "code": null, "e": 26549, "s": 26546, "text": "Or" }, { "code": null, "e": 26587, "s": 26549, "text": "xstream.autodetectAnnotations(true);\n" }, { "code": null, "e": 26839, "s": 26587, "text": "XStream converters are the key components of the XStream library, which are responsible to convert an object to XML and vice versa. XStream provides numerous converters for common types such as primitives, String, File, Collections, arrays, and Dates." }, { "code": null, "e": 27006, "s": 26839, "text": "Let us use a SingleValueConvertor whose purpose is to convert an object into a single string. We will use SingleValueConvertor to write an object as attribute string." }, { "code": null, "e": 27424, "s": 27006, "text": "class NameConverter implements SingleValueConverter {\n\n public Object fromString(String name) {\n String[] nameparts = name.split(\",\");\n return new Name(nameparts[0], nameparts[1]);\n }\n \n public String toString(Object name) {\n return ((Name)name).getFirstName() + \",\" + ((Name)name).getLastName();\n }\n \n public boolean canConvert(Class type) {\n return type.equals(Name.class);\n }\t\n}" }, { "code": null, "e": 27472, "s": 27424, "text": "xstream.registerConverter(new NameConverter());" }, { "code": null, "e": 27529, "s": 27472, "text": "Let us first test the code without converter in XStream." }, { "code": null, "e": 27627, "s": 27529, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 27652, "s": 27627, "text": "File: XStreamTester.java" }, { "code": null, "e": 30196, "s": 27652, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.annotations.XStreamAlias;\nimport com.thoughtworks.xstream.annotations.XStreamAsAttribute;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n public static void main(String args[]) {\n \n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n Student student = tester.getStudentDetails();\n xstream.autodetectAnnotations(true);\n \n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\n }\n \n private Student getStudentDetails() {\n Student student = new Student(\"Mahesh\",\"Parashar\");\n return student;\n }\n \n public static String formatXml(String xml) {\n \n try {\n \n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream());\n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) {\n return xml;\n }\n }\n}\n\n@XStreamAlias(\"student\")\nclass Student {\n\n @XStreamAlias(\"name\")\n @XStreamAsAttribute\n private Name studentName;\n\n public Student(String firstName, String lastName) {\n this.studentName = new Name(firstName, lastName);\n }\n\n public Name getName() {\n return studentName;\n }\t\n}\n\nclass Name {\n private String firstName;\n private String lastName;\n\n public Name(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n } \n}" }, { "code": null, "e": 30214, "s": 30196, "text": "Verify the Result" }, { "code": null, "e": 30268, "s": 30214, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 30342, "s": 30268, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 30388, "s": 30342, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 30456, "s": 30388, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 30487, "s": 30456, "text": "Verify the output as follows −" }, { "code": null, "e": 30645, "s": 30487, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<student>\n <name>\n <firstName>Mahesh</firstName>\n <lastName>Parashar</lastName>\n </name>\n</student>\n" }, { "code": null, "e": 30697, "s": 30645, "text": "Let us now test the code with converter in XStream." }, { "code": null, "e": 30795, "s": 30697, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 30820, "s": 30795, "text": "File: XStreamTester.java" }, { "code": null, "e": 33926, "s": 30820, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.annotations.XStreamAlias;\nimport com.thoughtworks.xstream.annotations.XStreamAsAttribute;\nimport com.thoughtworks.xstream.converters.SingleValueConverter;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n\n public static void main(String args[]) {\n \n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n Student student = tester.getStudentDetails();\t\t\n \n xstream.autodetectAnnotations(true);\n xstream.registerConverter(new NameConverter());\n \n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\t\t\n }\t\n\n private Student getStudentDetails() {\n Student student = new Student(\"Mahesh\",\"Parashar\");\t\t\n return student;\n }\n\n public static String formatXml(String xml) {\n\n try {\n \n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\"); \n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) { \n return xml;\n }\n }\n}\n\n@XStreamAlias(\"student\")\nclass Student {\n\n @XStreamAlias(\"name\")\n @XStreamAsAttribute\t\n private Name studentName;\n\n public Student(String firstName, String lastName) {\n this.studentName = new Name(firstName, lastName);\n }\n\n public Name getName() {\n return studentName;\n }\t\n}\n\nclass Name {\n private String firstName;\n private String lastName;\n\n public Name(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n } \n}\n\nclass NameConverter implements SingleValueConverter {\n\n public Object fromString(String name) {\n String[] nameparts = name.split(\",\");\n return new Name(nameparts[0], nameparts[1]);\n }\n\n public String toString(Object name) {\n return ((Name)name).getFirstName() + \",\" + ((Name)name).getLastName();\n }\n\n public boolean canConvert(Class type) {\n return type.equals(Name.class);\n }\n}" }, { "code": null, "e": 33944, "s": 33926, "text": "Verify the Result" }, { "code": null, "e": 33998, "s": 33944, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 34072, "s": 33998, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 34118, "s": 34072, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 34186, "s": 34118, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 34217, "s": 34186, "text": "Verify the output as follows −" }, { "code": null, "e": 34297, "s": 34217, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<student name = \"Mahesh,Parashar\"/>\n" }, { "code": null, "e": 34314, "s": 34297, "text": "Custom Converter" }, { "code": null, "e": 34606, "s": 34314, "text": "XStream provides alternative implementations of java.io.ObjectInputStream and java.io.ObjectOutputStream so that streams of objects can be serialized or deserialized from XML. This is particularly useful when large sets of objects are to be processed, keeping one object in memory at a time." }, { "code": null, "e": 34718, "s": 34606, "text": "ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(\n new FileOutputStream(\"test.txt\"));" }, { "code": null, "e": 34826, "s": 34718, "text": "ObjectInputStream objectInputStream = xstream.createObjectInputStream(\n new FileInputStream(\"test.txt\"));" }, { "code": null, "e": 34883, "s": 34826, "text": "Let us now test the code with object streams in XStream." }, { "code": null, "e": 34981, "s": 34883, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 37612, "s": 34981, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.annotations.XStreamAlias;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n public static void main(String args[]) {\n \n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n \n xstream.autodetectAnnotations(true);\n \n Student student1 = new Student(\"Mahesh\",\"Parashar\");\n Student student2 = new Student(\"Suresh\",\"Kalra\");\n Student student3 = new Student(\"Ramesh\",\"Kumar\");\n Student student4 = new Student(\"Naresh\",\"Sharma\");\n \n try {\n \n ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(\n new FileOutputStream(\"test.txt\"));\n \n objectOutputStream.writeObject(student1);\n objectOutputStream.writeObject(student2);\n objectOutputStream.writeObject(student3);\n objectOutputStream.writeObject(student4);\n objectOutputStream.writeObject(\"Hello World\");\n \n objectOutputStream.close();\n \n ObjectInputStream objectInputStream = xstream.createObjectInputStream(\n new FileInputStream(\"test.txt\"));\n \n Student student5 = (Student)objectInputStream.readObject();\n Student student6 = (Student)objectInputStream.readObject();\n Student student7 = (Student)objectInputStream.readObject();\n Student student8 = (Student)objectInputStream.readObject();\n \n String text = (String)objectInputStream.readObject();\n \n System.out.println(student5);\n System.out.println(student6);\n System.out.println(student7);\n System.out.println(student8);\n System.out.println(text);\n \n } catch (IOException e) {\n e.printStackTrace();\n \n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n }\n}\n\n@XStreamAlias(\"student\")\nclass Student {\n\n private String firstName;\n private String lastName;\n \n public Student(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n } \n\n public String toString() {\n return \"Student [ firstName: \"+firstName+\", lastName: \"+ lastName+ \" ]\";\n }\t\n}" }, { "code": null, "e": 37666, "s": 37612, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 37740, "s": 37666, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 37786, "s": 37740, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 37854, "s": 37786, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 37885, "s": 37854, "text": "Verify the output as follows −" }, { "code": null, "e": 38090, "s": 37885, "text": "Student [ firstName: Mahesh, lastName: Parashar ]\nStudent [ firstName: Suresh, lastName: Kalra ]\nStudent [ firstName: Ramesh, lastName: Kumar ]\nStudent [ firstName: Naresh, lastName: Sharma ]\nHello World\n" }, { "code": null, "e": 38194, "s": 38090, "text": "Look at the content of the test.txt present at C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream folder." }, { "code": null, "e": 38684, "s": 38194, "text": "<?xml version = \"1.0\" ?>\n<object-stream>\n <student>\n <firstName>Mahesh</firstName>\n <lastName>Parashar</lastName>\n </student>\n \n <student>\n <firstName>Suresh</firstName>\n <lastName>Kalra</lastName>\n </student>\n \n <student>\n <firstName>Ramesh</firstName>\n <lastName>Kumar</lastName>\n </student>\n \n <student>\n <firstName>Naresh</firstName>\n <lastName>Sharma</lastName>\n </student>\n <string>Hello World</string>\n</object-stream>" }, { "code": null, "e": 38850, "s": 38684, "text": "XStream supports JSON by initializing XStream object with an appropriate driver. XStream currently supports JettisonMappedXmlDriver and JsonHierarchicalStreamDriver." }, { "code": null, "e": 38906, "s": 38850, "text": "Let us now test the code with json handling in XStream." }, { "code": null, "e": 39004, "s": 38906, "text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE\\com\\tutorialspoint\\xstream." }, { "code": null, "e": 40407, "s": 39004, "text": "package com.tutorialspoint.xstream;\n\nimport java.io.Writer;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.annotations.XStreamAlias;\nimport com.thoughtworks.xstream.io.HierarchicalStreamWriter;\nimport com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;\nimport com.thoughtworks.xstream.io.json.JsonWriter;\n\npublic class XStreamTester {\n\n public static void main(String args[]) {\n\n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {\n \n public HierarchicalStreamWriter createWriter(Writer writer) {\n return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);\n }\n });\n\n Student student = new Student(\"Mahesh\",\"Parashar\");\n\n xstream.setMode(XStream.NO_REFERENCES);\n xstream.alias(\"student\", Student.class);\n \n System.out.println(xstream.toXML(student));\n }\n}\n\n@XStreamAlias(\"student\")\nclass Student {\n\n private String firstName;\n private String lastName;\n\n public Student(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n } \n\t\n public String toString() {\n return \"Student [ firstName: \"+firstName+\", lastName: \"+ lastName+ \" ]\";\n }\t\n}" }, { "code": null, "e": 40461, "s": 40407, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 40535, "s": 40461, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>javac XStreamTester.java\n" }, { "code": null, "e": 40581, "s": 40535, "text": "Now run the XStreamTester to see the result −" }, { "code": null, "e": 40649, "s": 40581, "text": "C:\\XStream_WORKSPACE\\com\\tutorialspoint\\xstream>java XStreamTester\n" }, { "code": null, "e": 40680, "s": 40649, "text": "Verify the output as follows −" }, { "code": null, "e": 40737, "s": 40680, "text": "{\n \"firstName\": \"Mahesh\",\n \"lastName\": \"Parashar\"\n}\n" }, { "code": null, "e": 40744, "s": 40737, "text": " Print" }, { "code": null, "e": 40755, "s": 40744, "text": " Add Notes" } ]
Groovy - Nested Switch Statement
It is also possible to have a nested set of switch statements. The general form of the statement is shown below − switch(expression) { case expression #1: statement #1 ... case expression #2: statement #2 ... case expression #N: statement #N ... default: statement #Default ... } Following is an example of the nested switch statement − class Example { static void main(String[] args) { //Initializing 2 variables i and j int i = 0; int j = 1; // First evaluating the value of variable i switch(i) { case 0: // Next evaluating the value of variable j switch(j) { case 0: println("i is 0, j is 0"); break; case 1: println("i is 0, j is 1"); break; // The default condition for the inner switch statement default: println("nested default case!!"); } break; // The default condition for the outer switch statement default: println("No matching case found!!"); } } } In the above example, we are first initializing a variable to the a to a value of 2. We then have a switch statement which evaluates the value of the variable a. Based on the value of the variable it will execute the relevant case set of statements. The output of the above code would be − i is 0, j is 1 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2238, "text": "It is also possible to have a nested set of switch statements. The general form of the statement is shown below −" }, { "code": null, "e": 2567, "s": 2352, "text": "switch(expression) { \n case expression #1: \n statement #1 \n ... \n case expression #2: \n statement #2\n ... \n case expression #N: \n statement #N \n ... \n default: \n statement #Default \n ... \n}\n" }, { "code": null, "e": 2624, "s": 2567, "text": "Following is an example of the nested switch statement −" }, { "code": null, "e": 3470, "s": 2624, "text": "class Example { \n static void main(String[] args) { \n //Initializing 2 variables i and j \n int i = 0; \n int j = 1; \n\t\t\n // First evaluating the value of variable i \n switch(i) { \n case 0: \n // Next evaluating the value of variable j \n switch(j) { \n case 0: \n println(\"i is 0, j is 0\"); \n break; \n case 1: \n println(\"i is 0, j is 1\"); \n break; \n \n // The default condition for the inner switch statement \n default: \n println(\"nested default case!!\"); \n } \n break; \n\t\t\t\n // The default condition for the outer switch statement \n default: \n println(\"No matching case found!!\"); \n }\n }\n}" }, { "code": null, "e": 3760, "s": 3470, "text": "In the above example, we are first initializing a variable to the a to a value of 2. We then have a switch statement which evaluates the value of the variable a. Based on the value of the variable it will execute the relevant case set of statements. The output of the above code would be −" }, { "code": null, "e": 3776, "s": 3760, "text": "i is 0, j is 1\n" }, { "code": null, "e": 3809, "s": 3776, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3827, "s": 3809, "text": " Krishna Sakinala" }, { "code": null, "e": 3862, "s": 3827, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3880, "s": 3862, "text": " Packt Publishing" }, { "code": null, "e": 3887, "s": 3880, "text": " Print" }, { "code": null, "e": 3898, "s": 3887, "text": " Add Notes" } ]
Solidity - For Loop
The for loop is the most compact form of looping. It includes the following three important parts − The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop. The iteration statement where you can increase or decrease your counter. The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by semicolons. The flow chart of a for loop in Solidity would be as follows − The syntax of for loop is Solidity is as follows − for (initialization; test condition; iteration statement) { Statement(s) to be executed if test condition is true } pragma solidity ^0.5.0; contract SolidityTest { uint storedData; constructor() public{ storedData = 10; } function getResult() public view returns(string memory){ uint a = 10; uint b = 2; uint result = a + b; return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j=0; uint len; for (j = _i; j != 0; j /= 10) { //for loop example len++; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. 0: string: 12 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2655, "s": 2555, "text": "The for loop is the most compact form of looping. It includes the following three important parts −" }, { "code": null, "e": 2797, "s": 2655, "text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins." }, { "code": null, "e": 2939, "s": 2797, "text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins." }, { "code": null, "e": 3140, "s": 2939, "text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop." }, { "code": null, "e": 3341, "s": 3140, "text": "The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop." }, { "code": null, "e": 3414, "s": 3341, "text": "The iteration statement where you can increase or decrease your counter." }, { "code": null, "e": 3487, "s": 3414, "text": "The iteration statement where you can increase or decrease your counter." }, { "code": null, "e": 3561, "s": 3487, "text": "You can put all the three parts in a single line separated by semicolons." }, { "code": null, "e": 3624, "s": 3561, "text": "The flow chart of a for loop in Solidity would be as follows −" }, { "code": null, "e": 3675, "s": 3624, "text": "The syntax of for loop is Solidity is as follows −" }, { "code": null, "e": 3795, "s": 3675, "text": "for (initialization; test condition; iteration statement) {\n Statement(s) to be executed if test condition is true\n}\n" }, { "code": null, "e": 4571, "s": 3795, "text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; \n constructor() public{\n storedData = 10; \n }\n\n function getResult() public view returns(string memory){\n uint a = 10; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n\n function integerToString(uint _i) internal pure \n returns (string memory) {\n if (_i == 0) {\n return \"0\";\n }\n uint j=0;\n uint len;\n for (j = _i; j != 0; j /= 10) { //for loop example\n len++; \n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);//access local variable\n }\n}" }, { "code": null, "e": 4653, "s": 4571, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 4668, "s": 4653, "text": "0: string: 12\n" }, { "code": null, "e": 4703, "s": 4668, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4720, "s": 4703, "text": " Abhilash Nelson" }, { "code": null, "e": 4755, "s": 4720, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4772, "s": 4755, "text": " Frahaan Hussain" }, { "code": null, "e": 4807, "s": 4772, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4821, "s": 4807, "text": " Swapnil Kole" }, { "code": null, "e": 4828, "s": 4821, "text": " Print" }, { "code": null, "e": 4839, "s": 4828, "text": " Add Notes" } ]
Perl require Function
This function then it demands that the script requires the specified version of Perl in order to continue if EXPR is numeric. If EXPR or $_ are not numeric, it assumes that the name is the name of a library file to be included. You cannot include the same file with this function twice. The included file must return a true value as the last statement. This differs from use in that included files effectively become additional text for the current script. Functions, variables, and other objects are not imported into the current name space, so if the specified file includes a package definition, then objects will require fully qualified names. The specified module is searched for in the directories defined in @INC, looking for a file with the specified name and an extension of .pm. Following is the simple syntax for this function − require EXPR require This function does not return any value. Following is the example code showing its basic usage − #!/usr/bin/perl -w # require to demand a particular perl version. require 5.003; # require to include amodule. require Module; .............. 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2573, "s": 2220, "text": "This function then it demands that the script requires the specified version of Perl in order to continue if EXPR is numeric. If EXPR or $_ are not numeric, it assumes that the name is the name of a library file to be included. You cannot include the same file with this function twice. The included file must return a true value as the last statement." }, { "code": null, "e": 2868, "s": 2573, "text": "This differs from use in that included files effectively become additional text for the current script. Functions, variables, and other objects are not imported into the current name space, so if the specified file includes a package definition, then objects will require fully qualified names." }, { "code": null, "e": 3009, "s": 2868, "text": "The specified module is searched for in the directories defined in @INC, looking for a file with the specified name and an extension of .pm." }, { "code": null, "e": 3060, "s": 3009, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 3083, "s": 3060, "text": "require EXPR\n\nrequire\n" }, { "code": null, "e": 3124, "s": 3083, "text": "This function does not return any value." }, { "code": null, "e": 3180, "s": 3124, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 3325, "s": 3180, "text": "#!/usr/bin/perl -w\n\n# require to demand a particular perl version.\nrequire 5.003;\n\n# require to include amodule.\nrequire Module;\n\n.............." }, { "code": null, "e": 3360, "s": 3325, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3374, "s": 3360, "text": " Devi Killada" }, { "code": null, "e": 3409, "s": 3374, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3429, "s": 3409, "text": " Harshit Srivastava" }, { "code": null, "e": 3462, "s": 3429, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3478, "s": 3462, "text": " TELCOMA Global" }, { "code": null, "e": 3511, "s": 3478, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3528, "s": 3511, "text": " Mohammad Nauman" }, { "code": null, "e": 3561, "s": 3528, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3584, "s": 3561, "text": " Stone River ELearning" }, { "code": null, "e": 3619, "s": 3584, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3642, "s": 3619, "text": " Stone River ELearning" }, { "code": null, "e": 3649, "s": 3642, "text": " Print" }, { "code": null, "e": 3660, "s": 3649, "text": " Add Notes" } ]
Convert covariance matrix to correlation matrix using Python - GeeksforGeeks
08 Oct, 2021 In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python. It tells us how two quantities are related to one another say we want to calculate the covariance between x and y the then the outcome can be one of these. where are the means of x and y respectively. Interpreting the output: Either the covariance between x and y is : Covariance(x,y) > 0 : this means that they are positively related Covariance(x,y) < 0 : this means that x and y are negatively related if Covariance(x,y) = 0 : then x and y are independent of each other. Covariance matrix: Covariance provides a measure of the strength of correlation between two variable or more set of variables, to calculate the covariance matrix, the cov() method in numpy is used.. Syntax: ny.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None) m : [array_like] A 1D or 2D variables. variables are columns y : [array_like] It has the same form as that of m. rowvar : [bool, optional] If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: bias : Default normalization is False. If bias is True it normalize the data points. ddof : If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified. fweights : fweight is 1-D array of integer frequency weights aweights : aweight is 1-D array of observation vector weights. Returns: It returns ndarray covariance matrix It shows whether and how strongly pairs of variables are related to each other. Correlation takes values between -1 to +1, wherein values close to +1 represents strong positive correlation and values close to -1 represents strong negative correlation. It gives the direction and strength of the relationship between variables. Correlation Matrix: It is basically a covariance matrix. Also known as the auto-covariance matrix, dispersion matrix, variance matrix, or variance-covariance matrix. It is a matrix in which i-j position defines the correlation between the ith and jth parameter of the given data-set. It is calculated using numpy‘s corrcoeff() method. Syntax: numpy.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>) x : A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below. y, optional: An additional set of variables and observations. y has the same shape as x. rowvar : If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. Returns: ndarray Covariance tells us if two random variables are +ve or -ve related it doesn’t tell us by how much.Covariance is variant to arithmetic changes eg: if we multiply x by 10 or divide by 10 then the result will change, this is not true for correlation where the results remain unchanged by such operations.The output of covariance is difficult to compare as the values can range from – infinity to +infinity. While output values of correlation ranges from 0 to 1. Covariance tells us if two random variables are +ve or -ve related it doesn’t tell us by how much. Covariance is variant to arithmetic changes eg: if we multiply x by 10 or divide by 10 then the result will change, this is not true for correlation where the results remain unchanged by such operations. The output of covariance is difficult to compare as the values can range from – infinity to +infinity. While output values of correlation ranges from 0 to 1. Correlation is just normalized Covariance refer to the formula below. where are the standard deviation of x and y respectively. Python Program to convert Covariance matrix to Correlation matrix To solve this problem we have selected the iris data because to compute covariance we need data and it’s better if we use a real word example dataset. Loading and displaying the dataset Python3 import numpy as npimport pandas as pd # loading in the iris dataset for demo purposes dataset = pd.read_csv("iris.csv") dataset.head() In this example we won’t be using the target column Python3 data = dataset.iloc[:, :-1].values Program to implement covariance matrix: Python3 # calculates the covariance between x and ydef calcCov(x, y): mean_x, mean_y = x.mean(), y.mean() n = len(x) return sum((x - mean_x) * (y - mean_y)) / n # calculates the Covariance matrixdef covMat(data): # get the rows and cols rows, cols = data.shape # the covariance matroix has a shape of n_features x n_features # n_featurs = cols - 1 (not including the target column) cov_mat = np.zeros((cols, cols)) for i in range(cols): for j in range(cols): # store the value in the matrix cov_mat[i][j] = calcCov(data[:, i], data[:, j]) return cov_mat covMat(data) Output : Numpy cov() output : Python3 np.cov(data,rowvar=False) note : the rowVars needs to be make false otherwise it will take the rows as features and columns and observations. Output: Calculating Correlation: In this function, we are going to convert the Covariance matrix to correlation. Python3 # Now calculating Correlation using our Covariance function (covMat()) def corrMat(data): rows, cols = data.shape corr_mat = np.zeros((cols, cols)) for i in range(cols): for j in range(cols): x, y = data[:, i], data[:, j] # not here that we are just normalizing the covariance matrix corr_mat[i][j] = calcCov(x, y) / (x.std() * y.std()) return corr_mat corrMat(data) Output: The corrcoef() in numpy can also be used to compute the correlation. Python3 np.corrcoef(data,rowvar=False) Output: surinderdawra388 abhishek0719kadiyan 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 ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24470, "s": 24292, "text": "In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python. " }, { "code": null, "e": 24626, "s": 24470, "text": "It tells us how two quantities are related to one another say we want to calculate the covariance between x and y the then the outcome can be one of these." }, { "code": null, "e": 24672, "s": 24626, "text": "where are the means of x and y respectively. " }, { "code": null, "e": 24699, "s": 24672, "text": "Interpreting the output: " }, { "code": null, "e": 24743, "s": 24699, "text": "Either the covariance between x and y is : " }, { "code": null, "e": 24810, "s": 24743, "text": "Covariance(x,y) > 0 : this means that they are positively related " }, { "code": null, "e": 24881, "s": 24810, "text": "Covariance(x,y) < 0 : this means that x and y are negatively related " }, { "code": null, "e": 24950, "s": 24881, "text": "if Covariance(x,y) = 0 : then x and y are independent of each other." }, { "code": null, "e": 24970, "s": 24950, "text": "Covariance matrix: " }, { "code": null, "e": 25152, "s": 24970, "text": "Covariance provides a measure of the strength of correlation between two variable or more set of variables, to calculate the covariance matrix, the cov() method in numpy is used.. " }, { "code": null, "e": 25162, "s": 25152, "text": "Syntax: " }, { "code": null, "e": 25246, "s": 25162, "text": "ny.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)" }, { "code": null, "e": 25307, "s": 25246, "text": "m : [array_like] A 1D or 2D variables. variables are columns" }, { "code": null, "e": 25359, "s": 25307, "text": "y : [array_like] It has the same form as that of m." }, { "code": null, "e": 25528, "s": 25359, "text": "rowvar : [bool, optional] If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed:" }, { "code": null, "e": 25613, "s": 25528, "text": "bias : Default normalization is False. If bias is True it normalize the data points." }, { "code": null, "e": 25783, "s": 25613, "text": "ddof : If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified." }, { "code": null, "e": 25844, "s": 25783, "text": "fweights : fweight is 1-D array of integer frequency weights" }, { "code": null, "e": 25907, "s": 25844, "text": "aweights : aweight is 1-D array of observation vector weights." }, { "code": null, "e": 25954, "s": 25907, "text": "Returns: It returns ndarray covariance matrix " }, { "code": null, "e": 26281, "s": 25954, "text": "It shows whether and how strongly pairs of variables are related to each other. Correlation takes values between -1 to +1, wherein values close to +1 represents strong positive correlation and values close to -1 represents strong negative correlation. It gives the direction and strength of the relationship between variables." }, { "code": null, "e": 26301, "s": 26281, "text": "Correlation Matrix:" }, { "code": null, "e": 26618, "s": 26301, "text": "It is basically a covariance matrix. Also known as the auto-covariance matrix, dispersion matrix, variance matrix, or variance-covariance matrix. It is a matrix in which i-j position defines the correlation between the ith and jth parameter of the given data-set. It is calculated using numpy‘s corrcoeff() method. " }, { "code": null, "e": 26627, "s": 26618, "text": "Syntax: " }, { "code": null, "e": 26701, "s": 26627, "text": " numpy.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>)" }, { "code": null, "e": 26894, "s": 26701, "text": "x : A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below." }, { "code": null, "e": 26983, "s": 26894, "text": "y, optional: An additional set of variables and observations. y has the same shape as x." }, { "code": null, "e": 27207, "s": 26983, "text": "rowvar : If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations." }, { "code": null, "e": 27224, "s": 27207, "text": "Returns: ndarray" }, { "code": null, "e": 27684, "s": 27224, "text": "Covariance tells us if two random variables are +ve or -ve related it doesn’t tell us by how much.Covariance is variant to arithmetic changes eg: if we multiply x by 10 or divide by 10 then the result will change, this is not true for correlation where the results remain unchanged by such operations.The output of covariance is difficult to compare as the values can range from – infinity to +infinity. While output values of correlation ranges from 0 to 1." }, { "code": null, "e": 27783, "s": 27684, "text": "Covariance tells us if two random variables are +ve or -ve related it doesn’t tell us by how much." }, { "code": null, "e": 27987, "s": 27783, "text": "Covariance is variant to arithmetic changes eg: if we multiply x by 10 or divide by 10 then the result will change, this is not true for correlation where the results remain unchanged by such operations." }, { "code": null, "e": 28146, "s": 27987, "text": "The output of covariance is difficult to compare as the values can range from – infinity to +infinity. While output values of correlation ranges from 0 to 1." }, { "code": null, "e": 28275, "s": 28146, "text": "Correlation is just normalized Covariance refer to the formula below. where are the standard deviation of x and y respectively. " }, { "code": null, "e": 28342, "s": 28275, "text": "Python Program to convert Covariance matrix to Correlation matrix " }, { "code": null, "e": 28494, "s": 28342, "text": "To solve this problem we have selected the iris data because to compute covariance we need data and it’s better if we use a real word example dataset. " }, { "code": null, "e": 28530, "s": 28494, "text": "Loading and displaying the dataset " }, { "code": null, "e": 28538, "s": 28530, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd # loading in the iris dataset for demo purposes dataset = pd.read_csv(\"iris.csv\") dataset.head()", "e": 28673, "s": 28538, "text": null }, { "code": null, "e": 28726, "s": 28673, "text": "In this example we won’t be using the target column " }, { "code": null, "e": 28734, "s": 28726, "text": "Python3" }, { "code": "data = dataset.iloc[:, :-1].values", "e": 28769, "s": 28734, "text": null }, { "code": null, "e": 28811, "s": 28769, "text": "Program to implement covariance matrix: " }, { "code": null, "e": 28819, "s": 28811, "text": "Python3" }, { "code": "# calculates the covariance between x and ydef calcCov(x, y): mean_x, mean_y = x.mean(), y.mean() n = len(x) return sum((x - mean_x) * (y - mean_y)) / n # calculates the Covariance matrixdef covMat(data): # get the rows and cols rows, cols = data.shape # the covariance matroix has a shape of n_features x n_features # n_featurs = cols - 1 (not including the target column) cov_mat = np.zeros((cols, cols)) for i in range(cols): for j in range(cols): # store the value in the matrix cov_mat[i][j] = calcCov(data[:, i], data[:, j]) return cov_mat covMat(data)", "e": 29448, "s": 28819, "text": null }, { "code": null, "e": 29458, "s": 29448, "text": "Output : " }, { "code": null, "e": 29480, "s": 29458, "text": "Numpy cov() output : " }, { "code": null, "e": 29488, "s": 29480, "text": "Python3" }, { "code": "np.cov(data,rowvar=False)", "e": 29514, "s": 29488, "text": null }, { "code": null, "e": 29632, "s": 29514, "text": " note : the rowVars needs to be make false otherwise it will take the rows as features and columns and observations. " }, { "code": null, "e": 29642, "s": 29632, "text": "Output: " }, { "code": null, "e": 29668, "s": 29642, "text": "Calculating Correlation: " }, { "code": null, "e": 29749, "s": 29668, "text": "In this function, we are going to convert the Covariance matrix to correlation. " }, { "code": null, "e": 29757, "s": 29749, "text": "Python3" }, { "code": "# Now calculating Correlation using our Covariance function (covMat()) def corrMat(data): rows, cols = data.shape corr_mat = np.zeros((cols, cols)) for i in range(cols): for j in range(cols): x, y = data[:, i], data[:, j] # not here that we are just normalizing the covariance matrix corr_mat[i][j] = calcCov(x, y) / (x.std() * y.std()) return corr_mat corrMat(data) ", "e": 30189, "s": 29757, "text": null }, { "code": null, "e": 30198, "s": 30189, "text": "Output: " }, { "code": null, "e": 30268, "s": 30198, "text": "The corrcoef() in numpy can also be used to compute the correlation. " }, { "code": null, "e": 30276, "s": 30268, "text": "Python3" }, { "code": "np.corrcoef(data,rowvar=False)", "e": 30307, "s": 30276, "text": null }, { "code": null, "e": 30317, "s": 30307, "text": "Output: " }, { "code": null, "e": 30336, "s": 30319, "text": "surinderdawra388" }, { "code": null, "e": 30356, "s": 30336, "text": "abhishek0719kadiyan" }, { "code": null, "e": 30369, "s": 30356, "text": "Python-numpy" }, { "code": null, "e": 30376, "s": 30369, "text": "Python" }, { "code": null, "e": 30474, "s": 30376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30506, "s": 30474, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30562, "s": 30506, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30604, "s": 30562, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30646, "s": 30604, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30668, "s": 30646, "text": "Defaultdict in Python" }, { "code": null, "e": 30699, "s": 30668, "text": "Python | os.path.join() method" }, { "code": null, "e": 30738, "s": 30699, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30793, "s": 30738, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 30822, "s": 30793, "text": "Create a directory in Python" } ]
XAML - ProgressRing
A ProgressRing is a control that indicates an ongoing operation. The typical visual appearance is a ring-shaped "spinner" that cycles an animation as the progress continues. An important point here is that WPF projects do not support ProgressRing. So for this control, we will work on Windows Store App. The hierarchical inheritance of ProgressRing class is as follows − IsActive Gets or sets a value that indicates whether the ProgressRing is showing progress. IsActiveProperty Identifies the IsActive dependency property. TemplateSettings Gets an object that provides calculated values that can be referenced as TemplateBinding sources when defining templates for a ProgressRing control. ManipulationCompleted Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement) ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement) ManipulationInertiaStarting Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement) ManipulationStarted Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement) ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement) ValueChanged Occurs when the range value changes. (Inherited from RangeBase) OnManipulationCompleted Called before the ManipulationCompleted event occurs. (Inherited from Control) OnManipulationDelta Called before the ManipulationDelta event occurs. (Inherited from Control) OnManipulationInertiaStarting Called before the ManipulationInertiaStarting event occurs. (Inherited from Control) OnManipulationStarted Called before the ManipulationStarted event occurs. (Inherited from Control) OnManipulationStarting Called before the ManipulationStarting event occurs. (Inherited from Control) OnMaximumChanged Called when the Maximum property changes. (Inherited from RangeBase) OnMinimumChanged Called when the Minimum property changes. (Inherited from RangeBase) The following example shows how to use ProgressRing with ToggleSwitch. Here is the code in XAML to create and initialize a ProgressRing and a ToggleSwitch − <Page x:Class = "ProgressRing.MainPage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "using:ProgressRing" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable = "d"> <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> <StackPanel Orientation = "Horizontal" Margin = "342,0,-342,0"> <ProgressRing x:Name = "progress1"/> <ToggleSwitch Header = "ProgressRing Example" OffContent = "Do work" OnContent = "Working" Toggled = "ToggleSwitch_Toggled" Margin = "0,348,0,347"/> </StackPanel> </Grid> </Page> Given below is the implementation in C# for Toggled event − using System; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; namespace ProgressRing { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e) { ToggleSwitch toggleSwitch = sender as ToggleSwitch; if (toggleSwitch != null) { if (toggleSwitch.IsOn == true) { progress1.IsActive = true; progress1.Visibility = Visibility.Visible; } else { progress1.IsActive = false; progress1.Visibility = Visibility.Collapsed; } } } } } When you compile and execute the above code, it produces the following output − We recommend you to execute the above example code and experiment with some other properties and events in Windows App. Print Add Notes Bookmark this page
[ { "code": null, "e": 2294, "s": 1923, "text": "A ProgressRing is a control that indicates an ongoing operation. The typical visual appearance is a ring-shaped \"spinner\" that cycles an animation as the progress continues. An important point here is that WPF projects do not support ProgressRing. So for this control, we will work on Windows Store App. The hierarchical inheritance of ProgressRing class is as follows −" }, { "code": null, "e": 2303, "s": 2294, "text": "IsActive" }, { "code": null, "e": 2385, "s": 2303, "text": "Gets or sets a value that indicates whether the ProgressRing is showing progress." }, { "code": null, "e": 2402, "s": 2385, "text": "IsActiveProperty" }, { "code": null, "e": 2447, "s": 2402, "text": "Identifies the IsActive dependency property." }, { "code": null, "e": 2464, "s": 2447, "text": "TemplateSettings" }, { "code": null, "e": 2613, "s": 2464, "text": "Gets an object that provides calculated values that can be referenced as TemplateBinding sources when defining templates for a ProgressRing control." }, { "code": null, "e": 2635, "s": 2613, "text": "ManipulationCompleted" }, { "code": null, "e": 2719, "s": 2635, "text": "Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)" }, { "code": null, "e": 2737, "s": 2719, "text": "ManipulationDelta" }, { "code": null, "e": 2833, "s": 2737, "text": "Occurs when the input device changes position during a manipulation. (Inherited from UIElement)" }, { "code": null, "e": 2861, "s": 2833, "text": "ManipulationInertiaStarting" }, { "code": null, "e": 2999, "s": 2861, "text": "Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)" }, { "code": null, "e": 3019, "s": 2999, "text": "ManipulationStarted" }, { "code": null, "e": 3114, "s": 3019, "text": "Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)" }, { "code": null, "e": 3135, "s": 3114, "text": "ManipulationStarting" }, { "code": null, "e": 3219, "s": 3135, "text": "Occurs when the manipulation processor is first created. (Inherited from UIElement)" }, { "code": null, "e": 3232, "s": 3219, "text": "ValueChanged" }, { "code": null, "e": 3296, "s": 3232, "text": "Occurs when the range value changes. (Inherited from RangeBase)" }, { "code": null, "e": 3320, "s": 3296, "text": "OnManipulationCompleted" }, { "code": null, "e": 3399, "s": 3320, "text": "Called before the ManipulationCompleted event occurs. (Inherited from Control)" }, { "code": null, "e": 3419, "s": 3399, "text": "OnManipulationDelta" }, { "code": null, "e": 3494, "s": 3419, "text": "Called before the ManipulationDelta event occurs. (Inherited from Control)" }, { "code": null, "e": 3524, "s": 3494, "text": "OnManipulationInertiaStarting" }, { "code": null, "e": 3609, "s": 3524, "text": "Called before the ManipulationInertiaStarting event occurs. (Inherited from Control)" }, { "code": null, "e": 3631, "s": 3609, "text": "OnManipulationStarted" }, { "code": null, "e": 3708, "s": 3631, "text": "Called before the ManipulationStarted event occurs. (Inherited from Control)" }, { "code": null, "e": 3731, "s": 3708, "text": "OnManipulationStarting" }, { "code": null, "e": 3809, "s": 3731, "text": "Called before the ManipulationStarting event occurs. (Inherited from Control)" }, { "code": null, "e": 3826, "s": 3809, "text": "OnMaximumChanged" }, { "code": null, "e": 3895, "s": 3826, "text": "Called when the Maximum property changes. (Inherited from RangeBase)" }, { "code": null, "e": 3912, "s": 3895, "text": "OnMinimumChanged" }, { "code": null, "e": 3981, "s": 3912, "text": "Called when the Minimum property changes. (Inherited from RangeBase)" }, { "code": null, "e": 4138, "s": 3981, "text": "The following example shows how to use ProgressRing with ToggleSwitch. Here is the code in XAML to create and initialize a ProgressRing and a ToggleSwitch −" }, { "code": null, "e": 4941, "s": 4138, "text": "<Page x:Class = \"ProgressRing.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:local = \"using:ProgressRing\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n mc:Ignorable = \"d\">\n\t\n <Grid Background = \"{ThemeResource ApplicationPageBackgroundThemeBrush}\"> \n <StackPanel Orientation = \"Horizontal\" Margin = \"342,0,-342,0\"> \n <ProgressRing x:Name = \"progress1\"/> \n <ToggleSwitch Header = \"ProgressRing Example\" OffContent = \"Do work\"\n OnContent = \"Working\" Toggled = \"ToggleSwitch_Toggled\" \n Margin = \"0,348,0,347\"/> \n </StackPanel>\n </Grid> \n\t\n</Page>" }, { "code": null, "e": 5001, "s": 4941, "text": "Given below is the implementation in C# for Toggled event −" }, { "code": null, "e": 5881, "s": 5001, "text": "using System; \nusing System.Runtime.InteropServices.WindowsRuntime; \nusing Windows.Foundation; \nusing Windows.Foundation.Collections; \nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Controls.Primitives;\n \nnamespace ProgressRing { \n public sealed partial class MainPage : Page {\n public MainPage() {\n this.InitializeComponent(); \n } \n private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e) { \n ToggleSwitch toggleSwitch = sender as ToggleSwitch; \n\t\t\t\n if (toggleSwitch != null) { \n if (toggleSwitch.IsOn == true) { \n progress1.IsActive = true; \n progress1.Visibility = Visibility.Visible; \n } else {\n progress1.IsActive = false; \n progress1.Visibility = Visibility.Collapsed; \n }\n }\n }\n }\n}" }, { "code": null, "e": 5961, "s": 5881, "text": "When you compile and execute the above code, it produces the following output −" }, { "code": null, "e": 6081, "s": 5961, "text": "We recommend you to execute the above example code and experiment with some other properties and events in Windows App." }, { "code": null, "e": 6088, "s": 6081, "text": " Print" }, { "code": null, "e": 6099, "s": 6088, "text": " Add Notes" } ]
Ensemble Learning case study: Running XGBoost on Google Colab free GPU | by Gabriel Signoretti | Towards Data Science
This article is the second part of a case study where we are exploring the 1994 census income dataset. In the first part, we took a deeper look at the dataset, compared the performance of some ensemble methods and then explored some tools to help with the model interpretability. In this second part, we will explore a technique called Gradient Boosting and the Google Colaboratory, which is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Gradient Boosting is a type of ensemble method, much like Bagging and Pasting that we discussed last time. However, Boosting differs from the previously mentioned methods in relation to how it does such a combination of models. It uses techniques to combine several weak learners into one strong learner. While the other ensemble methods rely on the simultaneous construction of several isolated base learners that are then used to make the prediction, Boosting algorithms rely on a sequential process, where each model attempts to correct the mistakes of previous models. This leads to a major efficiency drawback, as the models are created one at a time and depend on the results obtained by previous iterations Gradient Boosting employs the gradient descent algorithm to minimize errors in sequential models. So, in essence, it is an optimization problem where the objective is to minimize the error (loss) function. XGBoost (eXtreme Gradient Boosting), in its turn, is an optimized implementation of the Gradient Boosting algorithm. It features (among other enhancements): parallelized tree building, cache-aware access, sparsity awareness, regularization (both L1 and L2), weighted quantile sketch. The library has become one of the go-to solutions for winning many data science competitions in recent years. XGBoost hyperparameters were divided into 3 categories by the original authors: General Parameters: hyperparameters that control the overall functioning of the algorithm; Booster Parameters: hyperparameters that control the individual boosters (tree or regression) at each step of the algorithm; Learning Task Parameters: hyperparameters that configure the optimization to be performed; One of XGBoost greatest advantages is the amount of customization available. To check the full list of available hyperparameters (it is quite extensive), I highly recommend you to check out the project documentation page. XGBoost provides a scikit-learn compatible API and some parameters have slightly different names, but they work the same as in the regular library API. We will briefly go over some of the hyperparameters that we will tune in our case study to get a better understanding of them: booster: allows us to choose each booster to use: gbtree, for tree-based models, or gblinear, for linear models. objective: is part of the Learning Task hyperparameters, and it specifies the learning task (regression, classification, ranking, etc) and function to be used in the optimization process. tree_method: we will use the option “gpu_exact” to run on the GPU eval_metric: the metric used to evaluate performance on the training data. We can pass multiple metrics in the format of a python list and, thus, we will use “error” (the binary classification error) and “auc” in the case study. learning_rate (eta): it scales newly added weights after each step of tree boosting. This technique is called “shrinkage” and is responsible for reducing the influence of each individual tree, leaving space for future trees to improve the model. Generally, learning_rates lower than 0.1 are found to yield better generalization errors. gamma: a tree node is split when the resulting split generates a positive reduction of the loss function. The gamma parameter specifies the minimum reduction required to perform such splits. Its value depends on the loss function being used. max_depth: limits the maximum depth that the trees are allowed to grow. Larger trees are prone to overfitting. colsample_bytree: sets the fraction of features (dataset columns) to be randomly used when fitting each individual tree. subsample: sets the fraction of observations (dataset rows) to be randomly used when fitting each individual tree. reg_alpha: controls the L1 regularization. Since L1 regularization tends to pull the weights to zero, it is more recommended when using linear boosters or data with high dimensionality. reg_lambda: controls L2 regularization. Since L2 regularization encourages lower weights (but not necessarily 0), it can be used for tree boosters. n_estimators: the number of trees to fit As you can see, there are multiple hyperparameters to tune, and the ones presented above are not even close to the whole of it. First, we are going to fit an out-of-the-box XGBoost classifier to get a basic understanding of the model’s performance, meaning that we are not going to tune most of the model’s parameters. The XGBoost library implements two main APIs for model training: the default Learning API, which gives more fine control over the model; and the Scikit-Learn API, a scikit-learn wrapper that enables us to use the XGBoost model in conjunction with scikit-learn objects such as Pipelines and RandomizedSearchCV. We are going to be primarily focusing on the Scikit-Learn API for now. This API provides a method to assess the model’s performance variation with the incremental addition of new trees. To do so we must provide the following additional arguments to the fit method: eval_set, the evaluation sets to be used (usually the train and test sets), and eval_metric, the metrics to be used when performing the evaluation. If these two arguments are provided, the evaluation results will be available by the eval_results attribute of the fitted model. But enough talk, let’s finally show some code! As this article is the part 2 of the case study, we are not going to be discussing the development of the preprocessing pipeline steps, as that was already covered in the part 1 of the series. To begin, we load the dataset, transform it into the X feature matrix and the y target vector, perform the preprocessing steps and, finally, split the data into training and test sets. This process is highlighted on the code below: # load the datasetincome = pd.read_csv("income.csv")# Create the X feature matrix and the y target vectorX = income.drop(labels=["high_income", 'fnlwgt'], axis=1)y = income["high_income"]# the only step necessary to be done outside of pipeline# convert the target column to categoricalcol = pd.Categorical(y)y = pd.Series(col.codes)# validate the preprocessing pipeline by passing data through itclean_X = preprocessing_pipeline.fit_transform(X)clean_X_df = pd.DataFrame(clean_X, columns=X.columns)# split the clean_X into train and test setsX_train, X_test, y_train, y_test = train_test_split(clean_X, y, test_size=0.20, random_state=seed, shuffle=True, stratify=y) With this, we are finally ready to train our first XGBoost classifier! To get a better sense of the model evolution, we will set the n_estimators hyperparameter to 500. The model training is highlighted on the code snippet below: import timefrom xgboost import XGBClassifier# create a default XGBoost classifiermodel = XGBClassifier(n_estimators=500, random_state=seed)# define the eval set and metriceval_set = [(X_train, y_train), (X_test, y_test)]eval_metric = ["auc","error"]# fit the model%time model.fit(X_train, y_train, eval_metric=eval_metric, eval_set=eval_set, verbose=False) The %time jupyter magic command returns the time execution of a Python statement or expression. In this case, the training took 11.2 seconds to be completed, not bad for a start. Then we can measure the model performance by making some predictions: # final model assessmentpred_test = model.predict(X_test)pred_train = model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('Classification Report:')print(classification_report(y_test,pred_test)) The default model already gave us a better test accuracy than the tunned random forest from the last article! Let’s see how the model behaved with the incremental addition of new estimators: # retrieve performance metricsresults = model.evals_result()epochs = len(results['validation_0']['error'])x_axis = range(0, epochs)fig, ax = plt.subplots(1, 2, figsize=(15,5))# plot aucax[0].plot(x_axis, results['validation_0']['auc'], label='Train')ax[0].plot(x_axis, results['validation_1']['auc'], label='Test')ax[0].legend()ax[0].set_title('XGBoost AUC-ROC')ax[0].set_ylabel('AUC-ROC')ax[0].set_xlabel('N estimators')# plot classification errorax[1].plot(x_axis, results['validation_0']['error'], label='Train')ax[1].plot(x_axis, results['validation_1']['error'], label='Test')ax[1].legend()ax[1].set_title('XGBoost Classification Error')ax[1].set_ylabel('Classification Error')ax[1].set_xlabel('N estimators')plt.show()plt.tight_layout() Well, it looks like our model is performing fine until about 300 estimators, then the error on the train set continues to drop while the error on the test set more or less remains stable. That might be a sign of overfitting! One way to avoid this is by using the early_stopping_rounds parameter to stop execution once no improvement is observed after a specified number of rounds. So, it looks like our default model performed quite well with its out-of-the-box configuration. However, we can still squeeze more out of it by tunning some hyperparameters, but how should we do that? Imagine if we wanted to tune 7 hyperparameters and test 3 different values for each of them. Tunning that by hand is just out of the question due to the massive number of different possible combinations. If we then decide to use a naive grid search to do the job, we would end um with 3ˆ7=2187 different models to fit! In that case, if we consider the time it took to fit our default model (11,2 seconds) as a general rule of thumb, it would take around 408 minutes or 6,8 hours to train! Therefore, as we did last time, we will be using a randomized search to tune the parameters, it might not find the best solution but it will find a “good enough” one in a reasonable amount of time. Using scikit-learn’s RandomizedSeaarchCV we configured the search space to include the learning_rate, colsample_bytree, subsample, max_depth, n_estimators, reg_lambda, and gamma hyperparameters. We also limited the number of iterations to be 50 so that the experiment would not take too long to run. The process of configuring and fitting this model is shown below: # create a default XGBoost classifiermodel = XGBClassifier( random_state=seed, eval_metric=["error", "auc"])# Create the grid search parameter grid and scoring funcitonsparam_grid = { "learning_rate": [0.1, 0.01], "colsample_bytree": [0.6, 0.8, 1.0], "subsample": [0.6, 0.8, 1.0], "max_depth": [2, 3, 4], "n_estimators": [100, 200, 300, 400], "reg_lambda": [1, 1.5, 2], "gamma": [0, 0.1, 0.3],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search objectn_iter=50grid = RandomizedSearchCV( estimator=model, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit="AUC",)# fit grid search%time best_model = grid.fit(X_train,y_train) Again we use the %time command to measure the execution speed of the training process. This time it took approximately 20 minutes and 19 seconds to return the best model after the execution of the 50 rounds. You can now have an idea of how this process can become really time-consuming quite fast if we used a larger search space and a bigger number of iterations. We can then check the best model AUC score and hyperparameters: print(f'Best score: {best_model.best_score_}')print(f'Best model: {best_model.best_params_}') And finally, we can make some predictions to assess the model overall performance: pred_test = best_model.predict(X_test)pred_train = best_model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\nClassification Report:')print(classification_report(y_test,pred_test)) It looks like we got a little improvement on both train and test accuracies, but not that much to be honest. We finally arrived at the section you were probably waiting for! We will use the Google Colaboratory free GPU access to hopefully speed up the process of fitting the XGBoost model. But how do you configure your workspace? It’s quite a simple two-step process: first, you need to access edit > notebook preferences, then, on the hardware accelerator dropdown menu select GPU and press Save. That’s it! your runtime will be restarted and then will be ready to go. On the XGBoost side, the only thing that changes is the inclusion of the tree_method hyperparameter while creating the model, everything else for the randomized search remains the same! The change on the model creatin can be seen on the code snippet below: model = XGBClassifier( tree_method = "gpu_hist", random_state=seed, eval_metric=["error", "auc"]) After retraining the model with this configuration, we verified that it took around 18 minutes to complete the whole process. That might not seem like a great improvement, but it was around 10% faster than the previous run! The gains of using the GPU can be more easily seen on larger datasets, where the parallelization overhead would be more compensated by the parallelization speed gains. After that, we repeated the process to check the best model parameters and performance. The results are shown in the figure below: We can see another slight increase in training and test accuracies, that’s always great, isn’t it!? So, to help make more sense of the XGBoost model predictions, we can use any of the techniques presented in the last part of this series: inspect and plot the feature_importances_ attribute of the fitted model; use the ELI5 feature weights table and prediction explanations; and, finally, use SHAP plots. However, the XGBoost library has another trick up its sleeve and provides a built-in plotting API for generating plots of feature importances and representations of individual trees used in the boosting! To plot the global feature importance we can use the plot_importances method. It is possible to specify one of three metrics to calculate the individual feature scores: Feature Weights: the score is calculated based on the number of times the feature appears in the trees Gain: the score is calculated based on the average gain of splits which use the feature Coverage: the score is calculated based on the average coverage (number of samples affected by the split) of splits which use the feature The three examples are shown in the code below: # store the winning model in a new variablexgc = best_model_gpu.best_estimator_# saving the feature names to the modelxgc.get_booster().feature_names = X.columns.to_list()# Create the feature importances plotfig, ax = plt.subplots(1, 3, figsize=(15,5))# plot importances with feature weightxgb.plot_importance( booster=xgc, importance_type='weight', title='Feature Weight', show_values=False, height=0.5, ax=ax[0],)# plot importances with split mean gainxgb.plot_importance( booster=xgc, importance_type='gain', title='Split Mean Gain', show_values=False, height=0.5, ax=ax[1])# plot importances with sample coveragexgb.plot_importance( xgc, importance_type='cover', title='Sample Coverage', show_values=False, height=0.5, ax=ax[2])plt.tight_layout()plt.show() And, finally, to plot a specific tree we can use the plot_tree method as shown below: # Create the feature importances plotfig, ax = plt.subplots(figsize=(20,20))# plot a decision tree from the boosterxgb.plot_tree(booster=xgc, num_trees=0, ax=ax, rankdir='LR')plt.tight_layout()plt.show() With this, we make it to the end of this two-part series on ensemble learning, I hope it was enjoyable and maybe a little bit useful! Thanks for reading! leave a comment with your thoughts below.
[ { "code": null, "e": 327, "s": 47, "text": "This article is the second part of a case study where we are exploring the 1994 census income dataset. In the first part, we took a deeper look at the dataset, compared the performance of some ensemble methods and then explored some tools to help with the model interpretability." }, { "code": null, "e": 530, "s": 327, "text": "In this second part, we will explore a technique called Gradient Boosting and the Google Colaboratory, which is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud." }, { "code": null, "e": 835, "s": 530, "text": "Gradient Boosting is a type of ensemble method, much like Bagging and Pasting that we discussed last time. However, Boosting differs from the previously mentioned methods in relation to how it does such a combination of models. It uses techniques to combine several weak learners into one strong learner." }, { "code": null, "e": 1244, "s": 835, "text": "While the other ensemble methods rely on the simultaneous construction of several isolated base learners that are then used to make the prediction, Boosting algorithms rely on a sequential process, where each model attempts to correct the mistakes of previous models. This leads to a major efficiency drawback, as the models are created one at a time and depend on the results obtained by previous iterations" }, { "code": null, "e": 1450, "s": 1244, "text": "Gradient Boosting employs the gradient descent algorithm to minimize errors in sequential models. So, in essence, it is an optimization problem where the objective is to minimize the error (loss) function." }, { "code": null, "e": 1844, "s": 1450, "text": "XGBoost (eXtreme Gradient Boosting), in its turn, is an optimized implementation of the Gradient Boosting algorithm. It features (among other enhancements): parallelized tree building, cache-aware access, sparsity awareness, regularization (both L1 and L2), weighted quantile sketch. The library has become one of the go-to solutions for winning many data science competitions in recent years." }, { "code": null, "e": 1924, "s": 1844, "text": "XGBoost hyperparameters were divided into 3 categories by the original authors:" }, { "code": null, "e": 2015, "s": 1924, "text": "General Parameters: hyperparameters that control the overall functioning of the algorithm;" }, { "code": null, "e": 2140, "s": 2015, "text": "Booster Parameters: hyperparameters that control the individual boosters (tree or regression) at each step of the algorithm;" }, { "code": null, "e": 2231, "s": 2140, "text": "Learning Task Parameters: hyperparameters that configure the optimization to be performed;" }, { "code": null, "e": 2453, "s": 2231, "text": "One of XGBoost greatest advantages is the amount of customization available. To check the full list of available hyperparameters (it is quite extensive), I highly recommend you to check out the project documentation page." }, { "code": null, "e": 2605, "s": 2453, "text": "XGBoost provides a scikit-learn compatible API and some parameters have slightly different names, but they work the same as in the regular library API." }, { "code": null, "e": 2732, "s": 2605, "text": "We will briefly go over some of the hyperparameters that we will tune in our case study to get a better understanding of them:" }, { "code": null, "e": 2845, "s": 2732, "text": "booster: allows us to choose each booster to use: gbtree, for tree-based models, or gblinear, for linear models." }, { "code": null, "e": 3033, "s": 2845, "text": "objective: is part of the Learning Task hyperparameters, and it specifies the learning task (regression, classification, ranking, etc) and function to be used in the optimization process." }, { "code": null, "e": 3099, "s": 3033, "text": "tree_method: we will use the option “gpu_exact” to run on the GPU" }, { "code": null, "e": 3328, "s": 3099, "text": "eval_metric: the metric used to evaluate performance on the training data. We can pass multiple metrics in the format of a python list and, thus, we will use “error” (the binary classification error) and “auc” in the case study." }, { "code": null, "e": 3664, "s": 3328, "text": "learning_rate (eta): it scales newly added weights after each step of tree boosting. This technique is called “shrinkage” and is responsible for reducing the influence of each individual tree, leaving space for future trees to improve the model. Generally, learning_rates lower than 0.1 are found to yield better generalization errors." }, { "code": null, "e": 3906, "s": 3664, "text": "gamma: a tree node is split when the resulting split generates a positive reduction of the loss function. The gamma parameter specifies the minimum reduction required to perform such splits. Its value depends on the loss function being used." }, { "code": null, "e": 4017, "s": 3906, "text": "max_depth: limits the maximum depth that the trees are allowed to grow. Larger trees are prone to overfitting." }, { "code": null, "e": 4138, "s": 4017, "text": "colsample_bytree: sets the fraction of features (dataset columns) to be randomly used when fitting each individual tree." }, { "code": null, "e": 4253, "s": 4138, "text": "subsample: sets the fraction of observations (dataset rows) to be randomly used when fitting each individual tree." }, { "code": null, "e": 4439, "s": 4253, "text": "reg_alpha: controls the L1 regularization. Since L1 regularization tends to pull the weights to zero, it is more recommended when using linear boosters or data with high dimensionality." }, { "code": null, "e": 4587, "s": 4439, "text": "reg_lambda: controls L2 regularization. Since L2 regularization encourages lower weights (but not necessarily 0), it can be used for tree boosters." }, { "code": null, "e": 4628, "s": 4587, "text": "n_estimators: the number of trees to fit" }, { "code": null, "e": 4756, "s": 4628, "text": "As you can see, there are multiple hyperparameters to tune, and the ones presented above are not even close to the whole of it." }, { "code": null, "e": 4947, "s": 4756, "text": "First, we are going to fit an out-of-the-box XGBoost classifier to get a basic understanding of the model’s performance, meaning that we are not going to tune most of the model’s parameters." }, { "code": null, "e": 5257, "s": 4947, "text": "The XGBoost library implements two main APIs for model training: the default Learning API, which gives more fine control over the model; and the Scikit-Learn API, a scikit-learn wrapper that enables us to use the XGBoost model in conjunction with scikit-learn objects such as Pipelines and RandomizedSearchCV." }, { "code": null, "e": 5799, "s": 5257, "text": "We are going to be primarily focusing on the Scikit-Learn API for now. This API provides a method to assess the model’s performance variation with the incremental addition of new trees. To do so we must provide the following additional arguments to the fit method: eval_set, the evaluation sets to be used (usually the train and test sets), and eval_metric, the metrics to be used when performing the evaluation. If these two arguments are provided, the evaluation results will be available by the eval_results attribute of the fitted model." }, { "code": null, "e": 6039, "s": 5799, "text": "But enough talk, let’s finally show some code! As this article is the part 2 of the case study, we are not going to be discussing the development of the preprocessing pipeline steps, as that was already covered in the part 1 of the series." }, { "code": null, "e": 6271, "s": 6039, "text": "To begin, we load the dataset, transform it into the X feature matrix and the y target vector, perform the preprocessing steps and, finally, split the data into training and test sets. This process is highlighted on the code below:" }, { "code": null, "e": 6938, "s": 6271, "text": "# load the datasetincome = pd.read_csv(\"income.csv\")# Create the X feature matrix and the y target vectorX = income.drop(labels=[\"high_income\", 'fnlwgt'], axis=1)y = income[\"high_income\"]# the only step necessary to be done outside of pipeline# convert the target column to categoricalcol = pd.Categorical(y)y = pd.Series(col.codes)# validate the preprocessing pipeline by passing data through itclean_X = preprocessing_pipeline.fit_transform(X)clean_X_df = pd.DataFrame(clean_X, columns=X.columns)# split the clean_X into train and test setsX_train, X_test, y_train, y_test = train_test_split(clean_X, y, test_size=0.20, random_state=seed, shuffle=True, stratify=y)" }, { "code": null, "e": 7168, "s": 6938, "text": "With this, we are finally ready to train our first XGBoost classifier! To get a better sense of the model evolution, we will set the n_estimators hyperparameter to 500. The model training is highlighted on the code snippet below:" }, { "code": null, "e": 7525, "s": 7168, "text": "import timefrom xgboost import XGBClassifier# create a default XGBoost classifiermodel = XGBClassifier(n_estimators=500, random_state=seed)# define the eval set and metriceval_set = [(X_train, y_train), (X_test, y_test)]eval_metric = [\"auc\",\"error\"]# fit the model%time model.fit(X_train, y_train, eval_metric=eval_metric, eval_set=eval_set, verbose=False)" }, { "code": null, "e": 7704, "s": 7525, "text": "The %time jupyter magic command returns the time execution of a Python statement or expression. In this case, the training took 11.2 seconds to be completed, not bad for a start." }, { "code": null, "e": 7774, "s": 7704, "text": "Then we can measure the model performance by making some predictions:" }, { "code": null, "e": 8066, "s": 7774, "text": "# final model assessmentpred_test = model.predict(X_test)pred_train = model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('Classification Report:')print(classification_report(y_test,pred_test))" }, { "code": null, "e": 8257, "s": 8066, "text": "The default model already gave us a better test accuracy than the tunned random forest from the last article! Let’s see how the model behaved with the incremental addition of new estimators:" }, { "code": null, "e": 9000, "s": 8257, "text": "# retrieve performance metricsresults = model.evals_result()epochs = len(results['validation_0']['error'])x_axis = range(0, epochs)fig, ax = plt.subplots(1, 2, figsize=(15,5))# plot aucax[0].plot(x_axis, results['validation_0']['auc'], label='Train')ax[0].plot(x_axis, results['validation_1']['auc'], label='Test')ax[0].legend()ax[0].set_title('XGBoost AUC-ROC')ax[0].set_ylabel('AUC-ROC')ax[0].set_xlabel('N estimators')# plot classification errorax[1].plot(x_axis, results['validation_0']['error'], label='Train')ax[1].plot(x_axis, results['validation_1']['error'], label='Test')ax[1].legend()ax[1].set_title('XGBoost Classification Error')ax[1].set_ylabel('Classification Error')ax[1].set_xlabel('N estimators')plt.show()plt.tight_layout()" }, { "code": null, "e": 9381, "s": 9000, "text": "Well, it looks like our model is performing fine until about 300 estimators, then the error on the train set continues to drop while the error on the test set more or less remains stable. That might be a sign of overfitting! One way to avoid this is by using the early_stopping_rounds parameter to stop execution once no improvement is observed after a specified number of rounds." }, { "code": null, "e": 9582, "s": 9381, "text": "So, it looks like our default model performed quite well with its out-of-the-box configuration. However, we can still squeeze more out of it by tunning some hyperparameters, but how should we do that?" }, { "code": null, "e": 10071, "s": 9582, "text": "Imagine if we wanted to tune 7 hyperparameters and test 3 different values for each of them. Tunning that by hand is just out of the question due to the massive number of different possible combinations. If we then decide to use a naive grid search to do the job, we would end um with 3ˆ7=2187 different models to fit! In that case, if we consider the time it took to fit our default model (11,2 seconds) as a general rule of thumb, it would take around 408 minutes or 6,8 hours to train!" }, { "code": null, "e": 10269, "s": 10071, "text": "Therefore, as we did last time, we will be using a randomized search to tune the parameters, it might not find the best solution but it will find a “good enough” one in a reasonable amount of time." }, { "code": null, "e": 10635, "s": 10269, "text": "Using scikit-learn’s RandomizedSeaarchCV we configured the search space to include the learning_rate, colsample_bytree, subsample, max_depth, n_estimators, reg_lambda, and gamma hyperparameters. We also limited the number of iterations to be 50 so that the experiment would not take too long to run. The process of configuring and fitting this model is shown below:" }, { "code": null, "e": 11501, "s": 10635, "text": "# create a default XGBoost classifiermodel = XGBClassifier( random_state=seed, eval_metric=[\"error\", \"auc\"])# Create the grid search parameter grid and scoring funcitonsparam_grid = { \"learning_rate\": [0.1, 0.01], \"colsample_bytree\": [0.6, 0.8, 1.0], \"subsample\": [0.6, 0.8, 1.0], \"max_depth\": [2, 3, 4], \"n_estimators\": [100, 200, 300, 400], \"reg_lambda\": [1, 1.5, 2], \"gamma\": [0, 0.1, 0.3],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search objectn_iter=50grid = RandomizedSearchCV( estimator=model, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit=\"AUC\",)# fit grid search%time best_model = grid.fit(X_train,y_train)" }, { "code": null, "e": 11866, "s": 11501, "text": "Again we use the %time command to measure the execution speed of the training process. This time it took approximately 20 minutes and 19 seconds to return the best model after the execution of the 50 rounds. You can now have an idea of how this process can become really time-consuming quite fast if we used a larger search space and a bigger number of iterations." }, { "code": null, "e": 11930, "s": 11866, "text": "We can then check the best model AUC score and hyperparameters:" }, { "code": null, "e": 12024, "s": 11930, "text": "print(f'Best score: {best_model.best_score_}')print(f'Best model: {best_model.best_params_}')" }, { "code": null, "e": 12107, "s": 12024, "text": "And finally, we can make some predictions to assess the model overall performance:" }, { "code": null, "e": 12456, "s": 12107, "text": "pred_test = best_model.predict(X_test)pred_train = best_model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('\\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\\nClassification Report:')print(classification_report(y_test,pred_test))" }, { "code": null, "e": 12565, "s": 12456, "text": "It looks like we got a little improvement on both train and test accuracies, but not that much to be honest." }, { "code": null, "e": 12746, "s": 12565, "text": "We finally arrived at the section you were probably waiting for! We will use the Google Colaboratory free GPU access to hopefully speed up the process of fitting the XGBoost model." }, { "code": null, "e": 13027, "s": 12746, "text": "But how do you configure your workspace? It’s quite a simple two-step process: first, you need to access edit > notebook preferences, then, on the hardware accelerator dropdown menu select GPU and press Save. That’s it! your runtime will be restarted and then will be ready to go." }, { "code": null, "e": 13284, "s": 13027, "text": "On the XGBoost side, the only thing that changes is the inclusion of the tree_method hyperparameter while creating the model, everything else for the randomized search remains the same! The change on the model creatin can be seen on the code snippet below:" }, { "code": null, "e": 13393, "s": 13284, "text": "model = XGBClassifier( tree_method = \"gpu_hist\", random_state=seed, eval_metric=[\"error\", \"auc\"])" }, { "code": null, "e": 13785, "s": 13393, "text": "After retraining the model with this configuration, we verified that it took around 18 minutes to complete the whole process. That might not seem like a great improvement, but it was around 10% faster than the previous run! The gains of using the GPU can be more easily seen on larger datasets, where the parallelization overhead would be more compensated by the parallelization speed gains." }, { "code": null, "e": 13916, "s": 13785, "text": "After that, we repeated the process to check the best model parameters and performance. The results are shown in the figure below:" }, { "code": null, "e": 14016, "s": 13916, "text": "We can see another slight increase in training and test accuracies, that’s always great, isn’t it!?" }, { "code": null, "e": 14321, "s": 14016, "text": "So, to help make more sense of the XGBoost model predictions, we can use any of the techniques presented in the last part of this series: inspect and plot the feature_importances_ attribute of the fitted model; use the ELI5 feature weights table and prediction explanations; and, finally, use SHAP plots." }, { "code": null, "e": 14525, "s": 14321, "text": "However, the XGBoost library has another trick up its sleeve and provides a built-in plotting API for generating plots of feature importances and representations of individual trees used in the boosting!" }, { "code": null, "e": 14694, "s": 14525, "text": "To plot the global feature importance we can use the plot_importances method. It is possible to specify one of three metrics to calculate the individual feature scores:" }, { "code": null, "e": 14797, "s": 14694, "text": "Feature Weights: the score is calculated based on the number of times the feature appears in the trees" }, { "code": null, "e": 14885, "s": 14797, "text": "Gain: the score is calculated based on the average gain of splits which use the feature" }, { "code": null, "e": 15023, "s": 14885, "text": "Coverage: the score is calculated based on the average coverage (number of samples affected by the split) of splits which use the feature" }, { "code": null, "e": 15071, "s": 15023, "text": "The three examples are shown in the code below:" }, { "code": null, "e": 15887, "s": 15071, "text": "# store the winning model in a new variablexgc = best_model_gpu.best_estimator_# saving the feature names to the modelxgc.get_booster().feature_names = X.columns.to_list()# Create the feature importances plotfig, ax = plt.subplots(1, 3, figsize=(15,5))# plot importances with feature weightxgb.plot_importance( booster=xgc, importance_type='weight', title='Feature Weight', show_values=False, height=0.5, ax=ax[0],)# plot importances with split mean gainxgb.plot_importance( booster=xgc, importance_type='gain', title='Split Mean Gain', show_values=False, height=0.5, ax=ax[1])# plot importances with sample coveragexgb.plot_importance( xgc, importance_type='cover', title='Sample Coverage', show_values=False, height=0.5, ax=ax[2])plt.tight_layout()plt.show()" }, { "code": null, "e": 15973, "s": 15887, "text": "And, finally, to plot a specific tree we can use the plot_tree method as shown below:" }, { "code": null, "e": 16177, "s": 15973, "text": "# Create the feature importances plotfig, ax = plt.subplots(figsize=(20,20))# plot a decision tree from the boosterxgb.plot_tree(booster=xgc, num_trees=0, ax=ax, rankdir='LR')plt.tight_layout()plt.show()" }, { "code": null, "e": 16311, "s": 16177, "text": "With this, we make it to the end of this two-part series on ensemble learning, I hope it was enjoyable and maybe a little bit useful!" } ]
Getting Started with Apache Kafka and Apache Flume (Import data to HDFS) | by Hadi Fadlallah | Towards Data Science
This article contains a complete guide for Apache Kafka installation, creating Kafka topics, publishing and subscribing Topic messages. In addition, it contains Apache Flume installation guide and how to import Kafka topic messages into HDFS using Apache Flume. Hadoop Version: 3.1.0 Apache Kafka Version: 1.1.1 Apache Flume Version: 1.8.0 Operating System: Ubuntu 16.04 Java Version: Java 8 Apache Kafka requires Java. To ensure that Java is installed first update the Operating System then try to install it: sudo apt-get updatesudo apt-get upgradesudo add-apt-repository -y ppa:webupd8team/javasudo apt-get install oracle-java8-installer Apache Kafka requires Zookeeper service to be installed, because it uses it to maintain its nodes heart beats, its configuration and to elect leaders. sudo apt-get install zookeeperd By default, zookeeper uses port 2181, and it runs automatically once it is installed. To check that Zookeeper is running use telnet command: telnet localhost 2181 When telnet prompt open write “are you okay” command: ruok If everything is okay it will return imok message. Because Kafka is a network application and it may use multiple node, it is better to create a service user with sudo privileges. sudo adduser — system — no-create-home — disabled-password — disabled-login kafkauser First, we need to download Kafka binaries package. wget http://www-eu.apache.org/dist/kafka/1.1.1/kafka_2.11-1.1.1.tgz Now, we need to extract the tgz package. We choose to install Kafka in /opt/kafka directory: sudo tar xvf kafka_2.11–1.1.1.tgz -–directory /opt/kafka -–strip 1 Kafka stores it logs on disk in /tmp directory, it is better to create a new directory to store logs sudo mkdir /var/lib/kafkasudo mkdir /var/lib/kafka/data Now, we need to edit the Kafka server configuration file. sudo gedit /opt/kafka/config/server.properties By default, Kafka does not allow us to delete topics. To be able to delete topics, find the line and change it (if it is not found just add it). delete.topic.enable = true Now, we need to change the log directory: log.dirs=/var/lib/kafka/data In addition, we can adjust the time interval for logs deletion (Kafka deletes logs after a particular time or according to disk size): log.retention.hours=168 # according to timelog.retention.bytes=104857600 # according to disk size We need to give access to kafkauser on the logs directory and kafka installation directory: sudo chown –R kafkauser:nogroup /opt/kafkasudo chown –R kafkauser:nogroup /var/lib/kafka To start Apache Kafka service you can use the following command: sudo /opt/kafka/bin/kafka-server-start.sh /opt/kafka/ config/server.properties You should see the following output, if the server has started successfully: [2018–07–23 21:43:48,279] WARN No meta.properties file under dir /var/lib/kafka/data/meta.properties (kafka.server.BrokerMetadataCheckpoint)[2018–07–23 21:43:48,516] INFO Kafka version : 0.10.0.1 (org.apache.kafka.common.utils.AppInfoParser)[2018–07–23 21:43:48,525] INFO Kafka commitId : a7a17cdec9eaa6c5 (org.apache.kafka.common.utils.AppInfoParser)[2018–07–23 21:43:48,527] INFO [Kafka Server 0], started (kafka.server.KafkaServer)[2018–07–23 21:43:48,555] INFO New leader is 0 (kafka.server.ZookeeperLeaderElector$LeaderChangeListener) To start Kafka as a background process, you can use nohup command sudo nohup /opt/kafka/bin/kafka-server-start.sh /opt/kafka/ config/server.properties /var/lib/kafka/data/kafka.log 2>&1 & You now have a Kafka server running and listening on port 9092. First, we need to create a service unit file in /etc/systemd/system sudo gedit /etc/systemd/system/kafka.service kafka.service [Unit]Description=High-available, distributed message brokerAfter=network.target[Service]User=kafkaExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties[Install]WantedBy=multi-user.target Also, use can forward log to another file so that your syslog is clean ExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties > /opt/kafka/server.log To start the created service, use the following command: sudo systemctl start kafka.service To auto start the service on operating system startup sudo systemctl enable kafka.service You can check your service status using the following command: sudo systemctl status kafka.service To create a Kafka topic we must use kafka-topics.sh script file, and we need to specify the zookeeper address, replication factor, partitioning factor and the topic name: /opt/kafka/bin/kafka-topics.sh — create — zookeeper localhost:2181 — replication-factor 1 — partitions 1 — topic testKafka To list all topics use the following command: /opt/kafka/bin/kafka-topics.sh — list — zookeeper localhost:2181 To publish a message into a topic we must use kafka-console-producer.sh script, and we must to specify the kafka server address and the topic name: /opt/kafka/bin/kafka-console-producer.sh — broker-list localhost:9092 — topic testKafka Then, we need to open another terminal and create a subscriber using kafka-console-consumer.sh script. We need to pass the Kafka server address and the topic name /opt/kafka/bin/kafka-console-consumer.sh — bootstrap-server localhost:9092 — topic test — from-beginning In the first terminal (producer), enter any message (example: Hello!!) it must appear in the second terminal. To open a text file into a Kafka topic, you need to use cat command with a pipeline: cat filename.txt | /opt/kafka/bin/kafka-console-producer.sh — broker-list localhost:9092 — topic testKafka In addition, we can run it on multiple nodes for data redundancy and accidentally failover. Assuming that we have 3 nodes: We need to follow the same steps we have mentioned before with some additions: 1. In /opt/kafka/config/server.properties : a. each node must have a unique broker.id property for node-2 broker.id=1for node-3 broker.id=2 b. change zookeeper.connect value to have such that it lists all zookeeper hosts with port zookeeper.connect=10.0.1.1:2181,10.0.1.2:2181,10.0.1.3:2181 2. We have to change the zookeeper settings. open zoo.cfg file with an editor sudo gedit /etc/zookeeper/conf/zoo.cfg and add the following lines: server.0=10.0.1.1:2888:3888server.1=10.0.1.2:2888:3888server.2=10.0.1.3:2888:3888 3. Restart Zookeeper service sudo systemctl restart zookeeper.service To read messages from a Kafka topic and store them into HDFS we need to install Apache Flume. Which is an application used to store unstructured and semi-structured data into HDFS. First, we need to download apache flume binaries package wget “http://www-eu.apache.org/dist/flume/1.8.0/apache_flume-1.8.0-bin.tar.gz" Now, we need to extract the .gz package. We choose to install Kafka in /opt/kafka directory: sudo tar -xvf apache_flume-1.8.0-bin.tar.gz –-directory /opt/flume –-strip 1 You need to edit “/etc/profile” and “~/.bashrc” file and add the following lines export FLUME_HOME= /opt/flumeexport PATH=$PATH:$FLUME_HOME/bin/ To apply these changes, use source ~/.bashrc command. Once finished, flume agent started automatically. To ensure that flume is installed successfully you can run the following command: flume-ng –help To import data into HDFS, first we need to create a log file in your home directory. gedit ~/access.log Write any data and save it. Create a file “flume.conf” file inside /opt/flume/conf and write the following data into it: flume1.sources = kafka-source-1flume1.channels = hdfs-channel-1flume1.sinks = hdfs-sink-1flume1.sources.kafka-source-1.type = org.apache.flume.source.kafka.KafkaSourceflume1.sources.kafka-source-1.zookeeperConnect = localhost:2181flume1.sources.kafka-source-1.topic = testKafkaflume1.sources.kafka-source-1.batchSize = 100flume1.sources.kafka-source-1.channels = hdfs-channel-1flume1.channels.hdfs-channel-1.type = memoryflume1.sinks.hdfs-sink-1.channel = hdfs-channel-1flume1.sinks.hdfs-sink-1.type = hdfsflume1.sinks.hdfs-sink-1.hdfs.writeFormat = Textflume1.sinks.hdfs-sink-1.hdfs.fileType = DataStreamflume1.sinks.hdfs-sink-1.hdfs.filePrefix = test-eventsflume1.sinks.hdfs-sink-1.hdfs.useLocalTimeStamp = trueflume1.sinks.hdfs-sink-1.hdfs.path = /data/kafka/%{topic}/%y-%m-%dflume1.sinks.hdfs-sink-1.hdfs.rollCount=100flume1.sinks.hdfs-sink-1.hdfs.rollSize=0flume1.channels.hdfs-channel-1.capacity = 10000flume1.channels.hdfs-channel-1.transactionCapacity = 1000 Note that flume1 is the flume agent name. Below, some parameters description: Now, you need to run the flume agent to read data from the Kafka topic and write it to HDFS. flume-ng agent -n flume1 -c conf -f flume.conf — Dflume.root.logger=INFO,console Note: The agent name is specified by -n FileAgent and must match an agent name given in -f conf/flume.conf Data will be now dumped to HDFS location under the following path /tmp/kafka/%{topic}/%y-%m-%d %{topic} >> Kafka topic name %y-%m-%d >> year-month-day [1] “Apache Kafka Official Documentation,” Apache, [Online]. Available: http://kafka.apache.org. [Accessed 15 07 2018]. [2] “Apache Flume Official Documentation,” Apache, [Online]. Available: http://flume.apache.org. [Accessed 20 07 2018]. [3] Sarad, “How to Install Kafka on Ubuntu 16.04,” Hevo, 20 August 2017. [Online]. Available: https://hevodata.com/blog/how-to-install-kafka-on-ubuntu. [Accessed 30 06 2018]. [4] “Kafka setup in 15 minutes,” ETL-Tools, [Online]. Available: http://etl-tools.info/en/examples/kafka-setup-in-15-minutes.htm. [Accessed 25 07 2018]. [5] hitjethva, “Install and Configure Apache Kafka on Ubuntu 16.04,” DevOps, 03 October 2016. [Online]. Available: https://devops.profitbricks.com/tutorials/install-and-configure-apache-kafka-on-ubuntu-1604-1/. [Accessed 15 07 2018]. [6] M. Litwintschik, “Hadoop 3 Single-Node Install Guide,” 19 March 2018. [Online]. Available: http://www.tech.marksblogg.com/hadoop-3-single-node-install-guide.html. [Accessed 10 06 2018]. [7] “Stack overflow Q&A,” Stack overflow, [Online]. Available: https://www.Stackoverflow.com. [8] Gwen Shapira and Jeff Holoman, “Flafka: Apache Flume Meets Apache Kafka for Event Processing,” Cloudera, 06 November 2014. [Online]. Available: http://blog.cloudera.com/blog/2014/11/flafka-apache-flume-meets-apache-kafka-for-event-processing/. [Accessed 15 06 2018]. [9] S. Team, “Apache Flume Installation Tutorial — A beginners guide,” Data Flair, 22 August 2016. [Online]. Available: https://data-flair.training/blogs/apache-flume-installation-tutorial. [Accessed 20 06 2018].
[ { "code": null, "e": 433, "s": 171, "text": "This article contains a complete guide for Apache Kafka installation, creating Kafka topics, publishing and subscribing Topic messages. In addition, it contains Apache Flume installation guide and how to import Kafka topic messages into HDFS using Apache Flume." }, { "code": null, "e": 455, "s": 433, "text": "Hadoop Version: 3.1.0" }, { "code": null, "e": 483, "s": 455, "text": "Apache Kafka Version: 1.1.1" }, { "code": null, "e": 511, "s": 483, "text": "Apache Flume Version: 1.8.0" }, { "code": null, "e": 542, "s": 511, "text": "Operating System: Ubuntu 16.04" }, { "code": null, "e": 563, "s": 542, "text": "Java Version: Java 8" }, { "code": null, "e": 682, "s": 563, "text": "Apache Kafka requires Java. To ensure that Java is installed first update the Operating System then try to install it:" }, { "code": null, "e": 812, "s": 682, "text": "sudo apt-get updatesudo apt-get upgradesudo add-apt-repository -y ppa:webupd8team/javasudo apt-get install oracle-java8-installer" }, { "code": null, "e": 963, "s": 812, "text": "Apache Kafka requires Zookeeper service to be installed, because it uses it to maintain its nodes heart beats, its configuration and to elect leaders." }, { "code": null, "e": 995, "s": 963, "text": "sudo apt-get install zookeeperd" }, { "code": null, "e": 1136, "s": 995, "text": "By default, zookeeper uses port 2181, and it runs automatically once it is installed. To check that Zookeeper is running use telnet command:" }, { "code": null, "e": 1158, "s": 1136, "text": "telnet localhost 2181" }, { "code": null, "e": 1212, "s": 1158, "text": "When telnet prompt open write “are you okay” command:" }, { "code": null, "e": 1217, "s": 1212, "text": "ruok" }, { "code": null, "e": 1268, "s": 1217, "text": "If everything is okay it will return imok message." }, { "code": null, "e": 1397, "s": 1268, "text": "Because Kafka is a network application and it may use multiple node, it is better to create a service user with sudo privileges." }, { "code": null, "e": 1483, "s": 1397, "text": "sudo adduser — system — no-create-home — disabled-password — disabled-login kafkauser" }, { "code": null, "e": 1534, "s": 1483, "text": "First, we need to download Kafka binaries package." }, { "code": null, "e": 1602, "s": 1534, "text": "wget http://www-eu.apache.org/dist/kafka/1.1.1/kafka_2.11-1.1.1.tgz" }, { "code": null, "e": 1695, "s": 1602, "text": "Now, we need to extract the tgz package. We choose to install Kafka in /opt/kafka directory:" }, { "code": null, "e": 1762, "s": 1695, "text": "sudo tar xvf kafka_2.11–1.1.1.tgz -–directory /opt/kafka -–strip 1" }, { "code": null, "e": 1863, "s": 1762, "text": "Kafka stores it logs on disk in /tmp directory, it is better to create a new directory to store logs" }, { "code": null, "e": 1919, "s": 1863, "text": "sudo mkdir /var/lib/kafkasudo mkdir /var/lib/kafka/data" }, { "code": null, "e": 1977, "s": 1919, "text": "Now, we need to edit the Kafka server configuration file." }, { "code": null, "e": 2024, "s": 1977, "text": "sudo gedit /opt/kafka/config/server.properties" }, { "code": null, "e": 2169, "s": 2024, "text": "By default, Kafka does not allow us to delete topics. To be able to delete topics, find the line and change it (if it is not found just add it)." }, { "code": null, "e": 2196, "s": 2169, "text": "delete.topic.enable = true" }, { "code": null, "e": 2238, "s": 2196, "text": "Now, we need to change the log directory:" }, { "code": null, "e": 2267, "s": 2238, "text": "log.dirs=/var/lib/kafka/data" }, { "code": null, "e": 2402, "s": 2267, "text": "In addition, we can adjust the time interval for logs deletion (Kafka deletes logs after a particular time or according to disk size):" }, { "code": null, "e": 2500, "s": 2402, "text": "log.retention.hours=168 # according to timelog.retention.bytes=104857600 # according to disk size" }, { "code": null, "e": 2592, "s": 2500, "text": "We need to give access to kafkauser on the logs directory and kafka installation directory:" }, { "code": null, "e": 2681, "s": 2592, "text": "sudo chown –R kafkauser:nogroup /opt/kafkasudo chown –R kafkauser:nogroup /var/lib/kafka" }, { "code": null, "e": 2746, "s": 2681, "text": "To start Apache Kafka service you can use the following command:" }, { "code": null, "e": 2825, "s": 2746, "text": "sudo /opt/kafka/bin/kafka-server-start.sh /opt/kafka/ config/server.properties" }, { "code": null, "e": 2902, "s": 2825, "text": "You should see the following output, if the server has started successfully:" }, { "code": null, "e": 3442, "s": 2902, "text": "[2018–07–23 21:43:48,279] WARN No meta.properties file under dir /var/lib/kafka/data/meta.properties (kafka.server.BrokerMetadataCheckpoint)[2018–07–23 21:43:48,516] INFO Kafka version : 0.10.0.1 (org.apache.kafka.common.utils.AppInfoParser)[2018–07–23 21:43:48,525] INFO Kafka commitId : a7a17cdec9eaa6c5 (org.apache.kafka.common.utils.AppInfoParser)[2018–07–23 21:43:48,527] INFO [Kafka Server 0], started (kafka.server.KafkaServer)[2018–07–23 21:43:48,555] INFO New leader is 0 (kafka.server.ZookeeperLeaderElector$LeaderChangeListener)" }, { "code": null, "e": 3508, "s": 3442, "text": "To start Kafka as a background process, you can use nohup command" }, { "code": null, "e": 3630, "s": 3508, "text": "sudo nohup /opt/kafka/bin/kafka-server-start.sh /opt/kafka/ config/server.properties /var/lib/kafka/data/kafka.log 2>&1 &" }, { "code": null, "e": 3694, "s": 3630, "text": "You now have a Kafka server running and listening on port 9092." }, { "code": null, "e": 3762, "s": 3694, "text": "First, we need to create a service unit file in /etc/systemd/system" }, { "code": null, "e": 3807, "s": 3762, "text": "sudo gedit /etc/systemd/system/kafka.service" }, { "code": null, "e": 3821, "s": 3807, "text": "kafka.service" }, { "code": null, "e": 4038, "s": 3821, "text": "[Unit]Description=High-available, distributed message brokerAfter=network.target[Service]User=kafkaExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties[Install]WantedBy=multi-user.target" }, { "code": null, "e": 4109, "s": 4038, "text": "Also, use can forward log to another file so that your syslog is clean" }, { "code": null, "e": 4216, "s": 4109, "text": "ExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties > /opt/kafka/server.log" }, { "code": null, "e": 4273, "s": 4216, "text": "To start the created service, use the following command:" }, { "code": null, "e": 4308, "s": 4273, "text": "sudo systemctl start kafka.service" }, { "code": null, "e": 4362, "s": 4308, "text": "To auto start the service on operating system startup" }, { "code": null, "e": 4398, "s": 4362, "text": "sudo systemctl enable kafka.service" }, { "code": null, "e": 4461, "s": 4398, "text": "You can check your service status using the following command:" }, { "code": null, "e": 4497, "s": 4461, "text": "sudo systemctl status kafka.service" }, { "code": null, "e": 4668, "s": 4497, "text": "To create a Kafka topic we must use kafka-topics.sh script file, and we need to specify the zookeeper address, replication factor, partitioning factor and the topic name:" }, { "code": null, "e": 4791, "s": 4668, "text": "/opt/kafka/bin/kafka-topics.sh — create — zookeeper localhost:2181 — replication-factor 1 — partitions 1 — topic testKafka" }, { "code": null, "e": 4837, "s": 4791, "text": "To list all topics use the following command:" }, { "code": null, "e": 4902, "s": 4837, "text": "/opt/kafka/bin/kafka-topics.sh — list — zookeeper localhost:2181" }, { "code": null, "e": 5050, "s": 4902, "text": "To publish a message into a topic we must use kafka-console-producer.sh script, and we must to specify the kafka server address and the topic name:" }, { "code": null, "e": 5138, "s": 5050, "text": "/opt/kafka/bin/kafka-console-producer.sh — broker-list localhost:9092 — topic testKafka" }, { "code": null, "e": 5301, "s": 5138, "text": "Then, we need to open another terminal and create a subscriber using kafka-console-consumer.sh script. We need to pass the Kafka server address and the topic name" }, { "code": null, "e": 5406, "s": 5301, "text": "/opt/kafka/bin/kafka-console-consumer.sh — bootstrap-server localhost:9092 — topic test — from-beginning" }, { "code": null, "e": 5516, "s": 5406, "text": "In the first terminal (producer), enter any message (example: Hello!!) it must appear in the second terminal." }, { "code": null, "e": 5601, "s": 5516, "text": "To open a text file into a Kafka topic, you need to use cat command with a pipeline:" }, { "code": null, "e": 5708, "s": 5601, "text": "cat filename.txt | /opt/kafka/bin/kafka-console-producer.sh — broker-list localhost:9092 — topic testKafka" }, { "code": null, "e": 5831, "s": 5708, "text": "In addition, we can run it on multiple nodes for data redundancy and accidentally failover. Assuming that we have 3 nodes:" }, { "code": null, "e": 5910, "s": 5831, "text": "We need to follow the same steps we have mentioned before with some additions:" }, { "code": null, "e": 5954, "s": 5910, "text": "1. In /opt/kafka/config/server.properties :" }, { "code": null, "e": 6005, "s": 5954, "text": "a. each node must have a unique broker.id property" }, { "code": null, "e": 6050, "s": 6005, "text": "for node-2 broker.id=1for node-3 broker.id=2" }, { "code": null, "e": 6141, "s": 6050, "text": "b. change zookeeper.connect value to have such that it lists all zookeeper hosts with port" }, { "code": null, "e": 6201, "s": 6141, "text": "zookeeper.connect=10.0.1.1:2181,10.0.1.2:2181,10.0.1.3:2181" }, { "code": null, "e": 6347, "s": 6201, "text": "2. We have to change the zookeeper settings. open zoo.cfg file with an editor sudo gedit /etc/zookeeper/conf/zoo.cfg and add the following lines:" }, { "code": null, "e": 6429, "s": 6347, "text": "server.0=10.0.1.1:2888:3888server.1=10.0.1.2:2888:3888server.2=10.0.1.3:2888:3888" }, { "code": null, "e": 6458, "s": 6429, "text": "3. Restart Zookeeper service" }, { "code": null, "e": 6499, "s": 6458, "text": "sudo systemctl restart zookeeper.service" }, { "code": null, "e": 6680, "s": 6499, "text": "To read messages from a Kafka topic and store them into HDFS we need to install Apache Flume. Which is an application used to store unstructured and semi-structured data into HDFS." }, { "code": null, "e": 6737, "s": 6680, "text": "First, we need to download apache flume binaries package" }, { "code": null, "e": 6816, "s": 6737, "text": "wget “http://www-eu.apache.org/dist/flume/1.8.0/apache_flume-1.8.0-bin.tar.gz\"" }, { "code": null, "e": 6909, "s": 6816, "text": "Now, we need to extract the .gz package. We choose to install Kafka in /opt/kafka directory:" }, { "code": null, "e": 6986, "s": 6909, "text": "sudo tar -xvf apache_flume-1.8.0-bin.tar.gz –-directory /opt/flume –-strip 1" }, { "code": null, "e": 7067, "s": 6986, "text": "You need to edit “/etc/profile” and “~/.bashrc” file and add the following lines" }, { "code": null, "e": 7131, "s": 7067, "text": "export FLUME_HOME= /opt/flumeexport PATH=$PATH:$FLUME_HOME/bin/" }, { "code": null, "e": 7185, "s": 7131, "text": "To apply these changes, use source ~/.bashrc command." }, { "code": null, "e": 7317, "s": 7185, "text": "Once finished, flume agent started automatically. To ensure that flume is installed successfully you can run the following command:" }, { "code": null, "e": 7332, "s": 7317, "text": "flume-ng –help" }, { "code": null, "e": 7417, "s": 7332, "text": "To import data into HDFS, first we need to create a log file in your home directory." }, { "code": null, "e": 7436, "s": 7417, "text": "gedit ~/access.log" }, { "code": null, "e": 7464, "s": 7436, "text": "Write any data and save it." }, { "code": null, "e": 7557, "s": 7464, "text": "Create a file “flume.conf” file inside /opt/flume/conf and write the following data into it:" }, { "code": null, "e": 8524, "s": 7557, "text": "flume1.sources = kafka-source-1flume1.channels = hdfs-channel-1flume1.sinks = hdfs-sink-1flume1.sources.kafka-source-1.type = org.apache.flume.source.kafka.KafkaSourceflume1.sources.kafka-source-1.zookeeperConnect = localhost:2181flume1.sources.kafka-source-1.topic = testKafkaflume1.sources.kafka-source-1.batchSize = 100flume1.sources.kafka-source-1.channels = hdfs-channel-1flume1.channels.hdfs-channel-1.type = memoryflume1.sinks.hdfs-sink-1.channel = hdfs-channel-1flume1.sinks.hdfs-sink-1.type = hdfsflume1.sinks.hdfs-sink-1.hdfs.writeFormat = Textflume1.sinks.hdfs-sink-1.hdfs.fileType = DataStreamflume1.sinks.hdfs-sink-1.hdfs.filePrefix = test-eventsflume1.sinks.hdfs-sink-1.hdfs.useLocalTimeStamp = trueflume1.sinks.hdfs-sink-1.hdfs.path = /data/kafka/%{topic}/%y-%m-%dflume1.sinks.hdfs-sink-1.hdfs.rollCount=100flume1.sinks.hdfs-sink-1.hdfs.rollSize=0flume1.channels.hdfs-channel-1.capacity = 10000flume1.channels.hdfs-channel-1.transactionCapacity = 1000" }, { "code": null, "e": 8566, "s": 8524, "text": "Note that flume1 is the flume agent name." }, { "code": null, "e": 8602, "s": 8566, "text": "Below, some parameters description:" }, { "code": null, "e": 8695, "s": 8602, "text": "Now, you need to run the flume agent to read data from the Kafka topic and write it to HDFS." }, { "code": null, "e": 8776, "s": 8695, "text": "flume-ng agent -n flume1 -c conf -f flume.conf — Dflume.root.logger=INFO,console" }, { "code": null, "e": 8883, "s": 8776, "text": "Note: The agent name is specified by -n FileAgent and must match an agent name given in -f conf/flume.conf" }, { "code": null, "e": 8949, "s": 8883, "text": "Data will be now dumped to HDFS location under the following path" }, { "code": null, "e": 8978, "s": 8949, "text": "/tmp/kafka/%{topic}/%y-%m-%d" }, { "code": null, "e": 9007, "s": 8978, "text": "%{topic} >> Kafka topic name" }, { "code": null, "e": 9034, "s": 9007, "text": "%y-%m-%d >> year-month-day" }, { "code": null, "e": 9154, "s": 9034, "text": "[1] “Apache Kafka Official Documentation,” Apache, [Online]. Available: http://kafka.apache.org. [Accessed 15 07 2018]." }, { "code": null, "e": 9274, "s": 9154, "text": "[2] “Apache Flume Official Documentation,” Apache, [Online]. Available: http://flume.apache.org. [Accessed 20 07 2018]." }, { "code": null, "e": 9449, "s": 9274, "text": "[3] Sarad, “How to Install Kafka on Ubuntu 16.04,” Hevo, 20 August 2017. [Online]. Available: https://hevodata.com/blog/how-to-install-kafka-on-ubuntu. [Accessed 30 06 2018]." }, { "code": null, "e": 9602, "s": 9449, "text": "[4] “Kafka setup in 15 minutes,” ETL-Tools, [Online]. Available: http://etl-tools.info/en/examples/kafka-setup-in-15-minutes.htm. [Accessed 25 07 2018]." }, { "code": null, "e": 9836, "s": 9602, "text": "[5] hitjethva, “Install and Configure Apache Kafka on Ubuntu 16.04,” DevOps, 03 October 2016. [Online]. Available: https://devops.profitbricks.com/tutorials/install-and-configure-apache-kafka-on-ubuntu-1604-1/. [Accessed 15 07 2018]." }, { "code": null, "e": 10026, "s": 9836, "text": "[6] M. Litwintschik, “Hadoop 3 Single-Node Install Guide,” 19 March 2018. [Online]. Available: http://www.tech.marksblogg.com/hadoop-3-single-node-install-guide.html. [Accessed 10 06 2018]." }, { "code": null, "e": 10120, "s": 10026, "text": "[7] “Stack overflow Q&A,” Stack overflow, [Online]. Available: https://www.Stackoverflow.com." }, { "code": null, "e": 10391, "s": 10120, "text": "[8] Gwen Shapira and Jeff Holoman, “Flafka: Apache Flume Meets Apache Kafka for Event Processing,” Cloudera, 06 November 2014. [Online]. Available: http://blog.cloudera.com/blog/2014/11/flafka-apache-flume-meets-apache-kafka-for-event-processing/. [Accessed 15 06 2018]." } ]
Python - Output Formatting
There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use. Sometimes user often wants more control the formatting of output than simply printing space-separated values. There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. The str.format()method of strings help a user to get a fancier Output User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants. The string type has some methods that perform useful operations for padding strings to a given column width. The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument. Live Demo # string modulo operator(%) to print # print integer and float value print("Vishesh : % 2d, Portal : % 5.2f" %(1, 05.333)) # print integer value print("Total students : % 3d, Boys : % 2d" %(240, 120)) # print octal value print("% 7.3o"% (25)) # print exponential value print("% 10.3E"% (356.08977)) Vishesh : 1, Portal : 5.33 Total students : 240, Boys : 120 031 3.561E+02 The format() method was added in Python(2.6). Format method of strings requires more manual effort. User use {} to mark where a variable will be substituted and can provide detailed formatting directives, but user also needs to provide the information to be formatted. # show format () is used in dictionary tab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678} # using format() in dictionary print('Vishesh: {0[vishesh]:d}; For: {0[for]:d}; ' 'python: {0[python]:d}'.format(tab)) data = dict(fun ="VisheshforPython", adj ="Python") # using format() in dictionary print("I love {fun} computer {adj}".format(**data)) In this output is formatted by using string slicing and concatenation operations. Live Demo # format a output using string() method cstr = "I love python" # Printing the center aligned # string with fillchr print ("Center aligned string with fillchr: ") print (cstr.center(40, '$')) # Printing the left aligned string with "-" padding print ("The left aligned string is : ") print (cstr.ljust(40, '-')) # Printing the right aligned string with "-" padding print ("The right aligned string is : ") print (cstr.rjust(40, '-')) Center aligned string with fillchr: $$$$$$$$$$$$$I love python$$$$$$$$$$$$$$ The left aligned string is : I love python--------------------------- The right aligned string is : ---------------------------I love python
[ { "code": null, "e": 1355, "s": 1062, "text": "There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use. Sometimes user often wants more control the formatting of output than simply printing space-separated values. There are several ways to format output." }, { "code": null, "e": 1476, "s": 1355, "text": "To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark." }, { "code": null, "e": 1546, "s": 1476, "text": "The str.format()method of strings help a user to get a fancier Output" }, { "code": null, "e": 1782, "s": 1546, "text": "User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants. The string type has some methods that perform useful operations for padding strings to a given column width." }, { "code": null, "e": 1947, "s": 1782, "text": "The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument." }, { "code": null, "e": 1958, "s": 1947, "text": " Live Demo" }, { "code": null, "e": 2257, "s": 1958, "text": "# string modulo operator(%) to print\n# print integer and float value\nprint(\"Vishesh : % 2d, Portal : % 5.2f\" %(1, 05.333))\n# print integer value\nprint(\"Total students : % 3d, Boys : % 2d\" %(240, 120))\n# print octal value\nprint(\"% 7.3o\"% (25))\n# print exponential value\nprint(\"% 10.3E\"% (356.08977))" }, { "code": null, "e": 2331, "s": 2257, "text": "Vishesh : 1, Portal : 5.33\nTotal students : 240, Boys : 120\n031\n3.561E+02" }, { "code": null, "e": 2600, "s": 2331, "text": "The format() method was added in Python(2.6). Format method of strings requires more manual effort. User use {} to mark where a variable will be substituted and can provide detailed formatting directives, but user also needs to provide the information to be formatted." }, { "code": null, "e": 2949, "s": 2600, "text": "# show format () is used in dictionary\ntab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678}\n# using format() in dictionary\nprint('Vishesh: {0[vishesh]:d}; For: {0[for]:d}; '\n'python: {0[python]:d}'.format(tab))\ndata = dict(fun =\"VisheshforPython\", adj =\"Python\")\n# using format() in dictionary\nprint(\"I love {fun} computer {adj}\".format(**data))" }, { "code": null, "e": 3031, "s": 2949, "text": "In this output is formatted by using string slicing and concatenation operations." }, { "code": null, "e": 3042, "s": 3031, "text": " Live Demo" }, { "code": null, "e": 3475, "s": 3042, "text": "# format a output using string() method\ncstr = \"I love python\"\n# Printing the center aligned\n# string with fillchr\nprint (\"Center aligned string with fillchr: \")\nprint (cstr.center(40, '$'))\n# Printing the left aligned string with \"-\" padding\nprint (\"The left aligned string is : \")\nprint (cstr.ljust(40, '-'))\n# Printing the right aligned string with \"-\" padding\nprint (\"The right aligned string is : \")\nprint (cstr.rjust(40, '-'))" }, { "code": null, "e": 3693, "s": 3475, "text": "Center aligned string with fillchr:\n$$$$$$$$$$$$$I love python$$$$$$$$$$$$$$\nThe left aligned string is :\nI love python---------------------------\nThe right aligned string is :\n---------------------------I love python" } ]
Tutorial: Uncertainty estimation with CatBoost | by Liudmila Prokhorenkova | Towards Data Science
This tutorial covers the following topics: What is predictive uncertainty and why should you care about it? What are the two sources of uncertainty? How to estimate uncertainty for regression problems using the CatBoost gradient boosting library You can follow all steps using this Jupyter Notebook. Machine learning has been widely applied to a range of tasks. However, in certain high-risk applications, such as autonomous driving, medical diagnostics, and financial forecasting, a mistake can lead to either a fatal outcome or large financial loss. In these applications, it is important to detect when the system makes a mistake and take safer actions. Furthermore, it is also desirable to collect these “failure scenarios”, label them, and teach the system to make the correct prediction through active learning. Predictive uncertainty estimation can be used for detecting errors . Ideally, the model indicates a high level of uncertainty in situations where it is likely to make a mistake. That allows us to detect errors and take safer actions. Crucially, the choice of action can depend on why the model is uncertain. There are two main sources of uncertainty: data uncertainty (also known as aleatoric uncertainty) and knowledge uncertainty (also known as epistemic uncertainty). If our goal is to detect errors, it is not necessary to separate these two uncertainties. However, if our goal is active learning, then we would like to detect novel inputs, and knowledge uncertainty can be used for that. Data uncertainty arises due to the inherent complexity of the data, such as additive noise or overlapping classes. In these cases, the model knows that the input has attributes of multiple classes or that the target is noisy. Importantly, data uncertainty cannot be reduced by collecting more training data. Knowledge uncertainty arises when the model is given an input from a region that is either sparsely covered by the training data or far from the training data. In these cases, the model knows very little about this region and is likely to make a mistake. Unlike data uncertainty, knowledge uncertainty can be reduced by collecting more training data from a poorly understood region. This tutorial post details how to quantify both data and knowledge uncertainty in CatBoost. To illustrate the concepts, we’ll use a simple synthetic example. Assume that we have two categorical features x1 and x2 with 9 values each, so there are 81 possible feature combinations. The target depends on the features as y = mean(x1,x2) + eps(x1,x2) where mean(x1,x2) is some unknown fixed value and eps(x1,x2) is a normally distributed noise (i.e., data uncertainty) with mean 0 and variance var(x1,x2). In our examples, mean(x1,x2) is randomly generated, and var(x1,x2) has two values (0.01 and 0.04) that are distributed as follows: Thus, points on the heart have more noise in the targets than points outside the heart. Note that we enumerated the categories for a nicer visualization, but in the dataset, both features are categorical, i.e., the order is not given. When we generate the dataset with this distribution, we assume that we do not have any training examples inside the heart — these feature combinations are considered outliers for our dataset. The standard model optimized with the RMSE loss can only predict mean(x1,x2). Ok, but what if we want to estimate the variance of y, i.e., data uncertainty? In other words, what if we want to understand which predictions are noisy? To estimate data uncertainty, one has to use probabilistic regression models that predict both mean and variance. For this purpose, there is a new loss function in CatBoost called RMSEWithUncertainty. With this loss, CatBoost estimates the mean and variance of the normal distribution optimizing the negative log-likelihood and using natural gradients, similarly to the NGBoost algorithm [1]. For each example, CatBoost model returns two values: estimated mean and estimated variance. Let’s try to apply this loss function to our simple example. We get the following variance: We can see that CatBoost successfully predicts the variance on the heart and outside it. Inside the heart, we have no training data, so anything can be predicted there. Ok, we know how to estimate noise in the data. But how to measure knowledge uncertainty coming from the lack of training data in a particular region? What to do if we want to detect outliers? Estimating knowledge uncertainty requires an ensemble of models. If all the models understand an input, they will give similar predictions (low knowledge uncertainty). However, if the models do not understand the input, then they are likely to provide diverse predictions and strongly disagree with each other (high knowledge uncertainty). For regression, knowledge uncertainty can be obtained by measuring the variance of the mean across multiple models. Note that this is different from the predicted variance of a single model, which captures data uncertainty. Let’s consider ensembles of GBDT models generated as follows: The models are generated using the option posterior_sampling since this allows the obtained (random) predictions to be nicely distributed (with good theoretical properties, and here we refer to [2] for details). Then, to estimate the knowledge uncertainty, we just compute the variance of the mean values predicted by models: knowledge = np.var(ens_preds, axis=0)[:, 0] We obtain the following result: The model correctly detected knowledge uncertainty inside the heart (we can see no traces of the original heart border). This illustrates how, by estimating knowledge uncertainty, we can detect anomalous inputs. In practice, training an ensemble of several CatBoost models can be too expensive. Ideally, we would like to train a single model but still be able to detect outliers. There is a solution for that: we can use a virtual ensemble, obtained from a single trained model: Having a single trained model, CatBoost returns several predictions for each example. These predictions are obtained via truncating the model: Again, we use the option posterior_sampling to guarantee a desirable distribution of cropped predictions. Let’s see what we obtain: Note that the predicted absolute values of knowledge uncertainty are now much smaller since the virtual ensemble elements are correlated. But still, it can successfully detect unoccupied regions (outliers). Instead of prediction_type=’VirtEnsembles’ that returns the predictions of several models, we could use prediction_type=’TotalUncertainty’ and get the same result easier. For this prediction type, CatBoost calculates all types of uncertainty using a virtual ensemble. Namely, for RMSEWithUncertainty it returns the following statistics: [Mean Prediction, Knowledge Uncertainty, Data Uncertainty]: Thanks for your attention! I hope this tutorial helped you to better understand the concept of uncertainty and how to estimate it with CatBoost. We’ll tell you more about applications of uncertainty in future posts. Stay tuned 😺 [1] T. Duan et al., NGBoost: Natural Gradient Boosting for Probabilistic Prediction (2020), ICML 2020 [2] A. Ustimenko, L. Prokhorenkova and A. Malinin, Uncertainty in Gradient Boosting via Ensembles” (2020), arXiv preprint arXiv:2006.10562
[ { "code": null, "e": 89, "s": 46, "text": "This tutorial covers the following topics:" }, { "code": null, "e": 154, "s": 89, "text": "What is predictive uncertainty and why should you care about it?" }, { "code": null, "e": 195, "s": 154, "text": "What are the two sources of uncertainty?" }, { "code": null, "e": 292, "s": 195, "text": "How to estimate uncertainty for regression problems using the CatBoost gradient boosting library" }, { "code": null, "e": 346, "s": 292, "text": "You can follow all steps using this Jupyter Notebook." }, { "code": null, "e": 864, "s": 346, "text": "Machine learning has been widely applied to a range of tasks. However, in certain high-risk applications, such as autonomous driving, medical diagnostics, and financial forecasting, a mistake can lead to either a fatal outcome or large financial loss. In these applications, it is important to detect when the system makes a mistake and take safer actions. Furthermore, it is also desirable to collect these “failure scenarios”, label them, and teach the system to make the correct prediction through active learning." }, { "code": null, "e": 1557, "s": 864, "text": "Predictive uncertainty estimation can be used for detecting errors . Ideally, the model indicates a high level of uncertainty in situations where it is likely to make a mistake. That allows us to detect errors and take safer actions. Crucially, the choice of action can depend on why the model is uncertain. There are two main sources of uncertainty: data uncertainty (also known as aleatoric uncertainty) and knowledge uncertainty (also known as epistemic uncertainty). If our goal is to detect errors, it is not necessary to separate these two uncertainties. However, if our goal is active learning, then we would like to detect novel inputs, and knowledge uncertainty can be used for that." }, { "code": null, "e": 1865, "s": 1557, "text": "Data uncertainty arises due to the inherent complexity of the data, such as additive noise or overlapping classes. In these cases, the model knows that the input has attributes of multiple classes or that the target is noisy. Importantly, data uncertainty cannot be reduced by collecting more training data." }, { "code": null, "e": 2248, "s": 1865, "text": "Knowledge uncertainty arises when the model is given an input from a region that is either sparsely covered by the training data or far from the training data. In these cases, the model knows very little about this region and is likely to make a mistake. Unlike data uncertainty, knowledge uncertainty can be reduced by collecting more training data from a poorly understood region." }, { "code": null, "e": 2340, "s": 2248, "text": "This tutorial post details how to quantify both data and knowledge uncertainty in CatBoost." }, { "code": null, "e": 2406, "s": 2340, "text": "To illustrate the concepts, we’ll use a simple synthetic example." }, { "code": null, "e": 2566, "s": 2406, "text": "Assume that we have two categorical features x1 and x2 with 9 values each, so there are 81 possible feature combinations. The target depends on the features as" }, { "code": null, "e": 2595, "s": 2566, "text": "y = mean(x1,x2) + eps(x1,x2)" }, { "code": null, "e": 2881, "s": 2595, "text": "where mean(x1,x2) is some unknown fixed value and eps(x1,x2) is a normally distributed noise (i.e., data uncertainty) with mean 0 and variance var(x1,x2). In our examples, mean(x1,x2) is randomly generated, and var(x1,x2) has two values (0.01 and 0.04) that are distributed as follows:" }, { "code": null, "e": 3116, "s": 2881, "text": "Thus, points on the heart have more noise in the targets than points outside the heart. Note that we enumerated the categories for a nicer visualization, but in the dataset, both features are categorical, i.e., the order is not given." }, { "code": null, "e": 3308, "s": 3116, "text": "When we generate the dataset with this distribution, we assume that we do not have any training examples inside the heart — these feature combinations are considered outliers for our dataset." }, { "code": null, "e": 4025, "s": 3308, "text": "The standard model optimized with the RMSE loss can only predict mean(x1,x2). Ok, but what if we want to estimate the variance of y, i.e., data uncertainty? In other words, what if we want to understand which predictions are noisy? To estimate data uncertainty, one has to use probabilistic regression models that predict both mean and variance. For this purpose, there is a new loss function in CatBoost called RMSEWithUncertainty. With this loss, CatBoost estimates the mean and variance of the normal distribution optimizing the negative log-likelihood and using natural gradients, similarly to the NGBoost algorithm [1]. For each example, CatBoost model returns two values: estimated mean and estimated variance." }, { "code": null, "e": 4117, "s": 4025, "text": "Let’s try to apply this loss function to our simple example. We get the following variance:" }, { "code": null, "e": 4286, "s": 4117, "text": "We can see that CatBoost successfully predicts the variance on the heart and outside it. Inside the heart, we have no training data, so anything can be predicted there." }, { "code": null, "e": 5042, "s": 4286, "text": "Ok, we know how to estimate noise in the data. But how to measure knowledge uncertainty coming from the lack of training data in a particular region? What to do if we want to detect outliers? Estimating knowledge uncertainty requires an ensemble of models. If all the models understand an input, they will give similar predictions (low knowledge uncertainty). However, if the models do not understand the input, then they are likely to provide diverse predictions and strongly disagree with each other (high knowledge uncertainty). For regression, knowledge uncertainty can be obtained by measuring the variance of the mean across multiple models. Note that this is different from the predicted variance of a single model, which captures data uncertainty." }, { "code": null, "e": 5104, "s": 5042, "text": "Let’s consider ensembles of GBDT models generated as follows:" }, { "code": null, "e": 5316, "s": 5104, "text": "The models are generated using the option posterior_sampling since this allows the obtained (random) predictions to be nicely distributed (with good theoretical properties, and here we refer to [2] for details)." }, { "code": null, "e": 5430, "s": 5316, "text": "Then, to estimate the knowledge uncertainty, we just compute the variance of the mean values predicted by models:" }, { "code": null, "e": 5474, "s": 5430, "text": "knowledge = np.var(ens_preds, axis=0)[:, 0]" }, { "code": null, "e": 5506, "s": 5474, "text": "We obtain the following result:" }, { "code": null, "e": 5718, "s": 5506, "text": "The model correctly detected knowledge uncertainty inside the heart (we can see no traces of the original heart border). This illustrates how, by estimating knowledge uncertainty, we can detect anomalous inputs." }, { "code": null, "e": 5985, "s": 5718, "text": "In practice, training an ensemble of several CatBoost models can be too expensive. Ideally, we would like to train a single model but still be able to detect outliers. There is a solution for that: we can use a virtual ensemble, obtained from a single trained model:" }, { "code": null, "e": 6128, "s": 5985, "text": "Having a single trained model, CatBoost returns several predictions for each example. These predictions are obtained via truncating the model:" }, { "code": null, "e": 6260, "s": 6128, "text": "Again, we use the option posterior_sampling to guarantee a desirable distribution of cropped predictions. Let’s see what we obtain:" }, { "code": null, "e": 6467, "s": 6260, "text": "Note that the predicted absolute values of knowledge uncertainty are now much smaller since the virtual ensemble elements are correlated. But still, it can successfully detect unoccupied regions (outliers)." }, { "code": null, "e": 6864, "s": 6467, "text": "Instead of prediction_type=’VirtEnsembles’ that returns the predictions of several models, we could use prediction_type=’TotalUncertainty’ and get the same result easier. For this prediction type, CatBoost calculates all types of uncertainty using a virtual ensemble. Namely, for RMSEWithUncertainty it returns the following statistics: [Mean Prediction, Knowledge Uncertainty, Data Uncertainty]:" }, { "code": null, "e": 7093, "s": 6864, "text": "Thanks for your attention! I hope this tutorial helped you to better understand the concept of uncertainty and how to estimate it with CatBoost. We’ll tell you more about applications of uncertainty in future posts. Stay tuned 😺" }, { "code": null, "e": 7195, "s": 7093, "text": "[1] T. Duan et al., NGBoost: Natural Gradient Boosting for Probabilistic Prediction (2020), ICML 2020" } ]
How to sort a Python date string list?
To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object. from datetime import datetime my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17'] my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y")) print(my_dates) This will give the output − ['7-Mar-17', '25-Mar-17', '1-Nov-18', '5-Nov-18']
[ { "code": null, "e": 1374, "s": 1062, "text": "To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object. " }, { "code": null, "e": 1549, "s": 1374, "text": "from datetime import datetime\nmy_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17']\nmy_dates.sort(key=lambda date: datetime.strptime(date, \"%d-%b-%y\"))\nprint(my_dates)" }, { "code": null, "e": 1577, "s": 1549, "text": "This will give the output −" }, { "code": null, "e": 1627, "s": 1577, "text": "['7-Mar-17', '25-Mar-17', '1-Nov-18', '5-Nov-18']" } ]
Count number of occurrences (or frequency) in a sorted array in C++
We are given a sorted array of integer type elements and the number let’s say, num and the task is to calculate the count of the number of times the given element num is appearing in an array. Input − int arr[] = {1, 1, 1,2, 3, 4}, num = 1 Output − Count of number of occurrences (or frequency) in a sorted array are − 3 Input − int arr[] = {2, 3, 4, 5, 5, 6, -7}, num = 5 Output − Count of number of occurrences (or frequency) in a sorted array are − 2 Input − int arr[] = {-1, 0, 1, 2, 3}, num = 7 Output − Count of number of occurrences (or frequency) in a sorted array are − 0 There can be multiple approaches that can be followed to solve the above problem. Naive approach Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array. Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array. Calculate the size of an array and pass all the data to the function for further processing. Calculate the size of an array and pass all the data to the function for further processing. Declare a temporary variable count to store the count of number of times the variable num is appearing Declare a temporary variable count to store the count of number of times the variable num is appearing Start loop FOR from i to 0 till the size of an array Start loop FOR from i to 0 till the size of an array Inside the loop, check IF num = arr[i] then increment the value of count by 1 Inside the loop, check IF num = arr[i] then increment the value of count by 1 Return the count Return the count Print the result. Print the result. Efficient approach Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array. Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array. Calculate the size of an array and pass all the data to the function for further processing. Calculate the size of an array and pass all the data to the function for further processing. Declare a temporary variable count to store the count of number of times the variable num is appearing Declare a temporary variable count to store the count of number of times the variable num is appearing Set a pointer first as lower_bound(arr, arr+size, num) Set a pointer first as lower_bound(arr, arr+size, num) Check IF first = (arr + size) || (*first != num) then return 0 Check IF first = (arr + size) || (*first != num) then return 0 Set end pointer as upper_bound(first, arr+size, num) Set end pointer as upper_bound(first, arr+size, num) Set count as last - first Set count as last - first Return count Return count Print result Print result Live Demo #include <iostream> using namespace std; int frequency_count(int arr[], int num, int size){ int count = 0; for(int i=0; i<size; i++){ if(num==arr[i]){ count++; } } return count; } int main(){ int arr[] = {1, 1, 1,2, 3, 4}; int num = 1; int size = sizeof(arr)/sizeof(arr[0]); cout<<"Count of number of occurrences (or frequency) in a sorted array are: "<<frequency_count(arr, num, size); return 0; } If we run the above code it will generate the following output − Count of number of occurrences (or frequency) in a sorted array are: 3 Live Demo # include <bits/stdc++.h> using namespace std; int frequency_count(int arr[], int num, int size){ int *first = lower_bound(arr, arr+size, num); if (first == (arr + size) || *first != num){ cout<<"The Element is not present in an array "; return 0; } int count = 0; int *last = upper_bound(first, arr+size, num); count = last - first; return count; } int main(){ int arr[] = {1, 1, 1, 2, 3, 4}; int num = 1; int size = sizeof(arr)/sizeof(arr[0]); cout<<"Count of number of occurrences (or frequency) in a sorted array are: "<<frequency_count(arr, num, size); return 0; } If we run the above code it will generate the following output − Count of number of occurrences (or frequency) in a sorted array are: 3
[ { "code": null, "e": 1255, "s": 1062, "text": "We are given a sorted array of integer type elements and the number let’s say, num and the task is to calculate the count of the number of times the given element num is appearing in an array." }, { "code": null, "e": 1302, "s": 1255, "text": "Input − int arr[] = {1, 1, 1,2, 3, 4}, num = 1" }, { "code": null, "e": 1383, "s": 1302, "text": "Output − Count of number of occurrences (or frequency) in a sorted array are − 3" }, { "code": null, "e": 1435, "s": 1383, "text": "Input − int arr[] = {2, 3, 4, 5, 5, 6, -7}, num = 5" }, { "code": null, "e": 1516, "s": 1435, "text": "Output − Count of number of occurrences (or frequency) in a sorted array are − 2" }, { "code": null, "e": 1562, "s": 1516, "text": "Input − int arr[] = {-1, 0, 1, 2, 3}, num = 7" }, { "code": null, "e": 1643, "s": 1562, "text": "Output − Count of number of occurrences (or frequency) in a sorted array are − 0" }, { "code": null, "e": 1725, "s": 1643, "text": "There can be multiple approaches that can be followed to solve the above problem." }, { "code": null, "e": 1740, "s": 1725, "text": "Naive approach" }, { "code": null, "e": 1903, "s": 1740, "text": "Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array." }, { "code": null, "e": 2066, "s": 1903, "text": "Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array." }, { "code": null, "e": 2159, "s": 2066, "text": "Calculate the size of an array and pass all the data to the function for further processing." }, { "code": null, "e": 2252, "s": 2159, "text": "Calculate the size of an array and pass all the data to the function for further processing." }, { "code": null, "e": 2355, "s": 2252, "text": "Declare a temporary variable count to store the count of number of times the variable num is appearing" }, { "code": null, "e": 2458, "s": 2355, "text": "Declare a temporary variable count to store the count of number of times the variable num is appearing" }, { "code": null, "e": 2511, "s": 2458, "text": "Start loop FOR from i to 0 till the size of an array" }, { "code": null, "e": 2564, "s": 2511, "text": "Start loop FOR from i to 0 till the size of an array" }, { "code": null, "e": 2642, "s": 2564, "text": "Inside the loop, check IF num = arr[i] then increment the value of count by 1" }, { "code": null, "e": 2720, "s": 2642, "text": "Inside the loop, check IF num = arr[i] then increment the value of count by 1" }, { "code": null, "e": 2737, "s": 2720, "text": "Return the count" }, { "code": null, "e": 2754, "s": 2737, "text": "Return the count" }, { "code": null, "e": 2772, "s": 2754, "text": "Print the result." }, { "code": null, "e": 2790, "s": 2772, "text": "Print the result." }, { "code": null, "e": 2809, "s": 2790, "text": "Efficient approach" }, { "code": null, "e": 2972, "s": 2809, "text": "Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array." }, { "code": null, "e": 3135, "s": 2972, "text": "Declare an array of integer elements containing both positive and negative numbers and an integer variable num of which we have to find the frequency in an array." }, { "code": null, "e": 3228, "s": 3135, "text": "Calculate the size of an array and pass all the data to the function for further processing." }, { "code": null, "e": 3321, "s": 3228, "text": "Calculate the size of an array and pass all the data to the function for further processing." }, { "code": null, "e": 3424, "s": 3321, "text": "Declare a temporary variable count to store the count of number of times the variable num is appearing" }, { "code": null, "e": 3527, "s": 3424, "text": "Declare a temporary variable count to store the count of number of times the variable num is appearing" }, { "code": null, "e": 3582, "s": 3527, "text": "Set a pointer first as lower_bound(arr, arr+size, num)" }, { "code": null, "e": 3637, "s": 3582, "text": "Set a pointer first as lower_bound(arr, arr+size, num)" }, { "code": null, "e": 3700, "s": 3637, "text": "Check IF first = (arr + size) || (*first != num) then return 0" }, { "code": null, "e": 3763, "s": 3700, "text": "Check IF first = (arr + size) || (*first != num) then return 0" }, { "code": null, "e": 3816, "s": 3763, "text": "Set end pointer as upper_bound(first, arr+size, num)" }, { "code": null, "e": 3869, "s": 3816, "text": "Set end pointer as upper_bound(first, arr+size, num)" }, { "code": null, "e": 3895, "s": 3869, "text": "Set count as last - first" }, { "code": null, "e": 3921, "s": 3895, "text": "Set count as last - first" }, { "code": null, "e": 3934, "s": 3921, "text": "Return count" }, { "code": null, "e": 3947, "s": 3934, "text": "Return count" }, { "code": null, "e": 3960, "s": 3947, "text": "Print result" }, { "code": null, "e": 3973, "s": 3960, "text": "Print result" }, { "code": null, "e": 3984, "s": 3973, "text": " Live Demo" }, { "code": null, "e": 4431, "s": 3984, "text": "#include <iostream>\nusing namespace std;\nint frequency_count(int arr[], int num, int size){\n int count = 0;\n for(int i=0; i<size; i++){\n if(num==arr[i]){\n count++;\n }\n }\n return count;\n}\nint main(){\n int arr[] = {1, 1, 1,2, 3, 4};\n int num = 1;\n int size = sizeof(arr)/sizeof(arr[0]);\n cout<<\"Count of number of occurrences (or frequency) in a sorted array are: \"<<frequency_count(arr, num, size);\n return 0;\n}" }, { "code": null, "e": 4496, "s": 4431, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4567, "s": 4496, "text": "Count of number of occurrences (or frequency) in a sorted array are: 3" }, { "code": null, "e": 4578, "s": 4567, "text": " Live Demo" }, { "code": null, "e": 5196, "s": 4578, "text": "# include <bits/stdc++.h>\nusing namespace std;\nint frequency_count(int arr[], int num, int size){\n int *first = lower_bound(arr, arr+size, num);\n if (first == (arr + size) || *first != num){\n cout<<\"The Element is not present in an array \";\n return 0;\n }\n int count = 0;\n int *last = upper_bound(first, arr+size, num);\n count = last - first;\n return count;\n}\nint main(){\n int arr[] = {1, 1, 1, 2, 3, 4};\n int num = 1;\n int size = sizeof(arr)/sizeof(arr[0]);\n cout<<\"Count of number of occurrences (or frequency) in a sorted array are: \"<<frequency_count(arr, num, size);\n return 0;\n}" }, { "code": null, "e": 5261, "s": 5196, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 5332, "s": 5261, "text": "Count of number of occurrences (or frequency) in a sorted array are: 3" } ]
How to read the data from a CSV file in Java?
A CSV stands for Comma Separated Values. In a CSV file, each line contains words that are separated with a comma(,) and it is stored with a .csv extension. We can read a CSV file line by line using the readLine() method of BufferedReader class. Split each line on comma character to get the words of the line into an array. Now we can easily print the contents of the array by iterating over it or by using an appropriate index. import java.io.*; public class CSVReaderTest { public static final String delimiter = ","; public static void read(String csvFile) { try { File file = new File(csvFile); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = ""; String[] tempArr; while((line = br.readLine()) != null) { tempArr = line.split(delimiter); for(String tempStr : tempArr) { System.out.print(tempStr + " "); } System.out.println(); } br.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } public static void main(String[] args) { // csv file to read String csvFile = "C:/Temp/Technology.csv"; CSVReaderTest.read(csvFile); } } "JAVA" "PYTHON" "JAVASCRIPT" "SELENIUM" "SCALA"
[ { "code": null, "e": 1218, "s": 1062, "text": "A CSV stands for Comma Separated Values. In a CSV file, each line contains words that are separated with a comma(,) and it is stored with a .csv extension." }, { "code": null, "e": 1491, "s": 1218, "text": "We can read a CSV file line by line using the readLine() method of BufferedReader class. Split each line on comma character to get the words of the line into an array. Now we can easily print the contents of the array by iterating over it or by using an appropriate index." }, { "code": null, "e": 2351, "s": 1491, "text": "import java.io.*;\npublic class CSVReaderTest {\n public static final String delimiter = \",\";\n public static void read(String csvFile) {\n try {\n File file = new File(csvFile);\n FileReader fr = new FileReader(file);\n BufferedReader br = new BufferedReader(fr);\n String line = \"\";\n String[] tempArr;\n while((line = br.readLine()) != null) {\n tempArr = line.split(delimiter);\n for(String tempStr : tempArr) {\n System.out.print(tempStr + \" \");\n }\n System.out.println();\n }\n br.close();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n public static void main(String[] args) {\n // csv file to read\n String csvFile = \"C:/Temp/Technology.csv\";\n CSVReaderTest.read(csvFile);\n }\n}" }, { "code": null, "e": 2399, "s": 2351, "text": "\"JAVA\" \"PYTHON\" \"JAVASCRIPT\" \"SELENIUM\" \"SCALA\"" } ]
quotactl() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <sys/quota.h> #include <sys/types.h> #include <xfs/xqm.h> #include <linux/dqblk_v1.h> #include <linux/dqblk_v2.h> long quotactl(int cmd, char *special, qid_t id, caddr_t addr) long quotactl(int cmd, char *special, qid_t id, caddr_t addr) The quotactl() call manipulates disk quotas. cmd indicates a command to be applied to UID id or GID id. To set the type of quota use the QCMD(cmd, type) macro. special is a pointer to a null-terminated string containing the path name of the block special device for the filesystem being manipulated. addr is the address of an optional, command specific, data structure which is copied in or out of the system. The interpretation of addr is given with each command below. quotactl() returns: quota (1) quota (1) getrlimit (2) getrlimit (2) quotacheck (8) quotacheck (8) quotaon (8) quotaon (8) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2512, "s": 2319, "text": "#include <sys/quota.h> \n#include <sys/types.h> \n#include <xfs/xqm.h> \n#include <linux/dqblk_v1.h> \n#include <linux/dqblk_v2.h> \n\nlong quotactl(int cmd, char *special, qid_t id, caddr_t addr) \n" }, { "code": null, "e": 2577, "s": 2512, "text": "\nlong quotactl(int cmd, char *special, qid_t id, caddr_t addr) \n" }, { "code": null, "e": 3056, "s": 2582, "text": "\nThe\nquotactl() call manipulates disk quotas.\ncmd indicates a command to be applied to\nUID id or\nGID id. To set the type of quota use the\nQCMD(cmd, type) macro.\nspecial is a pointer to a null-terminated string containing the path\nname of the block special device for the filesystem being manipulated.\naddr is the address of an optional, command specific, data structure\nwhich is copied in or out of the system. The interpretation of\naddr is given with each command below.\n" }, { "code": null, "e": 3078, "s": 3056, "text": "\nquotactl() returns:\n" }, { "code": null, "e": 3088, "s": 3078, "text": "quota (1)" }, { "code": null, "e": 3098, "s": 3088, "text": "quota (1)" }, { "code": null, "e": 3112, "s": 3098, "text": "getrlimit (2)" }, { "code": null, "e": 3126, "s": 3112, "text": "getrlimit (2)" }, { "code": null, "e": 3141, "s": 3126, "text": "quotacheck (8)" }, { "code": null, "e": 3156, "s": 3141, "text": "quotacheck (8)" }, { "code": null, "e": 3168, "s": 3156, "text": "quotaon (8)" }, { "code": null, "e": 3180, "s": 3168, "text": "quotaon (8)" }, { "code": null, "e": 3197, "s": 3180, "text": "\nAdvertisements\n" }, { "code": null, "e": 3232, "s": 3197, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3260, "s": 3232, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3294, "s": 3260, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3311, "s": 3294, "text": " Frahaan Hussain" }, { "code": null, "e": 3344, "s": 3311, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3355, "s": 3344, "text": " Pradeep D" }, { "code": null, "e": 3390, "s": 3355, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3406, "s": 3390, "text": " Musab Zayadneh" }, { "code": null, "e": 3439, "s": 3406, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 3451, "s": 3439, "text": " GUHARAJANM" }, { "code": null, "e": 3483, "s": 3451, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 3491, "s": 3483, "text": " Uplatz" }, { "code": null, "e": 3498, "s": 3491, "text": " Print" }, { "code": null, "e": 3509, "s": 3498, "text": " Add Notes" } ]
Linear Regression Using Least Squares | by Adarsh Menon | Towards Data Science
Linear Regression is the simplest form of machine learning out there. In this post, we will see how linear regression works and implement it in Python from scratch. This is the written version of the above video. Watch it if you prefer that. In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. In the case of one independent variable it is called simple linear regression. For more than one independent variable, the process is called mulitple linear regression. We will be dealing with simple linear regression in this tutorial. Let X be the independent variable and Y be the dependent variable. We will define a linear relationship between these two variables as follows: This is the equation for a line that you studied in high school. m is the slope of the line and c is the y intercept. Today we will use this equation to train our model with a given dataset and predict the value of Y for any given value of X. Our challenege today is to determine the value of m and c, that gives the minimum error for the given dataset. We will be doing this by using the Least Squares method. So to minimize the error we need a way to calculate the error in the first place. A loss function in machine learning is simply a measure of how different the predicted value is from the actual value. Today we will be using the Quadratic Loss Function to calculate the loss or error in our model. It can be defined as: We are squaring it because, for the points below the regression line y — p will be negative and we don’t want negative values in our total error. Now that we have determined the loss function, the only thing left to do is minimize it. This is done by finding the partial derivative of L, equating it to 0 and then finding an expression for m and c. After we do the math, we are left with these equations: Here x̅ is the mean of all the values in the input X and ȳ is the mean of all the values in the desired output Y. This is the Least Squares method. Now we will implement this in python and make predictions. 1.287357370010931 9.908606190326509 There wont be much accuracy because we are simply taking a straight line and forcing it to fit into the given data in the best possible way. But you can use this to make simple predictions or get an idea about the magnitude/range of the real value. Also this is a good first step for beginners in Machine Learning. Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/01%20Linear%20Regression%20using%20Least%20Squares Got questions ? Need help ? Contact me!
[ { "code": null, "e": 413, "s": 171, "text": "Linear Regression is the simplest form of machine learning out there. In this post, we will see how linear regression works and implement it in Python from scratch. This is the written version of the above video. Watch it if you prefer that." }, { "code": null, "e": 945, "s": 413, "text": "In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. In the case of one independent variable it is called simple linear regression. For more than one independent variable, the process is called mulitple linear regression. We will be dealing with simple linear regression in this tutorial. Let X be the independent variable and Y be the dependent variable. We will define a linear relationship between these two variables as follows:" }, { "code": null, "e": 1188, "s": 945, "text": "This is the equation for a line that you studied in high school. m is the slope of the line and c is the y intercept. Today we will use this equation to train our model with a given dataset and predict the value of Y for any given value of X." }, { "code": null, "e": 1356, "s": 1188, "text": "Our challenege today is to determine the value of m and c, that gives the minimum error for the given dataset. We will be doing this by using the Least Squares method." }, { "code": null, "e": 1675, "s": 1356, "text": "So to minimize the error we need a way to calculate the error in the first place. A loss function in machine learning is simply a measure of how different the predicted value is from the actual value. Today we will be using the Quadratic Loss Function to calculate the loss or error in our model. It can be defined as:" }, { "code": null, "e": 1821, "s": 1675, "text": "We are squaring it because, for the points below the regression line y — p will be negative and we don’t want negative values in our total error." }, { "code": null, "e": 2080, "s": 1821, "text": "Now that we have determined the loss function, the only thing left to do is minimize it. This is done by finding the partial derivative of L, equating it to 0 and then finding an expression for m and c. After we do the math, we are left with these equations:" }, { "code": null, "e": 2288, "s": 2080, "text": "Here x̅ is the mean of all the values in the input X and ȳ is the mean of all the values in the desired output Y. This is the Least Squares method. Now we will implement this in python and make predictions." }, { "code": null, "e": 2324, "s": 2288, "text": "1.287357370010931 9.908606190326509" }, { "code": null, "e": 2639, "s": 2324, "text": "There wont be much accuracy because we are simply taking a straight line and forcing it to fit into the given data in the best possible way. But you can use this to make simple predictions or get an idea about the magnitude/range of the real value. Also this is a good first step for beginners in Machine Learning." }, { "code": null, "e": 2786, "s": 2639, "text": "Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/01%20Linear%20Regression%20using%20Least%20Squares" } ]
Public vs Protected vs Package vs Private Access Modifier in Java - GeeksforGeeks
02 Mar, 2022 Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members. Modifier 1: Public Access Modifiers If a class is declared as public then we can access that class from anywhere. In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main method we create an object of type class A and trying to access the data of method m1. Example: Java // Java program to showcase the example// of public access modifier // creating a packagepackage pack1; // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println("GFG"); }} Compiling and saving the above code by using the below command line: Java // creating a packagepackage pack2; // import required packagesimport java.io.*;import java.util.*; // importing package pack1import pack1.A; // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }} If class A is not public while compiling B class we will get a compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package. Similarly, a member or method, or interface is declared as public as we can access that member from anywhere. Modifier 2: Protected Access Modifier This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface. A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package. Implementation: Example Java // Java program to showcase the example// of protected access modifier// import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println("GFG"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }} GFG GFG GFG Output explanation: In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference. Modifier 3: Private Access Modifiers This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes. If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them. Example: Java // Java program to showcase the example// of private access modifier // import required packagesimport java.io.*; import java.util.*; // helper classclass A { // helper method private void m1() { System.out.println("GFG"); }} // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }} Modifier 4: Package(Default) Access Modifier A class or method or variable declare without any access modifier then is considered that it has a package(default)access modifier The default modifier act as public within the same package and acts as private outside the package. If a class is declared as default then we can access that class only within the current package i.e from the outside package we can’t access it. Hence, the default access modifier is also known as the package–level access modifier. A similar rule also applies for variables and methods in java. Example: Java // Java Program to illustrate Package Level Access Modifier // Importing utility classes// Importing input output classesimport java.io.*;import java.util.*; // Main Classclass GFG { // Declaring default variables that is // having no access modifier String s = "Geeksfor"; String s1 = "Geeks"; // Method 1 // To declare a default method String fullName() { // Concatenation of strings return s + s1; } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object of main class(GFG) // in the main() method GFG g = new GFG(); // Calling method1 using class instance // and printing the concatenation of strings System.out.println(g.fullName()); }} GeeksforGeeks Finally, after getting it done with all four access modifiers let us conclude the evident differences between them gabaa406 adnanirshad158 saurabh1990aror prachisoda1234 avtarkumar719 Java-Modifier Picked Difference Between Java Java 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 Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24858, "s": 24830, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25307, "s": 24858, "text": "Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members." }, { "code": null, "e": 25343, "s": 25307, "text": "Modifier 1: Public Access Modifiers" }, { "code": null, "e": 25421, "s": 25343, "text": "If a class is declared as public then we can access that class from anywhere." }, { "code": null, "e": 25804, "s": 25421, "text": "In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main method we create an object of type class A and trying to access the data of method m1." }, { "code": null, "e": 25813, "s": 25804, "text": "Example:" }, { "code": null, "e": 25818, "s": 25813, "text": "Java" }, { "code": "// Java program to showcase the example// of public access modifier // creating a packagepackage pack1; // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println(\"GFG\"); }}", "e": 26117, "s": 25818, "text": null }, { "code": null, "e": 26187, "s": 26117, "text": " Compiling and saving the above code by using the below command line:" }, { "code": null, "e": 26192, "s": 26187, "text": "Java" }, { "code": "// creating a packagepackage pack2; // import required packagesimport java.io.*;import java.util.*; // importing package pack1import pack1.A; // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}", "e": 26568, "s": 26192, "text": null }, { "code": null, "e": 26738, "s": 26568, "text": " If class A is not public while compiling B class we will get a compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package." }, { "code": null, "e": 26848, "s": 26738, "text": "Similarly, a member or method, or interface is declared as public as we can access that member from anywhere." }, { "code": null, "e": 26886, "s": 26848, "text": "Modifier 2: Protected Access Modifier" }, { "code": null, "e": 27035, "s": 26886, "text": "This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface." }, { "code": null, "e": 27182, "s": 27035, "text": "A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package." }, { "code": null, "e": 27198, "s": 27182, "text": "Implementation:" }, { "code": null, "e": 27207, "s": 27198, "text": "Example " }, { "code": null, "e": 27212, "s": 27207, "text": "Java" }, { "code": "// Java program to showcase the example// of protected access modifier// import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println(\"GFG\"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }}", "e": 28109, "s": 27212, "text": null }, { "code": null, "e": 28121, "s": 28109, "text": "GFG\nGFG\nGFG" }, { "code": null, "e": 28141, "s": 28121, "text": "Output explanation:" }, { "code": null, "e": 28456, "s": 28141, "text": "In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference." }, { "code": null, "e": 28493, "s": 28456, "text": "Modifier 3: Private Access Modifiers" }, { "code": null, "e": 28643, "s": 28493, "text": "This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes. " }, { "code": null, "e": 28806, "s": 28643, "text": "If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them." }, { "code": null, "e": 28815, "s": 28806, "text": "Example:" }, { "code": null, "e": 28820, "s": 28815, "text": "Java" }, { "code": "// Java program to showcase the example// of private access modifier // import required packagesimport java.io.*; import java.util.*; // helper classclass A { // helper method private void m1() { System.out.println(\"GFG\"); }} // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}", "e": 29293, "s": 28820, "text": null }, { "code": null, "e": 29340, "s": 29293, "text": "Modifier 4: Package(Default) Access Modifier " }, { "code": null, "e": 29866, "s": 29340, "text": "A class or method or variable declare without any access modifier then is considered that it has a package(default)access modifier The default modifier act as public within the same package and acts as private outside the package. If a class is declared as default then we can access that class only within the current package i.e from the outside package we can’t access it. Hence, the default access modifier is also known as the package–level access modifier. A similar rule also applies for variables and methods in java." }, { "code": null, "e": 29876, "s": 29866, "text": "Example: " }, { "code": null, "e": 29881, "s": 29876, "text": "Java" }, { "code": "// Java Program to illustrate Package Level Access Modifier // Importing utility classes// Importing input output classesimport java.io.*;import java.util.*; // Main Classclass GFG { // Declaring default variables that is // having no access modifier String s = \"Geeksfor\"; String s1 = \"Geeks\"; // Method 1 // To declare a default method String fullName() { // Concatenation of strings return s + s1; } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object of main class(GFG) // in the main() method GFG g = new GFG(); // Calling method1 using class instance // and printing the concatenation of strings System.out.println(g.fullName()); }}", "e": 30685, "s": 29881, "text": null }, { "code": null, "e": 30699, "s": 30685, "text": "GeeksforGeeks" }, { "code": null, "e": 30815, "s": 30699, "text": "Finally, after getting it done with all four access modifiers let us conclude the evident differences between them " }, { "code": null, "e": 30826, "s": 30817, "text": "gabaa406" }, { "code": null, "e": 30841, "s": 30826, "text": "adnanirshad158" }, { "code": null, "e": 30857, "s": 30841, "text": "saurabh1990aror" }, { "code": null, "e": 30872, "s": 30857, "text": "prachisoda1234" }, { "code": null, "e": 30886, "s": 30872, "text": "avtarkumar719" }, { "code": null, "e": 30900, "s": 30886, "text": "Java-Modifier" }, { "code": null, "e": 30907, "s": 30900, "text": "Picked" }, { "code": null, "e": 30926, "s": 30907, "text": "Difference Between" }, { "code": null, "e": 30931, "s": 30926, "text": "Java" }, { "code": null, "e": 30936, "s": 30931, "text": "Java" }, { "code": null, "e": 31034, "s": 30936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31043, "s": 31034, "text": "Comments" }, { "code": null, "e": 31056, "s": 31043, "text": "Old Comments" }, { "code": null, "e": 31117, "s": 31056, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31185, "s": 31117, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 31241, "s": 31185, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 31299, "s": 31241, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 31354, "s": 31299, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 31369, "s": 31354, "text": "Arrays in Java" }, { "code": null, "e": 31413, "s": 31369, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31435, "s": 31413, "text": "For-each loop in Java" }, { "code": null, "e": 31471, "s": 31435, "text": "Arrays.sort() in Java with examples" } ]
How to check Leap Year in Java 8 How to get current timestamp in Java 8?
The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives. Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock. The isLeapYear() method of java.time.LocalDate verifies if the year in the current object is a leap year according to the ISO proleptic calendar system rules, returns true if so, else returns false. Following Java program gets the current date and finds out whether it is a leap year. import java.time.LocalDate; public class IsLeapYear { public static void main(String args[]) { //Getting the current date LocalDate currentDate = LocalDate.now(); //Verifying if leap year boolean bool = currentDate.isLeapYear(); //is after if(bool){ System.out.println("Current year is a leap year "); }else{ System.out.println("Current year is not a leap year "); } } } Current year is not a leap year Following example accepts an year from user and displays whether it is a leap year. import java.time.LocalDate; import java.util.Scanner; public class IsLeapYear { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the year: "); int year = sc.nextInt(); //Getting the date of jan1st of the given date value LocalDate givenDate = LocalDate.of(year, 01, 01); //Verifying if leap year boolean bool = givenDate.isLeapYear(); //is after if(bool){ System.out.println("Given year is a leap year "); }else{ System.out.println("Given year is not a leap year "); } } } Enter the year: 2004 Given year is a leap year
[ { "code": null, "e": 1387, "s": 1062, "text": "The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives." }, { "code": null, "e": 1571, "s": 1387, "text": "Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock." }, { "code": null, "e": 1770, "s": 1571, "text": "The isLeapYear() method of java.time.LocalDate verifies if the year in the current object is a leap year according to the ISO proleptic calendar system rules, returns true if so, else returns false." }, { "code": null, "e": 1856, "s": 1770, "text": "Following Java program gets the current date and finds out whether it is a leap year." }, { "code": null, "e": 2299, "s": 1856, "text": "import java.time.LocalDate;\npublic class IsLeapYear {\n public static void main(String args[]) {\n //Getting the current date\n LocalDate currentDate = LocalDate.now();\n //Verifying if leap year\n boolean bool = currentDate.isLeapYear();\n //is after\n if(bool){\n System.out.println(\"Current year is a leap year \");\n }else{\n System.out.println(\"Current year is not a leap year \");\n }\n }\n}" }, { "code": null, "e": 2331, "s": 2299, "text": "Current year is not a leap year" }, { "code": null, "e": 2415, "s": 2331, "text": "Following example accepts an year from user and displays whether it is a leap year." }, { "code": null, "e": 3033, "s": 2415, "text": "import java.time.LocalDate;\nimport java.util.Scanner;\npublic class IsLeapYear {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the year: \");\n int year = sc.nextInt();\n //Getting the date of jan1st of the given date value\n LocalDate givenDate = LocalDate.of(year, 01, 01);\n //Verifying if leap year\n boolean bool = givenDate.isLeapYear();\n //is after\n if(bool){\n System.out.println(\"Given year is a leap year \");\n }else{\n System.out.println(\"Given year is not a leap year \");\n }\n }\n}" }, { "code": null, "e": 3080, "s": 3033, "text": "Enter the year:\n2004\nGiven year is a leap year" } ]
High-quality slow-motion videos in 5 minutes with Deep Learning | by Dimitris Poulopoulos | Towards Data Science
We can all agree that slow-motion videos create this dramatic effect, which certainly adds an extra flavor to specific scenes. On the other hand, slowing down a video might create several unwanted artifacts, which could deem it unwatchable. But what makes a slow-motion video great? Let’s use Deep Learning for free, to produce the smooth result of a high-end camera capable of recording at high frame-rates Among other things, I would argue that the most important aspect is its FPS count: how many frames per second are rendered to the screen. Too low and the video stutters, creating an unpleasant viewing experience. Thus, we need to have an expensive camera able to record at a high frame-rate. Or, we could use Deep Learning for free, and try to synthesize intermediate images between two consecutive frames. Super slow-motion is just one of the applications of Video Frame Interpolation or VFI as it’s commonly known in the field of Computer Vision. In this story, we present RIFE: Real-Time Intermediate Flow Estimation for Video Frame Interpolation. We touch on what it is bringing to the table and take it for a quick test drive using our own videos. Let’s dive in! Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here! The ultimate goal for Video Frame Interpolation (VFI) is to improve the frame rate and enhance the visual quality of a video. To achieve this, it tries to synthesize intermediate images between two consecutive frames, that are both spatially and temporally coherent with the existing context. In the core of VFI, we find another vision task named Optical Flow. So, let’s take a quick detour to see what Optical Flow means, and how it helps us with VFI. Then, we will be ready to watch RIFE in action and play with it using our own videos. Very broadly, Optical Flow is understanding how things are moving in an image, at the pixel level. This is useful for a number of downstream video editing tasks, such as video analysis, image stabilization, and video alignment. An image is comprised of many pixels, and when we move our camera around there is some kind of change happening in these pixels. Optical Flow tries to figure out how that motion affects each individual pixel. So, we are trying to attach a motion vector to each pixel in the image, indicating where this pixel is moving to. Having that information is key to understand what is happening in an image, how objects are moving, and in what direction. Then, the next step is to generate plausible frames in-between these pixel changes. This is where VFI comes into play. We saw what VFI is and how it can increase the visual quality of a video. We also saw what Optical Flow is, why it is considered a core element of VFI, and how it can help us solve it. Now, it’s time to introduce RIFE and what it brings to the table. RIFE uses a neural network named IFNet that can directly estimate the intermediate flows from images. The main contributions of this new work are summarized below: The design of a novel and efficient network architecture, to simplify the flow-based VFI methods. Thus, given two input frames, the proposed model can be trained from scratch and directly approximate the intermediate flows. A novel leakage distillation loss function, which leads to a more stable convergence and large performance improvement The first flow-based real-time VFI algorithm that can process 720p videos at 30FPS Below we can see some examples of videos processed with RIFE. On the left, we see the original video, and on the right its enhanced version. Watch how smoother the processed version is. For more details, you can read the paper on ArXiv and browse through the project’s page. Let’s get into the fun part: use RIFE on our own videos! Using RIFE on our own videos it’s really easy. However, if we really want it to shine, we need an Nvidia GPU. To this end, let’s use Google Colab! Got to colab.research.google.com and create a new Notebook, with GPU support. If you haven’t done this before, select Change Runtime Type from the Runtime menu and select GPU. Now, we are ready to clone the RIFE repo. In a cell type the following: !git clone https://github.com/hzwer/arXiv2020-RIFE Next, we should download the pre-trained models, so we can generate predictions for the video’s frames. To achieve this, we use a Python’s module that makes it easy to download objects from Google Drive: gdown !gdown --id 1zYc3PEN4t6GOUoVYJjvcXoMmM3kFDNGS!7z e RIFE_trained_model_new.zip We have now downloaded the model’s weights and extracted them into our workspace. Let’s move them to the folder that the software expects them to be. !mkdir /content/arXiv2020-RIFE/train_log!mv *.pkl /content/arXiv2020-RIFE/train_log/ Next, we should install the project’s dependencies. cd into the project’s folder and use pip to install the necessary packages: %cd /content/arXiv2020-RIFE/!pip3 install -r requirements.txt Finally, upload your video into the project’s folder and run the following command: !python3 inference_video.py --exp=2 --video=mydemo.mp4 This script will quadruple the number of frames in your video. The output will be stored in the same location and its name will be something like mydemo_4X_120fps.mp4. Congratulations! Your new, enhanced video is now ready! There are some other options you can pass to the script. One of the most useful ones is --montage, which creates a montage between the original and the generated videos. Try it to compare the two items easily. In this story, we saw what Optical Flow is and how it is related to Video Frame Interpolation. We examined what are the goals of these two methods, and how a new technique, RIFE: Real-Time Intermediate Flow Estimation for VFI, can be used to generate impressive new content. Finally, we played with RIFE and our own videos. I kept the best part for the end: there is already a new Windows app that uses RIFE to provide Fast Video Interpolation for any GPU: Flowframes. However, using python you can reap the benefits of RIFE on any GPU-enabled machine! My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Opinions expressed are solely my own and do not express the views or opinions of my employer.
[ { "code": null, "e": 455, "s": 172, "text": "We can all agree that slow-motion videos create this dramatic effect, which certainly adds an extra flavor to specific scenes. On the other hand, slowing down a video might create several unwanted artifacts, which could deem it unwatchable. But what makes a slow-motion video great?" }, { "code": null, "e": 580, "s": 455, "text": "Let’s use Deep Learning for free, to produce the smooth result of a high-end camera capable of recording at high frame-rates" }, { "code": null, "e": 987, "s": 580, "text": "Among other things, I would argue that the most important aspect is its FPS count: how many frames per second are rendered to the screen. Too low and the video stutters, creating an unpleasant viewing experience. Thus, we need to have an expensive camera able to record at a high frame-rate. Or, we could use Deep Learning for free, and try to synthesize intermediate images between two consecutive frames." }, { "code": null, "e": 1348, "s": 987, "text": "Super slow-motion is just one of the applications of Video Frame Interpolation or VFI as it’s commonly known in the field of Computer Vision. In this story, we present RIFE: Real-Time Intermediate Flow Estimation for Video Frame Interpolation. We touch on what it is bringing to the table and take it for a quick test drive using our own videos. Let’s dive in!" }, { "code": null, "e": 1548, "s": 1348, "text": "Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!" }, { "code": null, "e": 1841, "s": 1548, "text": "The ultimate goal for Video Frame Interpolation (VFI) is to improve the frame rate and enhance the visual quality of a video. To achieve this, it tries to synthesize intermediate images between two consecutive frames, that are both spatially and temporally coherent with the existing context." }, { "code": null, "e": 2087, "s": 1841, "text": "In the core of VFI, we find another vision task named Optical Flow. So, let’s take a quick detour to see what Optical Flow means, and how it helps us with VFI. Then, we will be ready to watch RIFE in action and play with it using our own videos." }, { "code": null, "e": 2315, "s": 2087, "text": "Very broadly, Optical Flow is understanding how things are moving in an image, at the pixel level. This is useful for a number of downstream video editing tasks, such as video analysis, image stabilization, and video alignment." }, { "code": null, "e": 2638, "s": 2315, "text": "An image is comprised of many pixels, and when we move our camera around there is some kind of change happening in these pixels. Optical Flow tries to figure out how that motion affects each individual pixel. So, we are trying to attach a motion vector to each pixel in the image, indicating where this pixel is moving to." }, { "code": null, "e": 2880, "s": 2638, "text": "Having that information is key to understand what is happening in an image, how objects are moving, and in what direction. Then, the next step is to generate plausible frames in-between these pixel changes. This is where VFI comes into play." }, { "code": null, "e": 3131, "s": 2880, "text": "We saw what VFI is and how it can increase the visual quality of a video. We also saw what Optical Flow is, why it is considered a core element of VFI, and how it can help us solve it. Now, it’s time to introduce RIFE and what it brings to the table." }, { "code": null, "e": 3295, "s": 3131, "text": "RIFE uses a neural network named IFNet that can directly estimate the intermediate flows from images. The main contributions of this new work are summarized below:" }, { "code": null, "e": 3519, "s": 3295, "text": "The design of a novel and efficient network architecture, to simplify the flow-based VFI methods. Thus, given two input frames, the proposed model can be trained from scratch and directly approximate the intermediate flows." }, { "code": null, "e": 3638, "s": 3519, "text": "A novel leakage distillation loss function, which leads to a more stable convergence and large performance improvement" }, { "code": null, "e": 3721, "s": 3638, "text": "The first flow-based real-time VFI algorithm that can process 720p videos at 30FPS" }, { "code": null, "e": 3907, "s": 3721, "text": "Below we can see some examples of videos processed with RIFE. On the left, we see the original video, and on the right its enhanced version. Watch how smoother the processed version is." }, { "code": null, "e": 4053, "s": 3907, "text": "For more details, you can read the paper on ArXiv and browse through the project’s page. Let’s get into the fun part: use RIFE on our own videos!" }, { "code": null, "e": 4200, "s": 4053, "text": "Using RIFE on our own videos it’s really easy. However, if we really want it to shine, we need an Nvidia GPU. To this end, let’s use Google Colab!" }, { "code": null, "e": 4376, "s": 4200, "text": "Got to colab.research.google.com and create a new Notebook, with GPU support. If you haven’t done this before, select Change Runtime Type from the Runtime menu and select GPU." }, { "code": null, "e": 4448, "s": 4376, "text": "Now, we are ready to clone the RIFE repo. In a cell type the following:" }, { "code": null, "e": 4499, "s": 4448, "text": "!git clone https://github.com/hzwer/arXiv2020-RIFE" }, { "code": null, "e": 4709, "s": 4499, "text": "Next, we should download the pre-trained models, so we can generate predictions for the video’s frames. To achieve this, we use a Python’s module that makes it easy to download objects from Google Drive: gdown" }, { "code": null, "e": 4787, "s": 4709, "text": "!gdown --id 1zYc3PEN4t6GOUoVYJjvcXoMmM3kFDNGS!7z e RIFE_trained_model_new.zip" }, { "code": null, "e": 4937, "s": 4787, "text": "We have now downloaded the model’s weights and extracted them into our workspace. Let’s move them to the folder that the software expects them to be." }, { "code": null, "e": 5022, "s": 4937, "text": "!mkdir /content/arXiv2020-RIFE/train_log!mv *.pkl /content/arXiv2020-RIFE/train_log/" }, { "code": null, "e": 5150, "s": 5022, "text": "Next, we should install the project’s dependencies. cd into the project’s folder and use pip to install the necessary packages:" }, { "code": null, "e": 5212, "s": 5150, "text": "%cd /content/arXiv2020-RIFE/!pip3 install -r requirements.txt" }, { "code": null, "e": 5296, "s": 5212, "text": "Finally, upload your video into the project’s folder and run the following command:" }, { "code": null, "e": 5351, "s": 5296, "text": "!python3 inference_video.py --exp=2 --video=mydemo.mp4" }, { "code": null, "e": 5575, "s": 5351, "text": "This script will quadruple the number of frames in your video. The output will be stored in the same location and its name will be something like mydemo_4X_120fps.mp4. Congratulations! Your new, enhanced video is now ready!" }, { "code": null, "e": 5785, "s": 5575, "text": "There are some other options you can pass to the script. One of the most useful ones is --montage, which creates a montage between the original and the generated videos. Try it to compare the two items easily." }, { "code": null, "e": 6060, "s": 5785, "text": "In this story, we saw what Optical Flow is and how it is related to Video Frame Interpolation. We examined what are the goals of these two methods, and how a new technique, RIFE: Real-Time Intermediate Flow Estimation for VFI, can be used to generate impressive new content." }, { "code": null, "e": 6338, "s": 6060, "text": "Finally, we played with RIFE and our own videos. I kept the best part for the end: there is already a new Windows app that uses RIFE to provide Fast Video Interpolation for any GPU: Flowframes. However, using python you can reap the benefits of RIFE on any GPU-enabled machine!" }, { "code": null, "e": 6595, "s": 6338, "text": "My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA." }, { "code": null, "e": 6761, "s": 6595, "text": "If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter." } ]
Real Time Prediction using ResNet Model
ResNet is a pre-trained model. It is trained using ImageNet. ResNet model weights pre-trained on ImageNet. It has the following syntax − keras.applications.resnet.ResNet50 ( include_top = True, weights = 'imagenet', input_tensor = None, input_shape = None, pooling = None, classes = 1000 ) Here, include_top refers the fully-connected layer at the top of the network. include_top refers the fully-connected layer at the top of the network. weights refer pre-training on ImageNet. weights refer pre-training on ImageNet. input_tensor refers optional Keras tensor to use as image input for the model. input_tensor refers optional Keras tensor to use as image input for the model. input_shape refers optional shape tuple. The default input size for this model is 224x224. input_shape refers optional shape tuple. The default input size for this model is 224x224. classes refer optional number of classes to classify images. classes refer optional number of classes to classify images. Let us understand the model by writing a simple example − Let us load the necessary modules as specified below − >>> import PIL >>> from keras.preprocessing.image import load_img >>> from keras.preprocessing.image import img_to_array >>> from keras.applications.imagenet_utils import decode_predictions >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from keras.applications.resnet50 import ResNet50 >>> from keras.applications import resnet50 Let us choose an input image, Lotus as specified below − >>> filename = 'banana.jpg' >>> ## load an image in PIL format >>> original = load_img(filename, target_size = (224, 224)) >>> print('PIL image size',original.size) PIL image size (224, 224) >>> plt.imshow(original) <matplotlib.image.AxesImage object at 0x1304756d8> >>> plt.show() Here, we have loaded an image (banana.jpg) and displayed it. Let us convert our input, Banana into NumPy array, so that it can be passed into the model for the purpose of prediction. >>> #convert the PIL image to a numpy array >>> numpy_image = img_to_array(original) >>> plt.imshow(np.uint8(numpy_image)) <matplotlib.image.AxesImage object at 0x130475ac8> >>> print('numpy array size',numpy_image.shape) numpy array size (224, 224, 3) >>> # Convert the image / images into batch format >>> image_batch = np.expand_dims(numpy_image, axis = 0) >>> print('image batch size', image_batch.shape) image batch size (1, 224, 224, 3) >>> Let us feed our input into the model to get the predictions >>> prepare the image for the resnet50 model >>> >>> processed_image = resnet50.preprocess_input(image_batch.copy()) >>> # create resnet model >>>resnet_model = resnet50.ResNet50(weights = 'imagenet') >>> Downloavding data from https://github.com/fchollet/deep-learning-models/releas es/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5 102858752/102853048 [==============================] - 33s 0us/step >>> # get the predicted probabilities for each class >>> predictions = resnet_model.predict(processed_image) >>> # convert the probabilities to class labels >>> label = decode_predictions(predictions) Downloading data from https://storage.googleapis.com/download.tensorflow.org/ data/imagenet_class_index.json 40960/35363 [==================================] - 0s 0us/step >>> print(label) [ [ ('n07753592', 'banana', 0.99229723), ('n03532672', 'hook', 0.0014551596), ('n03970156', 'plunger', 0.0010738898), ('n07753113', 'fig', 0.0009359837) , ('n03109150', 'corkscrew', 0.00028538404) ] ] Here, the model predicted the images as banana correctly. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2188, "s": 2051, "text": "ResNet is a pre-trained model. It is trained using ImageNet. ResNet model weights pre-trained on ImageNet. It has the following syntax −" }, { "code": null, "e": 2364, "s": 2188, "text": "keras.applications.resnet.ResNet50 (\n include_top = True, \n weights = 'imagenet', \n input_tensor = None, \n input_shape = None, \n pooling = None, \n classes = 1000\n)" }, { "code": null, "e": 2370, "s": 2364, "text": "Here," }, { "code": null, "e": 2442, "s": 2370, "text": "include_top refers the fully-connected layer at the top of the network." }, { "code": null, "e": 2514, "s": 2442, "text": "include_top refers the fully-connected layer at the top of the network." }, { "code": null, "e": 2554, "s": 2514, "text": "weights refer pre-training on ImageNet." }, { "code": null, "e": 2594, "s": 2554, "text": "weights refer pre-training on ImageNet." }, { "code": null, "e": 2673, "s": 2594, "text": "input_tensor refers optional Keras tensor to use as image input for the model." }, { "code": null, "e": 2752, "s": 2673, "text": "input_tensor refers optional Keras tensor to use as image input for the model." }, { "code": null, "e": 2843, "s": 2752, "text": "input_shape refers optional shape tuple. The default input size for this model is 224x224." }, { "code": null, "e": 2934, "s": 2843, "text": "input_shape refers optional shape tuple. The default input size for this model is 224x224." }, { "code": null, "e": 2995, "s": 2934, "text": "classes refer optional number of classes to classify images." }, { "code": null, "e": 3056, "s": 2995, "text": "classes refer optional number of classes to classify images." }, { "code": null, "e": 3114, "s": 3056, "text": "Let us understand the model by writing a simple example −" }, { "code": null, "e": 3169, "s": 3114, "text": "Let us load the necessary modules as specified below −" }, { "code": null, "e": 3522, "s": 3169, "text": ">>> import PIL \n>>> from keras.preprocessing.image import load_img \n>>> from keras.preprocessing.image import img_to_array \n>>> from keras.applications.imagenet_utils import decode_predictions \n>>> import matplotlib.pyplot as plt \n>>> import numpy as np \n>>> from keras.applications.resnet50 import ResNet50 \n>>> from keras.applications import resnet50" }, { "code": null, "e": 3579, "s": 3522, "text": "Let us choose an input image, Lotus as specified below −" }, { "code": null, "e": 3867, "s": 3579, "text": ">>> filename = 'banana.jpg' \n>>> ## load an image in PIL format \n>>> original = load_img(filename, target_size = (224, 224)) \n>>> print('PIL image size',original.size)\nPIL image size (224, 224) \n>>> plt.imshow(original) \n<matplotlib.image.AxesImage object at 0x1304756d8> \n>>> plt.show()" }, { "code": null, "e": 3928, "s": 3867, "text": "Here, we have loaded an image (banana.jpg) and displayed it." }, { "code": null, "e": 4050, "s": 3928, "text": "Let us convert our input, Banana into NumPy array, so that it can be passed into the model for the purpose of prediction." }, { "code": null, "e": 4511, "s": 4050, "text": ">>> #convert the PIL image to a numpy array \n>>> numpy_image = img_to_array(original) \n\n>>> plt.imshow(np.uint8(numpy_image)) \n<matplotlib.image.AxesImage object at 0x130475ac8> \n\n>>> print('numpy array size',numpy_image.shape) \nnumpy array size (224, 224, 3) \n\n>>> # Convert the image / images into batch format \n>>> image_batch = np.expand_dims(numpy_image, axis = 0) \n\n>>> print('image batch size', image_batch.shape) \nimage batch size (1, 224, 224, 3)\n>>> " }, { "code": null, "e": 4571, "s": 4511, "text": "Let us feed our input into the model to get the predictions" }, { "code": null, "e": 5393, "s": 4571, "text": ">>> prepare the image for the resnet50 model >>> \n>>> processed_image = resnet50.preprocess_input(image_batch.copy()) \n\n>>> # create resnet model \n>>>resnet_model = resnet50.ResNet50(weights = 'imagenet') \n>>> Downloavding data from https://github.com/fchollet/deep-learning-models/releas\nes/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5 \n102858752/102853048 [==============================] - 33s 0us/step \n\n>>> # get the predicted probabilities for each class \n>>> predictions = resnet_model.predict(processed_image) \n\n>>> # convert the probabilities to class labels \n>>> label = decode_predictions(predictions) \nDownloading data from https://storage.googleapis.com/download.tensorflow.org/\ndata/imagenet_class_index.json \n40960/35363 [==================================] - 0s 0us/step \n\n>>> print(label)" }, { "code": null, "e": 5635, "s": 5393, "text": "[\n [\n ('n07753592', 'banana', 0.99229723), \n ('n03532672', 'hook', 0.0014551596), \n ('n03970156', 'plunger', 0.0010738898), \n ('n07753113', 'fig', 0.0009359837) , \n ('n03109150', 'corkscrew', 0.00028538404)\n ]\n]\n" }, { "code": null, "e": 5693, "s": 5635, "text": "Here, the model predicted the images as banana correctly." }, { "code": null, "e": 5727, "s": 5693, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 5744, "s": 5727, "text": " Abhilash Nelson" }, { "code": null, "e": 5777, "s": 5744, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 5799, "s": 5777, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5832, "s": 5799, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 5854, "s": 5832, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5887, "s": 5854, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 5909, "s": 5887, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5942, "s": 5909, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 5964, "s": 5942, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5997, "s": 5964, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 6008, "s": 5997, "text": " Mike West" }, { "code": null, "e": 6015, "s": 6008, "text": " Print" }, { "code": null, "e": 6026, "s": 6015, "text": " Add Notes" } ]
Essential Python Coding Questions for Data Science Interviews | by Leihua Ye, PhD | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Powered by Play.ht As the engineering culture keeps growing, Data Scientists often team up with other engineers to build pipelines and perform a ton of soft engineering stuff. Job candidates are expected to face extensive coding challenges in R/Python and SQL (Essential and Tricky SQL). From my past interview experiences, simply being able to code is far from enough. What differentiates experienced programmers from code-camp-trained beginners is the ability to dissect the big question into smaller pieces and then code it up. It’s my “aha” moment. For the past few months, I’ve been deliberately practiced to dissect the code and walk through my thinking processes, as many you may notice if you track my progress. I will do the same for today’s content. Data manipulation and string extraction are essential components of Data Science Interviews, both as an individual subject or combined with other topics. I’ve elaborated on 6 Python questions for Data Scientists in a previous post and provide additional authentic interview questions asked by major tech companies: towardsdatascience.com There is a common misconception in the field, which is using the Brutal Force method isn’t something worth recommending due to its inefficiency and memory usage. Here, I tend to argue differently. It is extremely helpful for new Python programmers because brutal force solves the problem step by step and reinforces our logical reasoning skills, aka, a better understanding of the question and a better “idea-realization” ability. Without further ado, let’s dig in - Write a function that reverses the string. - sentence = “I love programming in Python. How about you?” This is a warm-up question but can be complicated after embedding it into a larger question. Anyway, the most straightforward way of reversing a string is to access it backward. '?uoy tuoba woH .nohtyP ni gnimmargorp evol I' '?uoy tuoba woH .nohtyP ni gnimmargorp evol I' If asked for an alternative approach, I’d recommend list comprehension for its simplicity. - The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1, F(n) = F(n -1) + F(n-2), for n > 1. - Given n, calculate F(n). - https://leetcode.com/problems/fibonacci-number/ This is the type of “if-you-know-you-know”question. Interview candidates either love it or hate it, depending on which side they are on. If they are familiar with the shortcut, it’s almost a one-liner coding. Otherwise, it can be unnecessarily tedious and even unsolvable. First off, I will use brutal force to speak out my thoughts before presenting a better solution. As a rule of thumb, it is a good idea to list some Fibonacci numbers and try to spot any consistent patterns if we code up the naive way. F(1) = 1. F(2) = F(1) +F(0) = 1+0 = 1 F(3) =F(2) + F(1) = 1+1 = 2 F(4) = F(3) + F(2) = 2+1 = 3 F(5) = F(4) + F(3) = 3+ 2 = 5 ... Have you found any useful pattern? As it turns out, this is an iterative process. At each step, we have to update three values sequentially and prepare values for the next iteration. See the following code for detailed explanations. 2 As seen, it becomes unnecessarily tedious when a simple solution exists. Most likely, your interviewers will ask you to improve it. 2 Actually, the Fibonacci number is the ideal scenario for the adoption of recursion. We specify the base condition when n ≤1 and apply the function to itself two times. Neat solution! Your interviewer is happy now. - Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.- A string is represented by an array if the array elements concatenated in order forms the string.- https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ The question asks if two string arrays are the same. To be the same, they have to contain the same elements and order. For example, the following two arrays are not the same due to different element orders: word1 = [“a”, “cb”], word2 = [“ab”, “c”] The brutal method suggests that we can create two new strings and iterate elements from each array into the empty strings, respectively, and decide if they are the same. True This is not an optimal solution as it has created two new objects, which take up additional space, and for loops are generally not efficient in terms of speed. Solution 1 causes delays if the data is large. Your interviewer is not satisfied and asks for improvements. Well, let’s do solution 2. True The join() method is a powerful tool. We can join elements from two arrays into empty strings and check if they are the same without creating anything additional. Terrific! You passed the interview. - Given a square matrix mat, return the sum of the matrix diagonals.- Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.- https://leetcode.com/problems/matrix-diagonal-sum/ TBH, I was stuck for good 20 minutes for two reasons. First, I didn’t realize I don’t have to deduct the center element but only when the matrix length is odd. Second, I wasn’t sure how to add elements on the secondary diagonal. After some exploring and checking out others’ Leetcode solutions, I come up with the following code. 8 The Runtime and memory usage are above 80%, according to Leetcode. Is there any better solution for question 4? Please let me know if you know one. (updated on 1–14, 2021. Thanks to Nebadita Nayak, we have a better solution now.) Credits to Nebadita Nayak: - Given the array prices where prices[i] is the price of the ith item in a shop. - There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.- Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.- https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ I made a mistake for the first trial. I thought j has to be at the next position to i, aka. j = i+1. As it turns out, j could be anywhere as long as it is bigger than i. I didn’t get it until cross-checking my submission with the correct output. Also, we have to break the for loop once we have found one element; otherwise, the for loop will iterate over the entire array. The nested for loop takes up a ton of time and has an O(N2) runtime, which can be improved using another data type, stack (link). I’ll write another post on the topic. - Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.- https://leetcode.com/problems/reverse-words-in-a-string-iii/ This question has several variations. While reading the above information, I have some general direction. To reverse each character but keep the original order, I can split the string using whitespace as the separator. Then, reverse the word via word[::-1] and add whitespaces back between words. Include the rstrip() method to strip away the trailing whitespace. However, all other steps work except the returning results contain whitespace, which stops me from correctly submitting the code. def reverse_words(s): result = “” new = s.split(“ “) for word in new: word = word[::-1]+” “ result += word result.rstrip() # don't put it here return result # instead, put it here If I put rstrip() before the return command, it won’t work as intended. It generates the following result with trailing whitespace. "s'teL ekat edoCteeL tsetnoc " # trailing whitespace Every single line of code works fine except for the last one. Bummer! After Googling around, I find that rstrip() has to be at the beginning or end. It won’t work if it’s in the middle. After fixing the glitch, here we go. "s'teL ekat edoCteeL tsetnoc" Again, the rstrip() method has to be in the end or the beginning! The complete Python code is available on my Github. I love takeaways because this is the section where I reflect on my past mistakes and learn from them, which is today’s first lesson. Though brutal force is not recommended, it helps us better understand the underlying logic and document our thinking. There is no such thing as good coding, as there are always better solutions out there, which is why our interviews keep asking for improvement. Try another data type/structure? Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com towardsdatascience.com towardsdatascience.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 257, "s": 238, "text": "Powered by Play.ht" }, { "code": null, "e": 526, "s": 257, "text": "As the engineering culture keeps growing, Data Scientists often team up with other engineers to build pipelines and perform a ton of soft engineering stuff. Job candidates are expected to face extensive coding challenges in R/Python and SQL (Essential and Tricky SQL)." }, { "code": null, "e": 769, "s": 526, "text": "From my past interview experiences, simply being able to code is far from enough. What differentiates experienced programmers from code-camp-trained beginners is the ability to dissect the big question into smaller pieces and then code it up." }, { "code": null, "e": 791, "s": 769, "text": "It’s my “aha” moment." }, { "code": null, "e": 998, "s": 791, "text": "For the past few months, I’ve been deliberately practiced to dissect the code and walk through my thinking processes, as many you may notice if you track my progress. I will do the same for today’s content." }, { "code": null, "e": 1313, "s": 998, "text": "Data manipulation and string extraction are essential components of Data Science Interviews, both as an individual subject or combined with other topics. I’ve elaborated on 6 Python questions for Data Scientists in a previous post and provide additional authentic interview questions asked by major tech companies:" }, { "code": null, "e": 1336, "s": 1313, "text": "towardsdatascience.com" }, { "code": null, "e": 1498, "s": 1336, "text": "There is a common misconception in the field, which is using the Brutal Force method isn’t something worth recommending due to its inefficiency and memory usage." }, { "code": null, "e": 1767, "s": 1498, "text": "Here, I tend to argue differently. It is extremely helpful for new Python programmers because brutal force solves the problem step by step and reinforces our logical reasoning skills, aka, a better understanding of the question and a better “idea-realization” ability." }, { "code": null, "e": 1801, "s": 1767, "text": "Without further ado, let’s dig in" }, { "code": null, "e": 1846, "s": 1801, "text": "- Write a function that reverses the string." }, { "code": null, "e": 1906, "s": 1846, "text": "- sentence = “I love programming in Python. How about you?”" }, { "code": null, "e": 2084, "s": 1906, "text": "This is a warm-up question but can be complicated after embedding it into a larger question. Anyway, the most straightforward way of reversing a string is to access it backward." }, { "code": null, "e": 2131, "s": 2084, "text": "'?uoy tuoba woH .nohtyP ni gnimmargorp evol I'" }, { "code": null, "e": 2178, "s": 2131, "text": "'?uoy tuoba woH .nohtyP ni gnimmargorp evol I'" }, { "code": null, "e": 2269, "s": 2178, "text": "If asked for an alternative approach, I’d recommend list comprehension for its simplicity." }, { "code": null, "e": 2447, "s": 2269, "text": "- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1." }, { "code": null, "e": 2456, "s": 2447, "text": "That is," }, { "code": null, "e": 2476, "s": 2456, "text": "F(0) = 0, F(1) = 1," }, { "code": null, "e": 2512, "s": 2476, "text": "F(n) = F(n -1) + F(n-2), for n > 1." }, { "code": null, "e": 2539, "s": 2512, "text": "- Given n, calculate F(n)." }, { "code": null, "e": 2589, "s": 2539, "text": "- https://leetcode.com/problems/fibonacci-number/" }, { "code": null, "e": 2862, "s": 2589, "text": "This is the type of “if-you-know-you-know”question. Interview candidates either love it or hate it, depending on which side they are on. If they are familiar with the shortcut, it’s almost a one-liner coding. Otherwise, it can be unnecessarily tedious and even unsolvable." }, { "code": null, "e": 3097, "s": 2862, "text": "First off, I will use brutal force to speak out my thoughts before presenting a better solution. As a rule of thumb, it is a good idea to list some Fibonacci numbers and try to spot any consistent patterns if we code up the naive way." }, { "code": null, "e": 3107, "s": 3097, "text": "F(1) = 1." }, { "code": null, "e": 3135, "s": 3107, "text": "F(2) = F(1) +F(0) = 1+0 = 1" }, { "code": null, "e": 3163, "s": 3135, "text": "F(3) =F(2) + F(1) = 1+1 = 2" }, { "code": null, "e": 3192, "s": 3163, "text": "F(4) = F(3) + F(2) = 2+1 = 3" }, { "code": null, "e": 3222, "s": 3192, "text": "F(5) = F(4) + F(3) = 3+ 2 = 5" }, { "code": null, "e": 3226, "s": 3222, "text": "..." }, { "code": null, "e": 3261, "s": 3226, "text": "Have you found any useful pattern?" }, { "code": null, "e": 3459, "s": 3261, "text": "As it turns out, this is an iterative process. At each step, we have to update three values sequentially and prepare values for the next iteration. See the following code for detailed explanations." }, { "code": null, "e": 3461, "s": 3459, "text": "2" }, { "code": null, "e": 3593, "s": 3461, "text": "As seen, it becomes unnecessarily tedious when a simple solution exists. Most likely, your interviewers will ask you to improve it." }, { "code": null, "e": 3595, "s": 3593, "text": "2" }, { "code": null, "e": 3763, "s": 3595, "text": "Actually, the Fibonacci number is the ideal scenario for the adoption of recursion. We specify the base condition when n ≤1 and apply the function to itself two times." }, { "code": null, "e": 3778, "s": 3763, "text": "Neat solution!" }, { "code": null, "e": 3809, "s": 3778, "text": "Your interviewer is happy now." }, { "code": null, "e": 4103, "s": 3809, "text": "- Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.- A string is represented by an array if the array elements concatenated in order forms the string.- https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/" }, { "code": null, "e": 4310, "s": 4103, "text": "The question asks if two string arrays are the same. To be the same, they have to contain the same elements and order. For example, the following two arrays are not the same due to different element orders:" }, { "code": null, "e": 4351, "s": 4310, "text": "word1 = [“a”, “cb”], word2 = [“ab”, “c”]" }, { "code": null, "e": 4521, "s": 4351, "text": "The brutal method suggests that we can create two new strings and iterate elements from each array into the empty strings, respectively, and decide if they are the same." }, { "code": null, "e": 4526, "s": 4521, "text": "True" }, { "code": null, "e": 4733, "s": 4526, "text": "This is not an optimal solution as it has created two new objects, which take up additional space, and for loops are generally not efficient in terms of speed. Solution 1 causes delays if the data is large." }, { "code": null, "e": 4794, "s": 4733, "text": "Your interviewer is not satisfied and asks for improvements." }, { "code": null, "e": 4821, "s": 4794, "text": "Well, let’s do solution 2." }, { "code": null, "e": 4826, "s": 4821, "text": "True" }, { "code": null, "e": 4989, "s": 4826, "text": "The join() method is a powerful tool. We can join elements from two arrays into empty strings and check if they are the same without creating anything additional." }, { "code": null, "e": 5025, "s": 4989, "text": "Terrific! You passed the interview." }, { "code": null, "e": 5302, "s": 5025, "text": "- Given a square matrix mat, return the sum of the matrix diagonals.- Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.- https://leetcode.com/problems/matrix-diagonal-sum/" }, { "code": null, "e": 5632, "s": 5302, "text": "TBH, I was stuck for good 20 minutes for two reasons. First, I didn’t realize I don’t have to deduct the center element but only when the matrix length is odd. Second, I wasn’t sure how to add elements on the secondary diagonal. After some exploring and checking out others’ Leetcode solutions, I come up with the following code." }, { "code": null, "e": 5634, "s": 5632, "text": "8" }, { "code": null, "e": 5782, "s": 5634, "text": "The Runtime and memory usage are above 80%, according to Leetcode. Is there any better solution for question 4? Please let me know if you know one." }, { "code": null, "e": 5864, "s": 5782, "text": "(updated on 1–14, 2021. Thanks to Nebadita Nayak, we have a better solution now.)" }, { "code": null, "e": 5891, "s": 5864, "text": "Credits to Nebadita Nayak:" }, { "code": null, "e": 6446, "s": 5891, "text": "- Given the array prices where prices[i] is the price of the ith item in a shop. - There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.- Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.- https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/" }, { "code": null, "e": 6692, "s": 6446, "text": "I made a mistake for the first trial. I thought j has to be at the next position to i, aka. j = i+1. As it turns out, j could be anywhere as long as it is bigger than i. I didn’t get it until cross-checking my submission with the correct output." }, { "code": null, "e": 6820, "s": 6692, "text": "Also, we have to break the for loop once we have found one element; otherwise, the for loop will iterate over the entire array." }, { "code": null, "e": 6988, "s": 6820, "text": "The nested for loop takes up a ton of time and has an O(N2) runtime, which can be improved using another data type, stack (link). I’ll write another post on the topic." }, { "code": null, "e": 7201, "s": 6988, "text": "- Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.- https://leetcode.com/problems/reverse-words-in-a-string-iii/" }, { "code": null, "e": 7565, "s": 7201, "text": "This question has several variations. While reading the above information, I have some general direction. To reverse each character but keep the original order, I can split the string using whitespace as the separator. Then, reverse the word via word[::-1] and add whitespaces back between words. Include the rstrip() method to strip away the trailing whitespace." }, { "code": null, "e": 7695, "s": 7565, "text": "However, all other steps work except the returning results contain whitespace, which stops me from correctly submitting the code." }, { "code": null, "e": 7927, "s": 7695, "text": "def reverse_words(s): result = “” new = s.split(“ “) for word in new: word = word[::-1]+” “ result += word result.rstrip() # don't put it here return result # instead, put it here" }, { "code": null, "e": 8059, "s": 7927, "text": "If I put rstrip() before the return command, it won’t work as intended. It generates the following result with trailing whitespace." }, { "code": null, "e": 8115, "s": 8059, "text": "\"s'teL ekat edoCteeL tsetnoc \" # trailing whitespace" }, { "code": null, "e": 8301, "s": 8115, "text": "Every single line of code works fine except for the last one. Bummer! After Googling around, I find that rstrip() has to be at the beginning or end. It won’t work if it’s in the middle." }, { "code": null, "e": 8338, "s": 8301, "text": "After fixing the glitch, here we go." }, { "code": null, "e": 8368, "s": 8338, "text": "\"s'teL ekat edoCteeL tsetnoc\"" }, { "code": null, "e": 8434, "s": 8368, "text": "Again, the rstrip() method has to be in the end or the beginning!" }, { "code": null, "e": 8486, "s": 8434, "text": "The complete Python code is available on my Github." }, { "code": null, "e": 8619, "s": 8486, "text": "I love takeaways because this is the section where I reflect on my past mistakes and learn from them, which is today’s first lesson." }, { "code": null, "e": 8737, "s": 8619, "text": "Though brutal force is not recommended, it helps us better understand the underlying logic and document our thinking." }, { "code": null, "e": 8914, "s": 8737, "text": "There is no such thing as good coding, as there are always better solutions out there, which is why our interviews keep asking for improvement. Try another data type/structure?" }, { "code": null, "e": 9126, "s": 8914, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 9147, "s": 9126, "text": "leihua-ye.medium.com" }, { "code": null, "e": 9170, "s": 9147, "text": "towardsdatascience.com" }, { "code": null, "e": 9193, "s": 9170, "text": "towardsdatascience.com" }, { "code": null, "e": 9233, "s": 9193, "text": "Please find me on LinkedIn and Youtube." } ]
AngularJS | SQL - GeeksforGeeks
14 Aug, 2020 In any web application we need to save, update, insert and fetch data to and from a database. AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google. It helps developers to build well structured, easily testable, and maintainable front-end applications. Features Important concepts in Angular JS Library is given below: Concept Template Directives Model Scope Expressions Compiler Filter Data Binding Controller Module Service Need of AngularJS Framework explanation with a basic example With the directives to the HTML elements and attributes, dynamic web pages are easily created by adding additional coding. AngularJS is pretty much helpful for displaying data from a Database. Provided data should be in a JSON format. Let’s see an example of it. Data is in MySQL and on server-side PHP interacts with MySQL and gets the data in JSON format. Angular JS displays the output. With the basic example below, let us see in detail about Angular JS SQL. Example: <html> <style> table, th, td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <div ng-app="empApp" ng-controller="employeeCtrl"> <table> <tr ng-repeat="output in names"> <td>{{ output.Name }}</td> <td>{{ output.Country }}</td> </tr> </table> </div> <script> var app = angular.module("empApp", []); app.controller( "employeeCtrl", function ($scope, $http) { $http.get( "employee_mysql.php").then(function (response) { $scope.names = response.data.records; }); }); </script> </body></html> Explanation: The ng-app directive is a starting point. Here “empApp” is given in ng-app, here initialization is started and compiles the HTML template ng-controller is used to specify a controller in the HTML element. This controller will add behavior or maintain the data in that HTML element and its child elements Server Code PHP and MySQL Main thing here is the output should be in the format of JSON Server Code PHP and MySQL: <?phpheader("Access-Control-Allow-Origin: *");header("Content-Type: application/json; charset=UTF-8"); $connection = new mysqli("myServer", "<username>", "<password>", "<dbname>"); $result = $connection->query("SELECT EmployeeName, EmployeeCity,EmployeeCountry FROM Employees"); $output = "";while ($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($output != "") { $output = ", "; } $output .= '{"Name":"' . $rs["EmployeeName"] . '", '; $output .= '"City":"' . $rs["EmployeeCity"] . '", '; $output .= '"Country":"' . $rs["EmployeeCountry"] . '"}';}$output = '{"records":[' . $output . ']}';$connection->close(); echo $output;?> Assume that the Employees table is having 6 records and they are in MySQL. PHP code retrieves the data from MySQL in the format of JSON and angular JS displays the output.Output: HTML Code: <!DOCTYPE html><html> <style> table, th, td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> <table> <tr> <td>Avinash</td> <td>USA</td> </tr> <tr> <td>Aisha</td> <td>UK</td> </tr> <tr> <td>Emma</td> <td>Australia</td> </tr> <tr> <td>Shreyas</td> <td>India</td> </tr> <tr> <td>Rachel</td> <td>USA</td> </tr> <tr> <td>Shravan</td> <td>India</td> </tr> </table></html> Output: AngularJS-Misc Picked AngularJS PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular PrimeNG Dropdown Component Angular | keyup event Auth Guards in Angular 9/10/11 How to Display Spinner on the Screen till the data from the API loads using Angular 8 ? How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ?
[ { "code": null, "e": 29540, "s": 29512, "text": "\n14 Aug, 2020" }, { "code": null, "e": 29824, "s": 29540, "text": "In any web application we need to save, update, insert and fetch data to and from a database. AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google. It helps developers to build well structured, easily testable, and maintainable front-end applications." }, { "code": null, "e": 29890, "s": 29824, "text": "Features Important concepts in Angular JS Library is given below:" }, { "code": null, "e": 29898, "s": 29890, "text": "Concept" }, { "code": null, "e": 29907, "s": 29898, "text": "Template" }, { "code": null, "e": 29918, "s": 29907, "text": "Directives" }, { "code": null, "e": 29924, "s": 29918, "text": "Model" }, { "code": null, "e": 29930, "s": 29924, "text": "Scope" }, { "code": null, "e": 29942, "s": 29930, "text": "Expressions" }, { "code": null, "e": 29951, "s": 29942, "text": "Compiler" }, { "code": null, "e": 29958, "s": 29951, "text": "Filter" }, { "code": null, "e": 29971, "s": 29958, "text": "Data Binding" }, { "code": null, "e": 29982, "s": 29971, "text": "Controller" }, { "code": null, "e": 29989, "s": 29982, "text": "Module" }, { "code": null, "e": 29997, "s": 29989, "text": "Service" }, { "code": null, "e": 30521, "s": 29997, "text": "Need of AngularJS Framework explanation with a basic example With the directives to the HTML elements and attributes, dynamic web pages are easily created by adding additional coding. AngularJS is pretty much helpful for displaying data from a Database. Provided data should be in a JSON format. Let’s see an example of it. Data is in MySQL and on server-side PHP interacts with MySQL and gets the data in JSON format. Angular JS displays the output. With the basic example below, let us see in detail about Angular JS SQL." }, { "code": null, "e": 30530, "s": 30521, "text": "Example:" }, { "code": "<html> <style> table, th, td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <body> <div ng-app=\"empApp\" ng-controller=\"employeeCtrl\"> <table> <tr ng-repeat=\"output in names\"> <td>{{ output.Name }}</td> <td>{{ output.Country }}</td> </tr> </table> </div> <script> var app = angular.module(\"empApp\", []); app.controller( \"employeeCtrl\", function ($scope, $http) { $http.get( \"employee_mysql.php\").then(function (response) { $scope.names = response.data.records; }); }); </script> </body></html>", "e": 31622, "s": 30530, "text": null }, { "code": null, "e": 32027, "s": 31622, "text": "Explanation: The ng-app directive is a starting point. Here “empApp” is given in ng-app, here initialization is started and compiles the HTML template ng-controller is used to specify a controller in the HTML element. This controller will add behavior or maintain the data in that HTML element and its child elements Server Code PHP and MySQL Main thing here is the output should be in the format of JSON" }, { "code": null, "e": 32054, "s": 32027, "text": "Server Code PHP and MySQL:" }, { "code": "<?phpheader(\"Access-Control-Allow-Origin: *\");header(\"Content-Type: application/json; charset=UTF-8\"); $connection = new mysqli(\"myServer\", \"<username>\", \"<password>\", \"<dbname>\"); $result = $connection->query(\"SELECT EmployeeName, EmployeeCity,EmployeeCountry FROM Employees\"); $output = \"\";while ($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($output != \"\") { $output = \", \"; } $output .= '{\"Name\":\"' . $rs[\"EmployeeName\"] . '\", '; $output .= '\"City\":\"' . $rs[\"EmployeeCity\"] . '\", '; $output .= '\"Country\":\"' . $rs[\"EmployeeCountry\"] . '\"}';}$output = '{\"records\":[' . $output . ']}';$connection->close(); echo $output;?>", "e": 32787, "s": 32054, "text": null }, { "code": null, "e": 32966, "s": 32787, "text": "Assume that the Employees table is having 6 records and they are in MySQL. PHP code retrieves the data from MySQL in the format of JSON and angular JS displays the output.Output:" }, { "code": null, "e": 32977, "s": 32966, "text": "HTML Code:" }, { "code": "<!DOCTYPE html><html> <style> table, th, td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> <table> <tr> <td>Avinash</td> <td>USA</td> </tr> <tr> <td>Aisha</td> <td>UK</td> </tr> <tr> <td>Emma</td> <td>Australia</td> </tr> <tr> <td>Shreyas</td> <td>India</td> </tr> <tr> <td>Rachel</td> <td>USA</td> </tr> <tr> <td>Shravan</td> <td>India</td> </tr> </table></html>", "e": 33822, "s": 32977, "text": null }, { "code": null, "e": 33830, "s": 33822, "text": "Output:" }, { "code": null, "e": 33845, "s": 33830, "text": "AngularJS-Misc" }, { "code": null, "e": 33852, "s": 33845, "text": "Picked" }, { "code": null, "e": 33862, "s": 33852, "text": "AngularJS" }, { "code": null, "e": 33866, "s": 33862, "text": "PHP" }, { "code": null, "e": 33883, "s": 33866, "text": "Web Technologies" }, { "code": null, "e": 33887, "s": 33883, "text": "PHP" }, { "code": null, "e": 33985, "s": 33887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34005, "s": 33985, "text": "Angular File Upload" }, { "code": null, "e": 34040, "s": 34005, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 34062, "s": 34040, "text": "Angular | keyup event" }, { "code": null, "e": 34093, "s": 34062, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 34181, "s": 34093, "text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?" }, { "code": null, "e": 34226, "s": 34181, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 34276, "s": 34226, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 34316, "s": 34276, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 34340, "s": 34316, "text": "PHP in_array() Function" } ]
How to select first object in object in AngularJS? - GeeksforGeeks
31 Oct, 2019 The main problem that we are dealing with is that for an object of objects reading the object of a particular index position is not as simple as a list. We cannot loop over it using ngFor as an object is not considered an iterable. The importance of this issue may arise when the data received from any source is an object containing objects(like JSON files).Altering the source file is very inconvenient so we need to be able to do something in the application itself. The most effective way is hidden in the problem itself. If objects are not iterable convert them to iterables. Two Approaches are discussed below to solve this problem. Approach 1:Using the ng-repeat directive and the limitTo filter.ng-repeat is able to iterate over the properties of objects which in our case are objects itself. The following syntax is used:< div ng-repeat="(key, value) in myObj" > ... < /div >limitTo filter creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning of the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit.Syntax:html binding: {{ limitTo_expression | limitTo : limit : begin}} Examples: the value of the limit can be changed to get the element(object in this case) of the iterable<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app='MyApp' ng-controller='MyCtrl'> <div ng-repeat="(key, obj) in institute | limitTo : 1"> <ul> <li ng-repeat="(prop, value) in obj"> {{prop}}: {{value}} </li> </ul> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { 'school': { location: 'Jamshedpur', name: 'RV' }, 'college': { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>Output: This is the elements of the first object of the object institute(mentioned in the code above). Using the ng-repeat directive and the limitTo filter. ng-repeat is able to iterate over the properties of objects which in our case are objects itself. The following syntax is used:< div ng-repeat="(key, value) in myObj" > ... < /div > < div ng-repeat="(key, value) in myObj" > ... < /div > limitTo filter creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning of the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Syntax: html binding: {{ limitTo_expression | limitTo : limit : begin}} Examples: the value of the limit can be changed to get the element(object in this case) of the iterable <!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app='MyApp' ng-controller='MyCtrl'> <div ng-repeat="(key, obj) in institute | limitTo : 1"> <ul> <li ng-repeat="(prop, value) in obj"> {{prop}}: {{value}} </li> </ul> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { 'school': { location: 'Jamshedpur', name: 'RV' }, 'college': { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html> Output: This is the elements of the first object of the object institute(mentioned in the code above). Approach 2:Convert the object of objects into an array of objects and use the indexing method of square brackets([]) to display the first object of the array.Syntax:{{name_of_the array[index]}}Examples: The value of the index is 0 for the first object of the array. Since the elements of the array are objects we can refer to the properties of the objects using the (.) operator.<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <div ng-app="MyApp" ng-controller="MyCtrl"> <p>The Name of the school is: {{institute[0].name}}</p> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { school: { location: 'Jamshedpur', name: 'RV' }, college: { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>Output: This shows one of the properties of the first object of the object institute(mentioned in the code above). Convert the object of objects into an array of objects and use the indexing method of square brackets([]) to display the first object of the array. Syntax: {{name_of_the array[index]}} Examples: The value of the index is 0 for the first object of the array. Since the elements of the array are objects we can refer to the properties of the objects using the (.) operator. <!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <div ng-app="MyApp" ng-controller="MyCtrl"> <p>The Name of the school is: {{institute[0].name}}</p> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { school: { location: 'Jamshedpur', name: 'RV' }, college: { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html> Output: This shows one of the properties of the first object of the object institute(mentioned in the code above). AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n31 Oct, 2019" }, { "code": null, "e": 26935, "s": 26354, "text": "The main problem that we are dealing with is that for an object of objects reading the object of a particular index position is not as simple as a list. We cannot loop over it using ngFor as an object is not considered an iterable. The importance of this issue may arise when the data received from any source is an object containing objects(like JSON files).Altering the source file is very inconvenient so we need to be able to do something in the application itself. The most effective way is hidden in the problem itself. If objects are not iterable convert them to iterables." }, { "code": null, "e": 26993, "s": 26935, "text": "Two Approaches are discussed below to solve this problem." }, { "code": null, "e": 28844, "s": 26993, "text": "Approach 1:Using the ng-repeat directive and the limitTo filter.ng-repeat is able to iterate over the properties of objects which in our case are objects itself. The following syntax is used:< div ng-repeat=\"(key, value) in myObj\" > ... < /div >limitTo filter creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning of the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit.Syntax:html binding:\n{{ limitTo_expression | limitTo : limit : begin}}\nExamples: the value of the limit can be changed to get the element(object in this case) of the iterable<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app='MyApp' ng-controller='MyCtrl'> <div ng-repeat=\"(key, obj) in institute | limitTo : 1\"> <ul> <li ng-repeat=\"(prop, value) in obj\"> {{prop}}: {{value}} </li> </ul> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { 'school': { location: 'Jamshedpur', name: 'RV' }, 'college': { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>Output: This is the elements of the first object of the object institute(mentioned in the code above)." }, { "code": null, "e": 28898, "s": 28844, "text": "Using the ng-repeat directive and the limitTo filter." }, { "code": null, "e": 29080, "s": 28898, "text": "ng-repeat is able to iterate over the properties of objects which in our case are objects itself. The following syntax is used:< div ng-repeat=\"(key, value) in myObj\" > ... < /div >" }, { "code": null, "e": 29135, "s": 29080, "text": "< div ng-repeat=\"(key, value) in myObj\" > ... < /div >" }, { "code": null, "e": 29395, "s": 29135, "text": "limitTo filter creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning of the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit." }, { "code": null, "e": 29403, "s": 29395, "text": "Syntax:" }, { "code": null, "e": 29468, "s": 29403, "text": "html binding:\n{{ limitTo_expression | limitTo : limit : begin}}\n" }, { "code": null, "e": 29572, "s": 29468, "text": "Examples: the value of the limit can be changed to get the element(object in this case) of the iterable" }, { "code": "<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app='MyApp' ng-controller='MyCtrl'> <div ng-repeat=\"(key, obj) in institute | limitTo : 1\"> <ul> <li ng-repeat=\"(prop, value) in obj\"> {{prop}}: {{value}} </li> </ul> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { 'school': { location: 'Jamshedpur', name: 'RV' }, 'college': { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>", "e": 30643, "s": 29572, "text": null }, { "code": null, "e": 30746, "s": 30643, "text": "Output: This is the elements of the first object of the object institute(mentioned in the code above)." }, { "code": null, "e": 32190, "s": 30746, "text": "Approach 2:Convert the object of objects into an array of objects and use the indexing method of square brackets([]) to display the first object of the array.Syntax:{{name_of_the array[index]}}Examples: The value of the index is 0 for the first object of the array. Since the elements of the array are objects we can refer to the properties of the objects using the (.) operator.<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <div ng-app=\"MyApp\" ng-controller=\"MyCtrl\"> <p>The Name of the school is: {{institute[0].name}}</p> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { school: { location: 'Jamshedpur', name: 'RV' }, college: { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>Output: This shows one of the properties of the first object of the object institute(mentioned in the code above)." }, { "code": null, "e": 32338, "s": 32190, "text": "Convert the object of objects into an array of objects and use the indexing method of square brackets([]) to display the first object of the array." }, { "code": null, "e": 32346, "s": 32338, "text": "Syntax:" }, { "code": null, "e": 32375, "s": 32346, "text": "{{name_of_the array[index]}}" }, { "code": null, "e": 32562, "s": 32375, "text": "Examples: The value of the index is 0 for the first object of the array. Since the elements of the array are objects we can refer to the properties of the objects using the (.) operator." }, { "code": "<!DOCTYPE html><html> <head> <title>Angular first object in object</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <div ng-app=\"MyApp\" ng-controller=\"MyCtrl\"> <p>The Name of the school is: {{institute[0].name}}</p> </div> <script> var app = angular.module('MyApp', []); app.controller('MyCtrl', function($scope) { $scope.institute = { school: { location: 'Jamshedpur', name: 'RV' }, college: { location: 'Kolkata', name: 'Jadavpur' } }; var instilist = new Array(); for (key of Object.keys($scope.institute)) { instilist.push($scope.institute[key]); } $scope.institute = instilist; }); </script></body> </html>", "e": 33513, "s": 32562, "text": null }, { "code": null, "e": 33628, "s": 33513, "text": "Output: This shows one of the properties of the first object of the object institute(mentioned in the code above)." }, { "code": null, "e": 33643, "s": 33628, "text": "AngularJS-Misc" }, { "code": null, "e": 33650, "s": 33643, "text": "Picked" }, { "code": null, "e": 33660, "s": 33650, "text": "AngularJS" }, { "code": null, "e": 33677, "s": 33660, "text": "Web Technologies" }, { "code": null, "e": 33704, "s": 33677, "text": "Web technologies Questions" }, { "code": null, "e": 33802, "s": 33704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33837, "s": 33802, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 33872, "s": 33837, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 33896, "s": 33872, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 33931, "s": 33896, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 33984, "s": 33931, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 34024, "s": 33984, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34057, "s": 34024, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34102, "s": 34057, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34145, "s": 34102, "text": "How to fetch data from an API in ReactJS ?" } ]
How to remove non-word characters in JavaScript?
To remove non-word characters we need to use regular expressions. The logic behind removing non-word characters is that just replace the non-word characters with nothing(''). In the following example there are many non-word characters and in between them there exists a text named "Tutorix is the best e-learning platform". So using regular expressions the non-word characters were replaced with nothing('') so as to get the word characters as the output. Live Demo <html> <body> <script type="text/javascript"> function remNonWord (string) { if ((string===null) || (string==='')) return false; else string = string.toString(); var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; return string.replace(PATTERN, ''); } document.write(remNonWord('Tutorix is the ~!@^&";\'/?>#$%*()+`={}[]|\\:<.,best e-learning platform')); </script> </body> </html> Tutorix is the best e-learning platform
[ { "code": null, "e": 1237, "s": 1062, "text": "To remove non-word characters we need to use regular expressions. The logic behind removing non-word characters is that just replace the non-word characters with nothing('')." }, { "code": null, "e": 1518, "s": 1237, "text": "In the following example there are many non-word characters and in between them there exists a text named \"Tutorix is the best e-learning platform\". So using regular expressions the non-word characters were replaced with nothing('') so as to get the word characters as the output." }, { "code": null, "e": 1528, "s": 1518, "text": "Live Demo" }, { "code": null, "e": 1983, "s": 1528, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n function remNonWord (string) {\n if ((string===null) || (string===''))\n return false;\n else\n string = string.toString();\n var PATTERN = /[^\\x20\\x2D0-9A-Z\\x5Fa-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\xFF]/g;\n return string.replace(PATTERN, '');\n }\n document.write(remNonWord('Tutorix is the ~!@^&\";\\'/?>#$%*()+`={}[]|\\\\:<.,best e-learning platform'));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2023, "s": 1983, "text": "Tutorix is the best e-learning platform" } ]
Delays in Computer Network - GeeksforGeeks
27 Sep, 2021 The delays, here, means the time for which the processing of a particular packet takes place. We have the following types of delays in computer networks: 1. Transmission Delay: The time taken to transmit a packet from the host to the transmission medium is called Transmission delay. For example, if bandwidth is 1 bps (every second 1 bit can be transmitted onto the transmission medium) and data size is 20 bits then what is the transmission delay? If in one second, 1 bit can be transmitted. To transmit 20 bits, 20 seconds would be required. Let B bps is the bandwidth and L bit is the size of the data then transmission delay is, Tt = L/B This delay depends upon the following factors: If there are multiple active sessions, the delay will become significant. Increasing bandwidth decreases transmission delay. MAC protocol largely influences the delay if the link is shared among multiple devices. Sending and receiving a packet involves a context switch in the operating system, which takes a finite time. 2. Propagation delay: After the packet is transmitted to the transmission medium, it has to go through the medium to reach the destination. Hence the time taken by the last bit of the packet to reach the destination is called propagation delay. Factors affecting propagation delay: Distance – It takes more time to reach the destination if the distance of the medium is longer. Velocity – If the velocity(speed) of the signal is higher, the packet will be received faster. Distance – It takes more time to reach the destination if the distance of the medium is longer. Velocity – If the velocity(speed) of the signal is higher, the packet will be received faster. Tp = Distance / Velocity Note: Velocity =3 X 10^8 m/s (for air) Velocity= 2.1 X 10^8 m/s (for optical fibre) 3. Queueing delay: Let the packet is received by the destination, the packet will not be processed by the destination immediately. It has to wait in a queue in something called a buffer. So the amount of time it waits in queue before being processed is called queueing delay. In general, we can’t calculate queueing delay because we don’t have any formula for that. This delay depends upon the following factors: If the size of the queue is large, the queuing delay will be huge. If the queue is empty there will be less or no delay. If more packets are arriving in a short or no time interval, queuing delay will be large. The less the number of servers/links, the greater is the queuing delay. 4. Processing delay: Now the packet will be taken for the processing which is called processing delay. Time is taken to process the data packet by the processor that is the time required by intermediate routers to decide where to forward the packet, update TTL, perform header checksum calculations. It also doesn’t have any formula since it depends upon the speed of the processor and the speed of the processor varies from computer to computer. Note: Both queueing delay and processing delay doesn’t have any formula because they depend on the speed of the processor This delay depends upon the following factors: It depends on the speed of the processor. Ttotal = Tt + Tp + Tq + Tpro Ttotal = Tt+Tp (when taking Tq and Tpro equals to 0) shrishti_m180521ca jeevanyasa Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Active and Passive attacks in Information Security Cryptography and its Types Multiple Access Protocols in Computer Network Intrusion Detection System (IDS) ACID Properties in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems Normal Forms in DBMS LRU Cache Implementation
[ { "code": null, "e": 24144, "s": 24116, "text": "\n27 Sep, 2021" }, { "code": null, "e": 24299, "s": 24144, "text": "The delays, here, means the time for which the processing of a particular packet takes place. We have the following types of delays in computer networks: " }, { "code": null, "e": 24430, "s": 24299, "text": "1. Transmission Delay: The time taken to transmit a packet from the host to the transmission medium is called Transmission delay. " }, { "code": null, "e": 24692, "s": 24430, "text": "For example, if bandwidth is 1 bps (every second 1 bit can be transmitted onto the transmission medium) and data size is 20 bits then what is the transmission delay? If in one second, 1 bit can be transmitted. To transmit 20 bits, 20 seconds would be required. " }, { "code": null, "e": 24782, "s": 24692, "text": "Let B bps is the bandwidth and L bit is the size of the data then transmission delay is, " }, { "code": null, "e": 24791, "s": 24782, "text": "Tt = L/B" }, { "code": null, "e": 24838, "s": 24791, "text": "This delay depends upon the following factors:" }, { "code": null, "e": 24912, "s": 24838, "text": "If there are multiple active sessions, the delay will become significant." }, { "code": null, "e": 24963, "s": 24912, "text": "Increasing bandwidth decreases transmission delay." }, { "code": null, "e": 25051, "s": 24963, "text": "MAC protocol largely influences the delay if the link is shared among multiple devices." }, { "code": null, "e": 25160, "s": 25051, "text": "Sending and receiving a packet involves a context switch in the operating system, which takes a finite time." }, { "code": null, "e": 25406, "s": 25160, "text": "2. Propagation delay: After the packet is transmitted to the transmission medium, it has to go through the medium to reach the destination. Hence the time taken by the last bit of the packet to reach the destination is called propagation delay. " }, { "code": null, "e": 25445, "s": 25406, "text": "Factors affecting propagation delay: " }, { "code": null, "e": 25638, "s": 25445, "text": "Distance – It takes more time to reach the destination if the distance of the medium is longer. Velocity – If the velocity(speed) of the signal is higher, the packet will be received faster. " }, { "code": null, "e": 25735, "s": 25638, "text": "Distance – It takes more time to reach the destination if the distance of the medium is longer. " }, { "code": null, "e": 25832, "s": 25735, "text": "Velocity – If the velocity(speed) of the signal is higher, the packet will be received faster. " }, { "code": null, "e": 25858, "s": 25832, "text": "Tp = Distance / Velocity " }, { "code": null, "e": 25866, "s": 25858, "text": "Note: " }, { "code": null, "e": 25945, "s": 25866, "text": "Velocity =3 X 10^8 m/s (for air)\nVelocity= 2.1 X 10^8 m/s (for optical fibre) " }, { "code": null, "e": 26222, "s": 25945, "text": "3. Queueing delay: Let the packet is received by the destination, the packet will not be processed by the destination immediately. It has to wait in a queue in something called a buffer. So the amount of time it waits in queue before being processed is called queueing delay. " }, { "code": null, "e": 26313, "s": 26222, "text": "In general, we can’t calculate queueing delay because we don’t have any formula for that. " }, { "code": null, "e": 26360, "s": 26313, "text": "This delay depends upon the following factors:" }, { "code": null, "e": 26481, "s": 26360, "text": "If the size of the queue is large, the queuing delay will be huge. If the queue is empty there will be less or no delay." }, { "code": null, "e": 26571, "s": 26481, "text": "If more packets are arriving in a short or no time interval, queuing delay will be large." }, { "code": null, "e": 26643, "s": 26571, "text": "The less the number of servers/links, the greater is the queuing delay." }, { "code": null, "e": 26746, "s": 26643, "text": "4. Processing delay: Now the packet will be taken for the processing which is called processing delay." }, { "code": null, "e": 26943, "s": 26746, "text": "Time is taken to process the data packet by the processor that is the time required by intermediate routers to decide where to forward the packet, update TTL, perform header checksum calculations." }, { "code": null, "e": 27093, "s": 26943, "text": " It also doesn’t have any formula since it depends upon the speed of the processor and the speed of the processor varies from computer to computer. " }, { "code": null, "e": 27262, "s": 27093, "text": "Note: Both queueing delay and processing delay doesn’t have any formula because they depend on the speed of the processor This delay depends upon the following factors:" }, { "code": null, "e": 27304, "s": 27262, "text": "It depends on the speed of the processor." }, { "code": null, "e": 27388, "s": 27304, "text": "Ttotal = Tt + Tp + Tq + Tpro\n\nTtotal = Tt+Tp\n(when taking Tq and Tpro equals to 0) " }, { "code": null, "e": 27409, "s": 27390, "text": "shrishti_m180521ca" }, { "code": null, "e": 27420, "s": 27409, "text": "jeevanyasa" }, { "code": null, "e": 27438, "s": 27420, "text": "Computer Networks" }, { "code": null, "e": 27446, "s": 27438, "text": "GATE CS" }, { "code": null, "e": 27464, "s": 27446, "text": "Computer Networks" }, { "code": null, "e": 27562, "s": 27464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27571, "s": 27562, "text": "Comments" }, { "code": null, "e": 27584, "s": 27571, "text": "Old Comments" }, { "code": null, "e": 27619, "s": 27584, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27670, "s": 27619, "text": "Active and Passive attacks in Information Security" }, { "code": null, "e": 27697, "s": 27670, "text": "Cryptography and its Types" }, { "code": null, "e": 27743, "s": 27697, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 27776, "s": 27743, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27800, "s": 27776, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27827, "s": 27800, "text": "Types of Operating Systems" }, { "code": null, "e": 27876, "s": 27827, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27897, "s": 27876, "text": "Normal Forms in DBMS" } ]
Keras - Flatten Layers
Flatten is used to flatten the input. For example, if flatten is applied to layer having input shape as (batch_size, 2,2), then the output shape of the layer will be (batch_size, 4) Flatten has one argument as follows keras.layers.Flatten(data_format = None) data_format is an optional argument and it is used to preserve weight ordering when switching from one data format to another data format. It accepts either channels_last or channels_first as value. channels_last is the default one and it identifies the input shape as (batch_size, ..., channels) whereas channels_first identifies the input shape as (batch_size, channels, ...) A simple example to use Flatten layers is as follows − >>> from keras.models import Sequential >>> from keras.layers import Activation, Dense, Flatten >>> >>> >>> model = Sequential() >>> layer_1 = Dense(16, input_shape=(8,8)) >>> model.add(layer_1) >>> layer_2 = Flatten() >>> model.add(layer_2) >>> layer_2.input_shape (None, 8, 16) >>> layer_2.output_shape (None, 128) >>> where, the second layer input shape is (None, 8, 16) and it gets flattened into (None, 128). 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2233, "s": 2051, "text": "Flatten is used to flatten the input. For example, if flatten is applied to layer having input shape as (batch_size, 2,2), then the output shape of the layer will be (batch_size, 4)" }, { "code": null, "e": 2269, "s": 2233, "text": "Flatten has one argument as follows" }, { "code": null, "e": 2311, "s": 2269, "text": "keras.layers.Flatten(data_format = None)\n" }, { "code": null, "e": 2689, "s": 2311, "text": "data_format is an optional argument and it is used to preserve weight ordering when switching from one data format to another data format. It accepts either channels_last or channels_first as value. channels_last is the default one and it identifies the input shape as (batch_size, ..., channels) whereas channels_first identifies the input shape as (batch_size, channels, ...)" }, { "code": null, "e": 2744, "s": 2689, "text": "A simple example to use Flatten layers is as follows −" }, { "code": null, "e": 3076, "s": 2744, "text": ">>> from keras.models import Sequential \n>>> from keras.layers import Activation, Dense, Flatten \n>>> \n>>> \n>>> model = Sequential() \n>>> layer_1 = Dense(16, input_shape=(8,8)) \n>>> model.add(layer_1) \n>>> layer_2 = Flatten() \n>>> model.add(layer_2) \n>>> layer_2.input_shape (None, 8, 16) \n>>> layer_2.output_shape (None, 128) \n>>>" }, { "code": null, "e": 3169, "s": 3076, "text": "where, the second layer input shape is (None, 8, 16) and it gets flattened into (None, 128)." }, { "code": null, "e": 3203, "s": 3169, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 3220, "s": 3203, "text": " Abhilash Nelson" }, { "code": null, "e": 3253, "s": 3220, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 3275, "s": 3253, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3308, "s": 3275, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 3330, "s": 3308, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3363, "s": 3330, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 3385, "s": 3363, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3418, "s": 3385, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 3440, "s": 3418, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3473, "s": 3440, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 3484, "s": 3473, "text": " Mike West" }, { "code": null, "e": 3491, "s": 3484, "text": " Print" }, { "code": null, "e": 3502, "s": 3491, "text": " Add Notes" } ]
How to copy the text to the clipboard in JavaScript? - GeeksforGeeks
20 Mar, 2019 In order to copy the text to the clipboard in javascript we use document.execCommand() method . This can be done in two stepsStep1 : Write HTML code: <!-- The text field --><input type="text" value="GeeksForGeeks" id="GfGInput"> <!-- The button used to copy the text --><button onclick="GeeksForGeeks()">Copy text</button> Step2 : Write JavaScript code: function GeeksForGeeks() { /* Get the text field */ var copyGfGText = document.getElementById("GfGInput"); /* Select the text field */ copyGfGText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyGfGText.value);} Note : The document.execCommand() method is not supported in IE8 and earlier. Example 1: <!DOCTYPE html><html> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input type="text" value="GeeksForGeeks" id="GfGInput"> <button onclick="GeeksForGeeks()">Copy text</button> <script> function GeeksForGeeks() { var copyGfGText = document.getElementById("GfGInput"); copyGfGText.select(); document.execCommand("copy"); alert("Copied the text: " + copyGfGText.value); } </script> <p> Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect. </p> </body></html> Output :After clicking on element:Selected text is copied: Example 2: <!DOCTYPE html><html> <head> <style> h1 { border: 1px solid black; height: 90px; padding-top: 40px; background: green; color: white; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:white;" > GeeksForGeeks </h1> <input type="text" value="GeeksForGeeks" id="GfGInput"> <button onclick="GeeksForGeeks()">Copy text</button> <script> function GeeksForGeeks() { var copyGfGText = document.getElementById("GfGInput"); copyGfGText.select(); document.execCommand("copy"); alert("Copied the text: " + copyGfGText.value); } </script> <p>Click on the button to copy the text from the field. Try to paste the text (e.g. "ctrl+v")to see the effect. </p> </body></html> Output :After clicking on element:Selected text is copied: JavaScript-Misc Picked 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 How to create a link in JavaScript ? How to Show Images on Click using HTML ? How to remove an HTML element using JavaScript ? Remove elements from a JavaScript Array Express.js express.Router() Function 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24909, "s": 24881, "text": "\n20 Mar, 2019" }, { "code": null, "e": 25059, "s": 24909, "text": "In order to copy the text to the clipboard in javascript we use document.execCommand() method . This can be done in two stepsStep1 : Write HTML code:" }, { "code": "<!-- The text field --><input type=\"text\" value=\"GeeksForGeeks\" id=\"GfGInput\"> <!-- The button used to copy the text --><button onclick=\"GeeksForGeeks()\">Copy text</button> ", "e": 25234, "s": 25059, "text": null }, { "code": null, "e": 25265, "s": 25234, "text": "Step2 : Write JavaScript code:" }, { "code": "function GeeksForGeeks() { /* Get the text field */ var copyGfGText = document.getElementById(\"GfGInput\"); /* Select the text field */ copyGfGText.select(); /* Copy the text inside the text field */ document.execCommand(\"copy\"); /* Alert the copied text */ alert(\"Copied the text: \" + copyGfGText.value);} ", "e": 25586, "s": 25265, "text": null }, { "code": null, "e": 25664, "s": 25586, "text": "Note : The document.execCommand() method is not supported in IE8 and earlier." }, { "code": null, "e": 25675, "s": 25664, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input type=\"text\" value=\"GeeksForGeeks\" id=\"GfGInput\"> <button onclick=\"GeeksForGeeks()\">Copy text</button> <script> function GeeksForGeeks() { var copyGfGText = document.getElementById(\"GfGInput\"); copyGfGText.select(); document.execCommand(\"copy\"); alert(\"Copied the text: \" + copyGfGText.value); } </script> <p> Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect. </p> </body></html>", "e": 26462, "s": 25675, "text": null }, { "code": null, "e": 26521, "s": 26462, "text": "Output :After clicking on element:Selected text is copied:" }, { "code": null, "e": 26532, "s": 26521, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { border: 1px solid black; height: 90px; padding-top: 40px; background: green; color: white; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:white;\" > GeeksForGeeks </h1> <input type=\"text\" value=\"GeeksForGeeks\" id=\"GfGInput\"> <button onclick=\"GeeksForGeeks()\">Copy text</button> <script> function GeeksForGeeks() { var copyGfGText = document.getElementById(\"GfGInput\"); copyGfGText.select(); document.execCommand(\"copy\"); alert(\"Copied the text: \" + copyGfGText.value); } </script> <p>Click on the button to copy the text from the field. Try to paste the text (e.g. \"ctrl+v\")to see the effect. </p> </body></html>", "e": 27482, "s": 26532, "text": null }, { "code": null, "e": 27541, "s": 27482, "text": "Output :After clicking on element:Selected text is copied:" }, { "code": null, "e": 27557, "s": 27541, "text": "JavaScript-Misc" }, { "code": null, "e": 27564, "s": 27557, "text": "Picked" }, { "code": null, "e": 27575, "s": 27564, "text": "JavaScript" }, { "code": null, "e": 27592, "s": 27575, "text": "Web Technologies" }, { "code": null, "e": 27690, "s": 27592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27699, "s": 27690, "text": "Comments" }, { "code": null, "e": 27712, "s": 27699, "text": "Old Comments" }, { "code": null, "e": 27773, "s": 27712, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27810, "s": 27773, "text": "How to create a link in JavaScript ?" }, { "code": null, "e": 27851, "s": 27810, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 27900, "s": 27851, "text": "How to remove an HTML element using JavaScript ?" }, { "code": null, "e": 27940, "s": 27900, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27977, "s": 27940, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28010, "s": 27977, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28072, "s": 28010, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28115, "s": 28072, "text": "How to fetch data from an API in ReactJS ?" } ]
Convert string to objectid in MongoDB?
To convert string to objectid in MongoDB, use $toObjectId. Let us create a collection with documents − > db.demo95.insertOne({"Id":"5ab9cbe531c2ab715d42129a"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2d5ef5b8903cdd865577ac") } Display all documents from a collection with the help of find() method − > db.demo95.find(); This will produce the following output − { "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a" } Following is the query to convert string to objectid in MongoDB − > db.demo95.aggregate([ { "$addFields": { "d" : { "$toObjectId": "$Id" } }} ]) This will produce the following output − { "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a", "d" : ObjectId("5ab9cbe531c2ab715d42129a") }
[ { "code": null, "e": 1165, "s": 1062, "text": "To convert string to objectid in MongoDB, use $toObjectId. Let us create a collection with documents −" }, { "code": null, "e": 1308, "s": 1165, "text": "> db.demo95.insertOne({\"Id\":\"5ab9cbe531c2ab715d42129a\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d5ef5b8903cdd865577ac\")\n}" }, { "code": null, "e": 1381, "s": 1308, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1401, "s": 1381, "text": "> db.demo95.find();" }, { "code": null, "e": 1442, "s": 1401, "text": "This will produce the following output −" }, { "code": null, "e": 1526, "s": 1442, "text": "{ \"_id\" : ObjectId(\"5e2d5ef5b8903cdd865577ac\"), \"Id\" : \"5ab9cbe531c2ab715d42129a\" }" }, { "code": null, "e": 1592, "s": 1526, "text": "Following is the query to convert string to objectid in MongoDB −" }, { "code": null, "e": 1671, "s": 1592, "text": "> db.demo95.aggregate([ { \"$addFields\": { \"d\" : { \"$toObjectId\": \"$Id\" } }} ])" }, { "code": null, "e": 1712, "s": 1671, "text": "This will produce the following output −" }, { "code": null, "e": 1840, "s": 1712, "text": "{ \"_id\" : ObjectId(\"5e2d5ef5b8903cdd865577ac\"), \"Id\" : \"5ab9cbe531c2ab715d42129a\", \"d\" : ObjectId(\"5ab9cbe531c2ab715d42129a\") }" } ]