code-rag-bench/online-tutorials huggingface dataset:
Iterator Invalidation in C++ - GeeksforGeeks

23 Dec, 2021
When the container to which an Iterator points changes shape internally, i.e. when elements are moved from one position to another, and the initial iterator still points to the old invalid location, then it is called Iterator invalidation. One should be careful while using iterators in C++. When we iterate over our container using iterators then it may happen that the iterator gets invalidated. This may be due to change in the shape and size of the container while iterating. 
For example, Iterator invalidation in a vector whenever either, at any point in the vector, an element is inserted or an element from the vector is removed. Let us take an example to understand this,
CPP
// CPP program to demonstrate iterator// invalidations#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){     // Creating a sample vector    vector<int> v = { 1, 5, 10, 15, 20 };     // Changing vector while iterating over it    // (This causes iterator invalidation)    for (auto it = v.begin(); it != v.end(); it++)        if ((*it) == 5)            v.push_back(-1);     for (auto it = v.begin(); it != v.end(); it++)        cout << (*it) << " ";     return 0;}
1 5 10 15 20 -1 -1 
In the above example code, it may happen that when we add an element -1 while iterating the vector, the size of the vector can get more than the maximum size due to which a new memory is allocated to the vector and all elements are copied there. But, our iterator still points to the previous old memory address. So, now we can say that iterator gets invalidated. This is one example of invalidation. Given below are some rules for iterator invalidation.
1. Insertion
2. Erasure 
3. Resizing 
Note: Invalidation of iterator does not always mean that dereferencing such an iterator causes a program to crash. It also includes the possibility that iterator does not point to an element which it is supposed to point.
This article is contributed by Ashish Sharma. 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. 
abhirishi0805
anshikajain26
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Python | Initializing multiple lists - GeeksforGeeks

30 Dec, 2018
In real applications, we often have to work with multiple lists and to initialize them with empty lists hampers the readability of code. Hence a one-liner is required to perform this task in short so as to give a clear idea of type and number of lists declared to be used.
Method #1 : Using * operatorWe can enlist all the required list comma separated and then initialize them with an empty list and multiply that empty list using the * operator by the number of lists specified.
# Python3 code to demonstrate # to initialize multiple lists# using * operator  # using * operator# to initialize multiple listslist1, list2, list3, list4 = ([], ) * 4  # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(list1))print ("List 2 : " + str(list2))print ("List 3 : " + str(list3))print ("List 4 : " + str(list4))
The initialized lists are : 
List 1 : []
List 2 : []
List 3 : []
List 4 : []

 Method #2 : Using loopThis method is similar to the method explained above but the only difference is that we use loop instead of * operator to perform the task of multiple assignments.
# Python3 code to demonstrate # to initialize multiple lists# using loop  # using loop# to initialize multiple listslist1, list2, list3, list4 = ([] for i in range(4))  # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(list1))print ("List 2 : " + str(list2))print ("List 3 : " + str(list3))print ("List 4 : " + str(list4))
The initialized lists are : 
List 1 : []
List 2 : []
List 3 : []
List 4 : []

 Method #3 : Using defaultdict()This is a method different and also performs a slightly different utility than the above two methods discussed. This creates a dictionary with a specific name and we have option to make any number of keys and perform the append operations straight away as they get initialized by the list.
# Python3 code to demonstrate # to initialize multiple lists# using defaultdict()import collections  # using defaultdict()# to initialize multiple lists# no need to initialize with empty listsmul_list_dict = collections.defaultdict(list)mul_list_dict['list1'].append(1)mul_list_dict['list2'].append(2)mul_list_dict['list3'].append(3)mul_list_dict['list4'].append(4)  # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(mul_list_dict['list1']))print ("List 2 : " + str(mul_list_dict['list2']))print ("List 3 : " + str(mul_list_dict['list3']))print ("List 4 : " + str(mul_list_dict['list4']))
The initialized lists are : 
List 1 : [1]
List 2 : [2]
List 3 : [3]
List 4 : [4]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
scipy stats.normaltest() function | Python - GeeksforGeeks

11 Feb, 2019
scipy.stats.normaltest(array, axis=0) function test whether the sample is different from the normal distribution. This function tests the null hypothesis of the population that the sample was drawn from.
Parameters :array : Input array or object having the elements.axis : Axis along which the normal distribution test is to be computed. By default axis = 0.
Returns : k2 value and P-value for the hypothesis test on data set.
Code #1:
# Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p   x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2  )  p.plot(x1, y1, '.')  print( '\nNormal test for given data :\n', normaltest(y1))
Output :


Normal test for given data :
 NormaltestResult(statistic=146.08066794511544, pvalue=1.901016994532079e-32)

 Code #2:
# Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p   x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2  )  p.plot(x1, y1, '.')  print( '\nNormal test for given data :\n', normaltest(y1))
Output :


Normal test for given data :
 NormaltestResult(statistic=344.05533061429884, pvalue=1.9468577593501764e-75)

Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.7

HTML Input types
Tryit: HTML reset button
How to initialize a tuple to an empty tuple in C#?

To initialize a tuple to an empty tuple −
Tuple<string, string> myTuple;
If you want to check for values in a tuple, that whether it is null or not −
using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Tuple <int, string> tuple = new Tuple<int, string>(10, null);

         if (tuple.Item1 == 10) {
            Console.WriteLine(tuple.Item1);
         }

         if (tuple.Item2 == null) {
            Console.WriteLine("Item is null");
         }
      }
   }
}
How to read inputs as strings in C#?

To read inputs as strings in C#, use the Console.ReadLine() method.
str = Console.ReadLine();
The above will read input as string. You don’t need to use the Convert method here since the input takes string by default.
Now display the string entered by user −
 Live Demo
using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string myStr;

      // use ReadLine() to read the entered line
      myStr = Console.ReadLine();

      // display the line
      Console.WriteLine("Result = {0}", myStr);
   }
}
Result =
The following is the output. Let’s say the user entered “Amit” as the input −
Result = amit
How to clear complete cache data in ReactJS ? - GeeksforGeeks

26 Apr, 2021
We can use the following approach in ReactJS to clear complete cache data. We can clear complete cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.
Approach: Follow these simple steps in order to clear complete cache data in ReactJS. We have created our clearCacheData function which clears the entire cache data from the browser. When we click on the button, the function is triggered, and the entire caches get deleted from the browser and, and we see an alert popup. 
In the following example, we have 5 caches stored in the browser named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below, and we clear the complete cache using our defined function.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import * as React from 'react';  export default function App() {    // Function to clear complete cache data  const clearCacheData = () => {    caches.keys().then((names) => {      names.forEach((name) => {        caches.delete(name);      });    });    alert('Complete Cache Cleared')  };    return (    <div style={{ height: 500, width: '80%' }}>      <h4>How to clear complete cache data in ReactJS?</h4>      <button onClick={() => clearCacheData()} >        Clear Cache Data</button>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to redirect to another page in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS setState()
Re-rendering Components in ReactJS
ReactJS defaultProps
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Angular7 - Overview

Angular 7 is owned by Google and the stable release was done on 18th October 2018. This is the latest version of Angular.
Below is the list of Angular versions released so far −
The release dates for the next two major upcoming versions of Angular are given below −
Google plans to release the major Angular version every 6 months. The version released so far are backward compatible and can be updated to the newer one very easily.
Let us discuss the new features added to Angular 7.
Angular 7 is a major release where in the angular core framework, Angular CLI, Angular Materials are updated. In case you are using Angular 5 or 6 and want to update to Angular 7, below is the command which will update your app to the recent version of Angular −
ng update @angular/cli @angular/core

While doing project setup using angular CLI, it prompts you about the built-in features available, i.e., routing and stylesheet support as shown below −
In Angular 7, there is bundle budget added in angular.json as shown below −
Budgets is a feature added to Angular CLI which allows you to set limit inside your configuration to make sure your application size is within the limit set. You can set the size so that the app can be warned when the limit is crossed.
The version of Angular Material/CDK is updated in Angular 7. Also there are 2 features added to CDK − virtual scrolling, and drag and drop.
Virtual scrolling feature shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen.
You can drag and drop elements from a list and place it wherever required within the list. The new feature is very smooth and fast.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
time.Date() Function in Golang With Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Date() function in Go language is used to find Date the Time which is equivalent to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the proper time zone in the stated location. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Here, “loc” is pointed to the location.
Return Value: It returns a time that is proper in one of the two associated zones in the conversion, but it won’t guarantee that which one is returned. And it returns panics if the given “loc” is nil.
Note: Here, the value of the month, day hour, min, sec and nsec can be more than the normal ranges but they will be automatically normalized during the conversion. For example, if the date is April 34 then it is converted to May 1.
Example 1:
// Golang program to illustrate the usage of// time.Date() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Date() method     // with all its parameters    tm := time.Date(2020, time.April,        11, 21, 34, 01, 0, time.UTC)      // Using Local() for location and printing    // the stated time and date in UTC    fmt.Printf("%s", tm.Local())}
Output:
2020-04-11 21:34:01 +0000 UTC

Example 2:
// Golang program to illustrate the usage of// time.Date() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling Date() method     // with all its parameters    tm := time.Date(2020, time.April,           34, 25, 72, 01, 0, time.UTC)      // Using Local() for location and printing    // the stated time and date in UTC    fmt.Printf("%s", tm.Local())}
Output:
2020-05-05 02:12:01 +0000 UTC

Here, the range of the values of day, hours, and minutes is outside the normal range but they are normalized during the conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
6 Best Books to Learn Go Programming Language
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
Python String join() Method - GeeksforGeeks

19 Apr, 2022
Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.
Syntax: 
string_name.join(iterable) 
Parameters: 
The join() method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set
Return Value: 
The join() method returns a string concatenated with the elements of iterable. 
Type Error:
If the iterable contains any non-string values, it raises a TypeError exception. 
Python
# Python program to demonstrate the# use of join function to join list# elements with a character. list1 = ['1','2','3','4'] s = "-" # joins elements of list1 by '-'# and stores in string ss = s.join(list1) # join use to join a list of# strings to a separator sprint(s)
Output: 
1-2-3-4
Python
# Python program to demonstrate the# use of join function to join list# elements without any separator. # Joining with empty separatorlist1 = ['g','e','e','k', 's']print("".join(list1))
Output: 
geeks
AmiyaRanjanRout
h6zqteft28todkgwkmlupd6nthpstwt8345j3o6o
Python-Functions
python-list
python-string
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to create new Collection in MongoDB using Node.js ? - GeeksforGeeks

01 Dec, 2020
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON format). Refer (this) article.
MongoDB Module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDb database which is running on a particular server on your machine. (Refer to this article). We can also use promises in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection.
Installing module:
node install mongodb
Project structure:
Running the server on Local IP:
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB Database:
Database:GFG
Index.js:
Javascript
const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG"; // Database name   MongoClient.connect(url).then((client) => {      const connect = client.db(databasename);      // New Collection    const collection = connect        .createCollection("GFGCollection");      console.log("collection created");}).catch((err) => {      // Handling the error     console.log(err.Message);})
Output:
MongoDB database:
Node.js-Misc
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
Matplotlib.figure.Figure.autofmt_xdate() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The autofmt_xdate() method figure module of matplotlib library is used to rotate them and right align them.
Syntax: autofmt_xdate(self, bottom=0.2, rotation=30, ha=’right’, which=None)
Parameters: This accept the following parameters that are described below:
bottom : This parameter is the bottom of the subplots for subplots_adjust().
rotation : This parameter is the rotation of the xtick labels.
ha : This parameter is the horizontal alignment of the xticklabels.
which : This parameter selects which ticklabels to rotate.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.autofmt_xdate() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook    years = mdates.YearLocator()   months = mdates.MonthLocator()  years_fmt = mdates.DateFormatter('% Y')    with cbook.get_sample_data('goog.npz') as datafile:    data = np.load(datafile)['price_data'].view(np.recarray)        fig, ax = plt.subplots()ax.plot('date', 'adj_close',          data = data[:300],         color ="green")    ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True)   fig.autofmt_xdate()   fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np    date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta)    y = np.arange(len(dates))    fig, ax = plt.subplots()ax.plot_date(dates, y ** 2, 'g')    ax.set_xlim(dates[0], dates[-1])    ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d'))    ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate()   fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Lex program to implement a simple Calculator - GeeksforGeeks

30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the LEX program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out 
Let’s see LEX program to implement a simple calculator.
Examples:
Input : 
3+3
Output :
6.0

Input : 
5*4
Output : 
20.0 
Below is the implementation:
/*lex program to implement          - a simple calculator.*/  % {  int op = 0,i;  float a, b;% }  dig [0-9]+|([0-9]*)"."([0-9]+)add "+"sub "-"mul "*"div "/"pow "^"ln \n%%  /* digi() is a user defined function */{dig} {digi();} {add} {op=1;}{sub} {op=2;}{mul} {op=3;}{div} {op=4;}{pow} {op=5;}{ln} {printf("\n The Answer :%f\n\n",a);}  %%digi(){ if(op==0)  /* atof() is used to convert       - the ASCII input to float */ a=atof(yytext);    else { b=atof(yytext);   switch(op) {   case 1:a=a+b;    break;     case 2:a=a-b;   break;      case 3:a=a*b;   break;      case 4:a=a/b;   break;      case 5:for(i=a;b>1;b--)   a=a*i;   break;  } op=0; }}  main(int argv,char *argc[]){ yylex();}  yywrap() {  return 1; }
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Phases of a Compiler
Three address code in Compiler
Symbol Table in Compiler
Code Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
How to use time input type in HTML?

The time input type is used in HTML using the <input type="time">. Using this, allow the users to select time. A time picker popup is visible whenever input field is clicked.
Note: The input type time is not supported in Firefox and Internet Explorer. It works on Google Chrome.
You can try to run the following code to learn how to use time input type in HTML.
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input time</title>
   </head>
   <body>
      <form action = "" method = "get">
         Details:<br><br>
         Student Name<br><input type="name" name="sname"><br>
         Exam Time<br><input type="time" name="etime"><br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
C# - Do...While Loop

Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
The syntax of a do...while loop in C# is −
do {
   statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
         
         /* do loop execution */
         do {
            Console.WriteLine("value of a: {0}", a);
            a = a + 1;
         } 
         while (a < 20);
         Console.ReadLine();
      }
   }
} 
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Split one-dimensional array into two-dimensional array JavaScript

We are required to write a function that takes in a one-dimensional array as the first argument
and a number n as the second argument and we have to make n subarrays inside of the parent
array (**if possible) and divide elements into them accordingly.
** if the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements
in each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to
fallback to nearest lowest level (3 in this case) because our requirement is to distribute equal
number of elements in each subarray except the last one in some special cases.
For example −
// if the input array is:
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
// and the number is 2
//then the output should be:
const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];
Let’s write the code for this function −
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
const splitArray = (arr, rows) => {
   const itemsPerRow = Math.ceil(arr.length / rows);
   return arr.reduce((acc, val, ind) => {
      const currentRow = Math.floor(ind / itemsPerRow);
      if(!acc[currentRow]){
         acc[currentRow] = [val];
      }else{
         acc[currentRow].push(val);
      };
      return acc;
   }, []);
};
console.log(splitArray(arr, 2));
The output in the console will be −
[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]
How do you check scroll position using selenium?

We can check scroll position using Selenium. To check the position we shall use the Javascript executor. We have to verify the value of the window.pageYOffset in the browser.
While the URL is launched, the scroll is at the top the value of window.pageYOffset is 0. As we scroll to an element, the value of the window.pageYOffset shall be greater than 0.
JavascriptExecutor j = (JavascriptExecutor) driver;
Long v = (Long) j.executeScript("return window.pageYOffset;");
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollPosition{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // get current scroll position with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      Long v = (Long) j.executeScript("return window.pageYOffset;");
      System.out.println("Scroll position after launch: " + v);
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Careers']"));
      // Javascript executor to scroll to the element
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", n);
      Thread.sleep(200);
      // get current scroll position with Javascript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      double d = (double) js.executeScript("return window.pageYOffset;");
      System.out.println("Scroll position after scrolling upto an element: "+d);
      driver.close();
   }
}
Find the minimum positive integer such that it is divisible by A and sum of its digits is equal to B in Python

Suppose we have two numbers A and B, we have to find the minimum positive number M so that M is divisible by A and the sum of the digits of M is same as B. So, if there is no such result, then return -1.
So, if the input is like A = 50, B = 2, then the output will be 200 as this is divisible by 50 and sum of its digit = 2 + 0 + 0 = 2.
To solve this, we will follow these steps −
Define one element type container, that contains two numbers a and b and one string
Define one element type container, that contains two numbers a and b and one string
que := a new list
que := a new list
elem := a new element with (0, 0, blank string)
elem := a new element with (0, 0, blank string)
visited[0, 0] := 1
visited[0, 0] := 1
insert elem at the end of que
insert elem at the end of que
while size of que > 0, dotemp_elem := delete first element from queif temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.stringfor i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into
que
while size of que > 0, do
temp_elem := delete first element from que
temp_elem := delete first element from que
if temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.string
if temp_elem.a is 0 and temp_elem.b is b, then
return integer of temp_elem.string
return integer of temp_elem.string
for i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into
que
for i in range 0 to 9, do
x :=(temp_elem.a * 10 + i) mod a
x :=(temp_elem.a * 10 + i) mod a
y := temp_elem.b + i
y := temp_elem.b + i
if y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into
que
if y <= b and visited[x, y] is False, then
visited[x, y] := 1
visited[x, y] := 1
insert new element with x, y and temp_elem.string concatenate i into
que
insert new element with x, y and temp_elem.string concatenate i into
que
return -1
return -1
Let us see the following implementation to get better understanding −
 Live Demo
visited = [[0 for x in range(501)] for y in range(5001)]
class Element:
   def __init__(self, a, b, string):
      self.a = a
      self.b = b
      self.string = string
def get_number(a, b):
   que = []
   elem = Element(0, 0, "")
   visited[0][0] = 1
   que.append(elem)
   while len(que) > 0:
      temp_elem = que.pop(0)
      if temp_elem.a == 0 and temp_elem.b == b:
         return int(temp_elem.string)
      for i in range(0, 10):
         x = (temp_elem.a * 10 + i) % a
         y = temp_elem.b + i
         if y <= b and visited[x][y] == False:
            visited[x][y] = 1
            que.append(Element(x, y, temp_elem.string + str(i)))
   return -1

a, b = 50, 2
print(get_number(a, b))
50, 2
200
PyQt - QMessageBox

QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number.
Important methods and enumerations associated with QMessageBox class are given in the following table −
setIcon()
Displays predefined icon corresponding to severity of the message
 Question
 Information
 Warning
 Critical
setText()
Sets the text of the main message to be displayed
setInformativeText()
Displays additional information
setDetailText()
Dialog shows a Details button. This text appears on clicking it
setTitle()
Displays the custom title of dialog
setStandardButtons()
List of standard buttons to be displayed. Each button is associated with
QMessageBox.Ok 0x00000400
QMessageBox.Open 0x00002000
QMessageBox.Save 0x00000800
QMessageBox.Cancel 0x00400000
QMessageBox.Close 0x00200000
QMessageBox.Yes 0x00004000
QMessageBox.No 0x00010000
QMessageBox.Abort 0x00040000
QMessageBox.Retry 0x00080000
QMessageBox.Ignore 0x00100000
setDefaultButton()
Sets the button as default. It emits the clicked signal if Enter is pressed
setEscapeButton()
Sets the button to be treated as clicked if the escape key is pressed
In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog.
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

setStandardButton() function displays desired buttons.
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal.
msg.buttonClicked.connect(msgbtn)

The complete code for the example is as follows −
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Show message!")

   b.move(50,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt Dialog demo")
   w.show()
   sys.exit(app.exec_())
	
def showdialog():
   msg = QMessageBox()
   msg.setIcon(QMessageBox.Information)

   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
   msg.buttonClicked.connect(msgbtn)
	
   retval = msg.exec_()
   print "value of pressed message box button:", retval
	
def msgbtn(i):
   print "Button pressed is:",i.text()
	
if __name__ == '__main__': 
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Aurelia - Component Lifecycle

Aurelia uses component lifecycle methods to manipulate the component lifecycle. In this chapter, we will show you those methods and explain the component lifecycle.
constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used.
constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used.
created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView).
created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView).
bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties.
bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties.
attached() − Attached method is invoked once the component is attached to the DOM.
attached() − Attached method is invoked once the component is attached to the DOM.
detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM.
detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM.
unbind() − The last lifecycle method is unbind. It is called when the component is unbound.
unbind() − The last lifecycle method is unbind. It is called when the component is unbound.
The lifecycle methods are useful when you want to have higher control over your component. You can use them when you need to trigger some functionalities at certain point of component lifecycle.
All lifecycle methods are shown below.
export class App {
   constructor(argument) {
      // Create and initialize your class object here...
   }

   created(owningView, myView) {
      // Invoked once the component is created...
   }

   bind(bindingContext, overrideContext) {
      // Invoked once the databinding is activated...
   }

   attached(argument) {
      // Invoked once the component is attached to the DOM...
   }

   detached(argument) {
      // Invoked when component is detached from the dom
   }

   unbind(argument) {
      // Invoked when component is unbound...
   }
}
 Print
 Add Notes
 Bookmark this page
How to use Python object in C++?

Here is an example in which a simple Python object is wrapped and embedded. We are using  .c for this, c++ has similar steps −
class PyClass(object):
    def __init__(self):
        self.data = []
    def add(self, val):
        self.data.append(val)
    def __str__(self):
        return "Data: " + str(self.data)
cdef public object createPyClass():
    return PyClass()
cdef public void addData(object p, int val):
    p.add(val)
cdef public char* printCls(object p):
    return bytes(str(p), encoding = 'utf-8')
We compile with cython pycls.pyx (use --cplus for c++) to generate a .c and .h file containing the source and the function declarations respectively. We now create a main.c file that starts up Python and we are ready to call these functions −
#include "Python.h"   // Python.h always gets included first.
#include "pycls.h"    // Include your header file.
int main(int argc, char *argv[]){
    Py_Initialize();   // initialize Python
    PyInit_pycls();    // initialize module (initpycls(); in Py2)
    PyObject *obj = createPyClass();
    for(int i=0; i<10; i++){
        addData(obj, i);
    }
    printf("%s\n", printCls(obj));
    Py_Finalize();
    return 0;
}
Compiling this with the proper flags (which you can obtain from python3.5-config of python-config [Py2]) −
gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99
will create our executable which interacts with our object −
./a.out
Data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
All this was done by using Cython along with the public keyword that generates the .h header file. We could alternatively just compile a python module with Cython and create the header/handle the additional boilerplate ourself.
How to find the number of times array is rotated in the sorted array by recursion using C#?

Find index of mid element (minimum element) Apply Binary Search on the subarray based on following conditions −
If number lies between start element and element at mid1 position.
If number lies between start element and element at mid1 position.
Then find number in array start to mid-1 using binary search
Then find number in array start to mid-1 using binary search
Else if number lies between mid and last element, then find number in array mid to last element using binary search.
Else if number lies between mid and last element, then find number in array mid to last element using binary search.
 Live Demo
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class Arrays{
      public int FindNumberRotated(int[] array, int start, int end, int value){
         if (start > end){
            return -1;
         }
         int mid = (start + end) / 2;
         if (array[mid] == value){
            return mid;
         }
         if (array[start] <= array[mid]){
            if (value >= array[start] && value <= array[mid]){
               return FindNumberRotated(array, start, mid - 1, value);
            }
            return FindNumberRotated(array, mid + 1, end, value);
         }
         if (value >= array[mid] && value <= array[end]){
            return FindNumberRotated(array, mid + 1, end, value);
         }
         return FindNumberRotated(array, start, mid - 1, value);
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 };
         int res = a.FindNumberRotated(arr, 0, arr.Length - 1, 1);
         Console.WriteLine(res);
      }
   }
}
8
CSS - text-transform

The  text-transform property changes the capitalization of text within an element, or else directs the user agent to leave the capitalization "as is."
capitalize − The first letter of each word in the element's text should be capitalized.
capitalize − The first letter of each word in the element's text should be capitalized.
uppercase − All of the characters in the element's text should be uppercase (capital letters).
uppercase − All of the characters in the element's text should be uppercase (capital letters).
lowercase − All of the characters in the element's text should be lowercase.
lowercase − All of the characters in the element's text should be lowercase.
none - The capitalization of the element's text should not be altered.
none - The capitalization of the element's text should not be altered.
All the HTML elements.
object.style.textTransform = "uppercase";

Following is the example which demonstrates how to set the cases for a text using text-transform property.
<html>
   <head>
   </head>

   <body>
      <p style = "text-transform:capitalize;">
         This will be capitalized
      </p>
      
      <p style = "text-transform:uppercase;">
         This will be in uppercase
      </p>
      
      <p style = "text-transform:lowercase;">
         This will be in lowercase
      </p>
   </body>
</html> 
This will produce following result −

   This will be capitalized


   This will be in uppercase


   This will be in lowercase


    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Creating a linked list using Javascript

Let's start by defining a simple class with a constructor that initializes the head to null. We'll also define another structure on the prototype of the LinkedList class that'll represent each node in the linked list.
class LinkedList {
   constructor() {
      this.head = null;
      this.length = 0;
    }
}
LinkedList.prototype.Node = class {
   constructor(data) {
      this.data = data; this.next = null;
   }
}
Let's also create a display function that'll help us see how our list looks like. This function works as follows.
It starts from the head.
It iterates over the list using currElem = currElem.next till currElem doesn't become null, ie, we've not reached the end.
It prints data for each of the iterations.
Here is an illustration for the same −
Now let's have a look at how we'll implement this −
display() {
   let currNode = this.head;
   while (currNode != null) {
      console.log(currNode.data + " -> ");
      currNode = currNode.next;
   }
}
Java Examples - Edit Table

How to edit(Add or update) columns of a Table and how to delete a table?
Following example uses create, alter & drop SQL commands to create, edit or delete table.
import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception { 
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection(
         "jdbc:derby://localhost:1527/testDb","username", "password");
      
      Statement stmt = con.createStatement();
      String query ="CREATE TABLE employees(id INTEGER PRIMARY KEY, first_name CHAR(50), last_name CHAR(75))";
      
      stmt.execute(query);
      System.out.println("Employee table created");
      String query1 = "aLTER TABLE employees ADD address CHAR(100) ";
      String query2 = "ALTER TABLE employees DROP COLUMN last_name";
      
      stmt.execute(query1);
      stmt.execute(query2);
      System.out.println("Address column added to the table & last_name column removed from the table");
      
      String query3 = "drop table employees";
      stmt.execute(query3);
      System.out.println("Employees table removed");
   }	
}
The above code sample will produce the following result. The result may vary.
Employee table created
Address column added to the table & last_name 
column removed from the table
Employees table removed from the database

 Print
 Add Notes
 Bookmark this page
Redis - String Setnx Command

Redis SETNX command is used to set some string value in Redis key, if the key does not exist in Redis. Fullform of SETNX is SET if Not eXists.
Integer reply 1 or 0
1, if the key is set.
0, if the key is not set.
Following is the basic syntax of Redis SETNX command.
redis 127.0.0.1:6379> SETNX KEY_NAME VALUE

redis 127.0.0.1:6379> SETNX mykey redis 
(integer) 1 
redis 127.0.0.1:6379> SETNX mykey mongodb 
(integer) 0 
redis 127.0.0.1:6379> GET mykey 
"redis"


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page