code-rag-bench/online-tutorials huggingface dataset:
Java | Class and Object | Question 4

28 Jun, 2021
Predict the output of following Java program.
class demoClass{    int a = 1;      void func()    {        demo obj = new demo();        obj.display();    }        class demo    {        int b = 2;          void display()        {            System.out.println("\na = " + a);        }    }      void get()    {        System.out.println("\nb = " + b);    }}    class Test{    public static void main(String[] args)    {        demoClass obj = new demoClass();        obj.func();        obj.get();      }}
(A)
a = 1
b = 2
(B) Compilation error
(C)
b = 2
a = 1
Answer: (B)Explanation:Members of inner class ‘demo’ can not be used in the outer class ‘Test’. Thus, get() of outer class can not access variable ‘b’ of inner class.Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Functions | Question 1
Java | Exception Handling | Question 3
Java | Exception Handling | Question 8
Java | Exception Handling | Question 4
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 7
Java | Exception Handling | Question 6
Java | Exception Handling | Question 8
Java | Java Packages | Question 3
Java | Operators | Question 9
Python program to print Calendar without calendar or datetime module

10 Jul, 2020
Given the month and year. The task is to show the calendar of that month and in the given year without using any module or pre-defined functions.
Examples:
Input : 
mm(1-12) :9
yy :2010

Output :    
September 2010
Su Mo Tu We Th Fr Sa
         01 02 03 04 
05 06 07 08 09 10 11 
12 13 14 15 16 17 18 
19 20 21 22 23 24 25 
26 27 28 29 30 

Approach:
In the program below, we first calculate the number of odd days to find the day of the date 01-mm-yyyy.Then, we take in the year(yy) and the month(mm) as input and displays the calendar for that month of the year.
Below is the implementation of the given approach.
# Python code to print Calendar# Without use of Calendar module   mm = 2yy = 2020  month ={1:'January', 2:'February', 3:'March',         4:'April', 5:'May', 6:'June', 7:'July',        8:'August', 9:'September', 10:'October',        11:'November', 12:'December'}   # code below for calculation of odd daysday =(yy-1)% 400day = (day//100)*5 + ((day % 100) - (day % 100)//4) + ((day % 100)//4)*2day = day % 7  nly =[31, 28, 31, 30, 31, 30,       31, 31, 30, 31, 30, 31]ly =[31, 29, 31, 30, 31, 30,      31, 31, 30, 31, 30, 31]s = 0  if yy % 4 == 0:    for i in range(mm-1):        s+= ly[i]else:    for i in range(mm-1):        s+= nly[i]  day += s % 7day = day % 7   # variable used for white space filling # where date not presentspace =''space = space.rjust(2, ' ')  # code below is to print the calendarprint(month[mm], yy)print('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa')  if mm == 9 or mm == 4 or mm == 6 or mm == 11:     for i in range(31 + day):                  if i<= day:            print(space, end =' ')        else:            print("{:02d}".format(i-day), end =' ')            if (i + 1)% 7 == 0:                print()elif mm == 2:    if yy % 4 == 0:        p = 30    else:        p = 29              for i in range(p + day):        if i<= day:            print(space, end =' ')        else:            print("{:02d}".format(i-day), end =' ')            if (i + 1)% 7 == 0:                print() else:    for i in range(32 + day):                  if i<= day:            print(space, end =' ')        else:            print("{:02d}".format(i-day), end =' ')            if (i + 1)% 7 == 0:                print()
Output:
February 2020
Su Mo Tu We Th Fr Sa
                  01 
02 03 04 05 06 07 08 
09 10 11 12 13 14 15 
16 17 18 19 20 21 22 
23 24 25 26 27 28 29

Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
GATE CS 2008 - GeeksforGeeks

02 Dec, 2021
If P, Q, R are subsets of the universal set U, then 
   
U 
Pc U Qc U Rc 
P U Qc U Rc 
Qc U Rc 
The following system of equations  
has a unique solution. The only possible value(s) for α is/are 
any real number  
one of 0, 1 or -1  
either 0 or 1 
0 
any real number other than 5 
The choice E was not there in GATE paper. We have added it as the given 4 choices don't seem correct.  
Augment the given matrix as

1 1 2 | 1
1 2 3 | 2
1 4 a | 4

Apply R2 <- R2 - R1 and R3 <- R3 - R1

1 1 2 | 1
0 1 1 | 1
0 3 a-2 | 3

Apply R3 <- R3 - 3R2

1 1 2 | 1
0 1 1 | 1
0 0 a-5 | 0

So for the system of equations to have a unique solution,

a - 5 != 0
or

a != 5
or
a = R - {5} 



A)   


B) 

C) 

D)  
A) m(4, 6)

B) m(4, 8)

C) m(6, 8)

D) m(4, 6, 8)
m(6,8)+m(1,6,15)
m(1,6,8,15)an
I. Whether the intersection of two regular languages is infinite
II. Whether a given context-free language is regular
III. Whether two push-down automata accept the same language
IV. Whether a given grammar is context-free

For Ex :

Grammar is :

S-> aAcBe

A->Ab|b

B->d

Input string : abbcde

Derivation : ( Top-Down, Right Most Derivation)

S->aAcBe
->aAcde
->aAbcde
->abbcde 

: abbcde

->aAbcde ( using A-> b )

->aAcde ( using A-> Ab )

->aAcBe ( using B -> d )

->S ( using S-> aAcBe ) 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Spring Boot - Annotations
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Download Image From URL in Android
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
How to write comments in ReactJS ?

19 Sep, 2021
ReactJS is a JavaScript library used for building user interfaces. It is Declarative, Component-based and Technology stack agnostic. It has been designed for speed, simplicity, and scalability. These features make it one of the most popular libraries among web developers.
In this article, we will explore creating a React application and adding comments to it.
Step 1: Create a React application with the following command:
npx create-react-app my-app
Step 2: Move to the project folder my-app with the following command:
cd my-app
 
Step 3: Start the development server with the following command:
yarn start
(This will run your application at localhost:3000, where you can see all the changes you make to the application.)
Project Structure: It will look like the following.
Example 1: Comments for React Components. We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript.
App.js
import React, { Component } from 'react';  // This is a comment  class App extends Component {      /* This is     also a comment*/    render() {        return (            <div>                <h1>Welcome to GeeksforGeeks</h1>            </div>        );    }}  export default App;
Output: 
 
Example 2: The above example does not work when we want to comment things inside the render block. This is because we use JSX inside the render block and must use multi-line comment in curly braces {/* */}.
App.js
import React, { Component } from 'react';  class App extends Component {    render() {        return (                  <div>                // This is not a valid comment                /* Neither is this */                  {/* THIS ONE IS A VALID COMMENT */}                                  <h1>Welcome to GeeksforGeeks</h1>            </div>        );    }}  export default App;
Output:
Note: We must remember, that even though JSX gets rendered just like normal HTML, it is actually a syntax extension to JavaScript. So, using <!– –> as we did with HTML and XML will not work.
App.js
import React, { Component } from 'react';  class App extends Component {    render() {        return (                 <div>                <!-- This is not a valid comment -->                                  {/* THIS ONE IS A VALID COMMENT */}                                  <h1>Welcome to GeeksforGeeks</h1>            </div>        );    }}  export default App;
Output:
Blogathon-2021
Picked
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Difference Between Local Storage, Session Storage And Cookies
Explain the purpose of render() in ReactJS
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
Python – Adjacent elements in List

11 Oct, 2020
Given a List extract both next and previous element for each element.
Input : test_list = [3, 7, 9, 3] Output : [(None, 7), (3, 9), (7, 3), (9, None)] Explanation : for 7 left element is 3 and right, 9.
Input : test_list = [3, 7, 3] Output : [(None, 7), (3, 3), (7, None)] Explanation : for 7 left element is 3 and right, 3. 
Method : Using loop
In this, we iterate for each element and get next and previous element using element access.
Python3
# Python3 code to demonstrate working of# Adjacent elements in List# Using loop    # Function to find adjacent# elements in Listdef findAdjacentElements(test_list):    res = []    for idx, ele in enumerate(test_list):          # Checking for all cases to append        if idx == 0:            res.append((None, test_list[idx + 1]))        elif idx == len(test_list) - 1:            res.append((test_list[idx - 1], None))        else:            res.append((test_list[idx - 1], test_list[idx + 1]))    return res    # Initializing listinput_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]  # Printing original listprint("The original list is:", input_list)    # printing resultprint("The Adjacent elements list:", findAdjacentElements(input_list))
Output:
The original list is: [3, 7, 8, 2, 1, 5, 8, 9, 3]The Adjacent elements list: [(None, 7), (3, 8), (7, 2), (8, 1), (2, 5), (1, 8), (5, 9), (8, 3), (9, None)]
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python | os.write() method

18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.write() method in Python is used to write a bytestring to the given file descriptor.
A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc.
Note: os.write() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method.
Syntax: os.write(fd, str)
Parameter:fd: The file descriptor representing the target file.str: A bytes-like object to be written in the file.
Return Type: This method returns an integer value which represents the number of bytes actually written.
# Python program to explain os.write() method     # importing os module import os  # File path path = "/home / ihritik / Documents / GeeksForGeeks.txt"    # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR)    # String to be writtens = "GeeksForGeeks: A Computer science portal for Geeks."  # Convert the string to bytesline = str.encode(s)  # Write the bytestring to the file# associated with the file# descriptor fd and get the number of# Bytes actually writtennumBytes = os.write(fd, line)  print("Number of bytes written:", numBytes)  # close the file descriptoros.close(fd)
Number of bytes written: 51

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Dart Programming - Map.addAll() Function

The Map.addAll() function adds all key-value pairs of other to this map.
Map.addAll(Map<K, V> other) 

other − represents a key value pair.
other − represents a key value pair.
Return Type − void
void main() { 
   Map m = {'name':'Tom','Id':'E1001'}; 
   print('Map :${m}'); 
   
   m.addAll({'dept':'HR','email':'tom@xyz.com'}); 
   print('Map after adding  entries :${m}'); 
} 
It will produce the following output −
Map : {name: Tom, Id: E1001} 
Map after adding entries : {name: Tom, Id: E1001, dept: HR, email: tom@xyz.com}


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to change the background color of the font in PowerShell?

To change the background color of the font, you can use the GUI and command line both.
With GUI − Colors → Screen Background.
CLI −
$host.UI.RawUI.BackgroundColor = "DarkBlue"
You will notice that the background color of the text has been changed to DarkBlue.
JSF - Convertor Tags

JSF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice versa. For example, these tags can convert a text into date object and can validate the format of input as well.
For these tags, you need to use the following namespaces of URI in html node.
<html 
   xmlns = "http://www.w3.org/1999/xhtml" 
   xmlns:f = "http://java.sun.com/jsf/core">
Following are important Convertor Tags in JSF 2.0 −
Converts a String into a Number of desired format
Converts a String into a Date of desired format
Creating a custom convertor

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
How to change the color of a Tkinter rectangle on clicking?

The Canvas widget is one of the most versatile widgets in the Tkinter Library. It is used for creating shapes of different types and sizes, animating objects, visualizing graphics, and many more. To change the property of a particular item in Tkinter, we can use itemconfig(**options) method. It takes options such as background color, outline color, and other useful properties of the items defined in a canvas.
In this example, we will create a rectangle such that the color inside the rectangle would change after clicking a Button.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry
win.geometry("700x300")

# Define a function to change the state of the Widget
def change_color():
   canvas.itemconfig(rectangle, fill='green')

# Define a Canvas Widget
canvas = Canvas(win, width=500, height=240)
canvas.pack()

# Create a rectangle in Canvas
rectangle = canvas.create_rectangle(100, 100, 400, 400, fill='blue')

# Create a Button to Disable the Combobox Widget
ttk.Button(win, text="Change Color", command=change_color).pack()
win.mainloop()
When you run the above code, it will display a window with a blue-colored rectangle at the center.
Now, click the "Change Color" button. It will change the color of the rectangle to green.
C# - Nullables

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows −
< data_type> ? <variable_name> = null;

The following example demonstrates use of nullable data types −
using System;

namespace CalculatorApplication {
   class NullablesAtShow {
      static void Main(string[] args) {
         int? num1 = null;
         int? num2 = 45;
         
         double? num3 = new double?();
         double? num4 = 3.14157;
         
         bool? boolval = new bool?();

         // display the values
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value:

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this −
using System;

namespace CalculatorApplication {
   class NullablesAtShow {
      static void Main(string[] args) {
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         
         num3 = num1 ?? 5.34;      
         Console.WriteLine(" Value of num3: {0}", num3);
         
         num3 = num2 ?? 5.34;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Value of num3: 5.34
Value of num3: 3.14157


    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
Program to find average salary excluding the minimum and maximum salary in Python

Suppoe we have an array with distinct elements called salary where salary[i] is the salary of ith employee. We have to find the average salary of employees excluding the minimum and maximum salary.
So, if the input is like salary = [8000,6000,2000,8500,2500,4000], then the output will be 5125.0, as the minimum and maximum salary values are 2000 and 8500, so excluding them the average salary values are [8000,6000,2500,4000] so the average is (8000 + 6000 + 2500 + 4000)/4 = 5125.
To solve this, we will follow these steps −
delete minimum of salary from salary
delete minimum of salary from salary
delete maximum of salary from salary
delete maximum of salary from salary
return sum of the salary values / number of elements in salary after removal
return sum of the salary values / number of elements in salary after removal
Let us see the following implementation to get better understanding −
 Live Demo
def solve(salary):
   salary.remove(min(salary))
   salary.remove(max(salary))
   return sum(salary)/len(salary)

salary = [8000,6000,2000,8500,2500,4000]
print(solve(salary))
[8000,6000,2000,8500,2500,4000]
5125.0
How to Find Interior and Exterior Skeleton of Binary Images Using MATLAB? - GeeksforGeeks

18 Jan, 2022
Skeletonization is a process for reducing foreground regions in a binary image to a skeletal remnant that largely preserves the extent and connectivity of the original region while throwing away most of the original foreground pixels. In this article, we will see how to find interior and exterior skeleton of binary images using MATLAB in-built function.
Thinning: Thinning is a morphological operation performed on binary images. It removes some selected foreground pixels from binary images and hence thins the image. Mathematically, it is the difference of binary image and the result of hit-or-miss transformation applied on the same binary image.
Inner Skeleton of image: Every binary image can be thinned infinite times. The inner structure is obtained when thinning operation is applied infinite times until the resultant image is 1 pixel thick. The underlying inner skeleton of the binary image is obtained finally.
Exterior Skeleton of image: The exterior skeleton of the image consists of the boundary only and interior pixels of the image are removed. It is different from edge detection because in edge detection we detect all interior edges along with boundary edges. In the exterior skeleton finding the result only consist of the outer boundary and all interior pixels are removed.
Function Used: 
imread( ) inbuilt function is used to read the image.
rgb2gray( ) inbuilt function is used to convert RGB colour image into grayscale.
bwmorph( ) inbuilt function is used to find skeleton of the image.
imtool( ) inbuilt function is used to display the image.
Example:
Matlab
% Find Skeleton of a binary image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % apply morphological operation.k1=bwmorph(k,'skel',Inf); % display original image.imtool(k); % display skeleton of image.imtool(k1);
Output:
Figure 1: Input image
 
Figure 2:Output image
Figure 3: Results on GFGlogo
Example:
Matlab
% MATLAB code for remove% inner pixels of image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % Apply morphological operation.k2=bwmorph(k,'remove',Inf); % display original image.imtool(k); % display boundary image.imtool(k2);
  
Output:
 
Figure 4: Input image 
 
 
Figure 5: Output image
 
Figure 6: Result on GFGlogo
 
surinderdawra388
sumitgumber28
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Laplacian of Gaussian Filter in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Boundary Extraction of image using MATLAB
Sorting odd and even elements separately JavaScript

We are required to write a JavaScript function that takes in an array of Integers.
The function should sort the array such all the odd numbers come first, then followed by the even number.
The order of odd or even numbers within themselves is not of much importance, but all odd numbers should come before any even number.
For example −
If the input array is −
const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];
Then the sorted array should be (it’s one of the many solutions where all odds are before evens) −
const output = [
1, 3, 5, 7, 9,
1, 0, 2, 4, 6,
8, 0
];
const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];
const sortOddEven = (arr = []) => {
   let i = 0, j, temp;
   while (i < arr.length - 1) {
      j = i;
      while (!(arr[j] % 2) && arr[j + 1] % 2) {
         temp = arr[j];
         arr[j] = arr[j + 1];
         arr[j + 1] = temp;
         if (!j) {
            break;
         };
         j--;
      };
      i++;
   };
};
sortOddEven(arr);
console.log(arr);
And the output in the console will be −
[
   1, 3, 5, 7, 9,
   1, 0, 2, 4, 6,
   8, 0
]
C library function - tmpfile()

The C library function FILE *tmpfile(void) creates a temporary file in binary update mode (wb+). The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates.
Following is the declaration for tmpfile() function.
FILE *tmpfile(void)
NA
NA
If successful, the function returns a stream pointer to the temporary file created. If the file cannot be created, then NULL is returned.
The following example shows the usage of tmpfile() function.
#include <stdio.h>

int main () {
   FILE *fp;

   fp = tmpfile();
   printf("Temporary file created\n");

   /* you can use tmp file here */

   fclose(fp);

   return(0);
}
Let us compile and run the above program to create a temporary file in /tmp folder but once your program is out, it will be deleted automatically and the program will produce the following result −
Temporary file created


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
CodeIgniter - File Uploading

Using File Uploading class, we can upload files and we can also, restrict the type and size of the file to be uploaded. Follow the steps shown in the given example to understand the file uploading process in CodeIgniter.
Copy the following code and store it at application/view/Upload_form.php.
<html>
 
   <head> 
      <title>Upload Form</title> 
   </head>
	
   <body> 
      <?php echo $error;?> 
      <?php echo form_open_multipart('upload/do_upload');?> 
		
      <form action = "" method = "">
         <input type = "file" name = "userfile" size = "20" /> 
         <br /><br /> 
         <input type = "submit" value = "upload" /> 
      </form> 
		
   </body>
	
</html>
Copy the code given below and store it at application/view/Upload_success.php
<html>
 
   <head> 
      <title>Upload Form</title> 
   </head>
	
   <body>  
      <h3>Your file was successfully uploaded!</h3>  
		
      <ul> 
         <?phpforeach ($upload_data as $item => $value):?> 
         <li><?php echo $item;?>: <?php echo $value;?></li> 
         <?phpendforeach; ?>
      </ul>  
		
      <p><?php echo anchor('upload', 'Upload Another File!'); ?></p>  
   </body>
	
</html>
Copy the code given below and store it at application/controllers/Upload.php. Create “uploads” folder at the root of CodeIgniter i.e. at the parent directory of application folder.
<?php
  
   class Upload extends CI_Controller {
	
      public function __construct() { 
         parent::__construct(); 
         $this->load->helper(array('form', 'url')); 
      }
		
      public function index() { 
         $this->load->view('upload_form', array('error' => ' ' )); 
      } 
		
      public function do_upload() { 
         $config['upload_path']   = './uploads/'; 
         $config['allowed_types'] = 'gif|jpg|png'; 
         $config['max_size']      = 100; 
         $config['max_width']     = 1024; 
         $config['max_height']    = 768;  
         $this->load->library('upload', $config);
			
         if ( ! $this->upload->do_upload('userfile')) {
            $error = array('error' => $this->upload->display_errors()); 
            $this->load->view('upload_form', $error); 
         }
			
         else { 
            $data = array('upload_data' => $this->upload->data()); 
            $this->load->view('upload_success', $data); 
         } 
      } 
   } 
?>
Make the following change in the route file in application/config/routes.php and add the following line at the end of file.
$route['upload'] = 'Upload';

Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/upload

It will produce the following screen −
After successfully uploading a file, you will see the following screen −
 Print
 Add Notes
 Bookmark this page
C# Enum IsDefined Method

The IsDefined method returns true if a given integral value, or its name as a string, is present in a specified enum.
The following is our enum −
enum Subjects { Maths, Science, English, Economics };
The above is initialized by default i.e.
Maths = 0, Science = 1, English = 2, Economics = 3
Therefore, when we will find 3 using IsDefined(), then it will return True as shown below −
 Live Demo
using System;
public class Demo {
   enum Subjects { Maths, Science, English, Economics };
   public static void Main() {
      object ob;
      ob = 3;
      Console.WriteLine("{0} = {1}", ob, Enum.IsDefined(typeof(Subjects), ob));
   }
}
3 = True
Memory Limit Exceeded Error

13 Jul, 2021
Memory Limit Exceeded Error: It typically occurs when no memory limit has been set. It means that the program is trying to allocate more memory than the memory limit for the particular problem. For Example, if the memory limit is 256 MB, then there is no need to write code that requires more than 256 MB of memory. Generally, all online platforms have the same memory limit as 256 MB. There might be many more reasons due to which this error can occur.
Program 1:
Below is the C++ program to declaring a global 1D array of size 107:
C++
// C++ program to declare the array// of size 10^7 globally #include <bits/stdc++.h>using namespace std; // Variable N initializedconst int N = 1e7; // Global array is declaredint a[N]; // Driver Codeint main(){    for (int i = 0; i < N; ++i) {        a[i] = i;    }    cout << a[N - 1];     return 0;}
9999999
 
Explanation: This code will successfully compile and output is 9999999 because the 1-D array has been declared globally of size 107.
Program 2: Below is the C++ program to declare a global 1D array of size 108:
C++
// C++ code declaring a global 1-D// array of size 10^8#include <bits/stdc++.h>using namespace std; // Variable N is initializedconst int N = 1e8; // Global array is declaredint a[N]; // Driver Codeint main(){    for (int i = 0; i < N; ++i) {        a[i] = i;    }    cout << a[N - 1];    return 0;}
 
 
Output:
 
Memory Limit Exceeded
 
or
 
Segmentation Fault (SIGSEGV)
 
Explanation: In the above program, the users will get a memory limit and exceed as an error, but some online platforms can also give an error as a Segmentation Fault(SIGSEGV). This is because users can only declare a global 1-D array of size 107, not more than that. Here, one declared a global 1-D array of size 108 and therefore has an error as the memory limit exceeded (MLE) occurs.
 
Note: 
 
Note that trying to exceed the memory limit may sometimes result in other errors.
An example would be if users are using malloc in C to allocate memory. If malloc fails because the user is trying to allocate too much, it simply returns a null pointer which, unless checked for it, would probably cause a Run Time Error when the user tries to use it.
Similarly, trying to allocate too much memory in C++ using new would cause a SIGABRT and give Run Time Error.
 
sweetyty
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Date.isValid() API

12 Mar, 2021
The date-and-time.Date.isValid() is a minimalist collection of functions for manipulating JS date and time module which is used to validate the particular date and time with its string format.
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
isValid(arg1[, arg2])
Parameters: This method takes the following arguments as parameters:
arg1: It is the date and time object.
arg2: It is the string format of the given date.
Return Value: This method returns true if and only if the terms are validated.
Example 1:
index.js
// Node.js program to demonstrate the  // Date.isValid() method  // Importing date-and-time moduleconst date = require('date-and-time')  // Parsing the date and time// by using date.parse() methodconst status = date.isValid('29-02-2015', 'DD-MM-YYYY');  // Display the resultif(status)  console.log("Date is valid")else  console.log("Date is not invalid")
Run the index.js file using the following command:
node index.js
Output:
Date is not invalid
Example 2:
index.js
// Node.js program to demonstrate the  // Date.isValid() method  // Importing date-and-time moduleconst date = require('date-and-time')  // Pre parsing the date and time// by using preparse() methodconst result = date.preparse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss');  // Validating the terms// by using date.isValid() methodconst status = date.isValid(result);  // Display the resultif(status)  console.log("Date is valid")else  console.log("Date is not invalid")
Run the index.js file using the following command:
node index.js
Output:
Date is valid
Reference: https://github.com/knowledgecode/date-and-time
NodeJS date-time
NodeJS-API
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Ruby | String chomp! Method

13 Dec, 2019
chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t. If $/ is an empty string, it will remove all trailing newlines from the string. It will return nil if no modifications were made.
Syntax: str.chomp!
Parameters: Here, str is the given string.
Returns: A new string having no record separator from the end or nil if no changes were made.
Example 1:
# Ruby program to demonstrate # the chomp! method        # Taking a string and # using the method puts "Ruby".chomp!puts "Ruby\r\n".chomp 
Output:

Ruby

Example 2:
# Ruby program to demonstrate # the chomp! method        # Taking a string and # using the method puts "String\r\n\r\r\n".chomp!('')puts "Method".chomp!("tho")
Output:
String



Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.chmod method

21 Sep, 2018
os.chmod() method in Python is used to change the mode of path to the numeric mode.
Syntax:
os.chmod(path, mode)
Parameters:path – path name of the file or directory pathmode – mode may take one of the following values:
stat.S_ISUID : Set user ID on execution
stat.S_ISGID : Set group ID on execution
stat.S_ENFMT : Record locking enforced
stat.S_ISVTX : Save text image after execution
stat.S_IREAD : Read by owner.
stat.S_IWRITE : Write by owner.
stat.S_IEXEC : Execute by owner.
stat.S_IRWXU : Read, write, and execute by owner
stat.S_IRUSR : Read by owner
stat.S_IWUSR : Write by owner.
stat.S_IXUSR : Execute by owner.
stat.S_IRWXG : Read, write, and execute by group
stat.S_IRGRP : Read by group
stat.S_IWGRP : Write by group
stat.S_IXGRP : Execute by group
stat.S_IRWXO : Read, write, and execute by others.
stat.S_IROTH : Read by others
stat.S_IWOTH : Write by others
stat.S_IXOTH : Execute by others
Code #1:
# Python program to explain os.chmod() method  # importing necessary librariesimport os, sys, stat  # Set given file read by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IREAD)print("File can be read only by owner.")  # Set given file read by others.os.chmod("/Geeks/gfg.txt", stat.S_IROTH)print("File access changed, can be read by others now.")
Output:
File can be read only by owner.
File access changed, can be read by others now.

 Code #2:
# Python program to explain os.chmod() method  # importing necessary librariesimport os, sys, stat  # Set given file written by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IWRITE)  # Set given file executed by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IXUSR)print("File can be written and executed only by owner.")
Output:
File can be written and executed only by owner.
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python program to print positive numbers in a list

26 Oct, 2018
Given a list of numbers, write a Python program to print all positive numbers in given list.
Example:
Input: list1 = [12, -7, 5, 64, -14]
Output: 12, 5, 64

Input: list2 = [12, 14, -95, 3]
Output: [12, 14, 3]
Example #1: Print all positive numbers from given list using for loop
Iterate each element in the list using for loop and check if number is greater than or equal to 0. If the condition satisfies, then only print the number.
# Python program to print positive Numbers in a List  # list of numberslist1 = [11, -21, 0, 45, 66, -93]  # iterating each number in listfor num in list1:          # checking condition    if num >= 0:       print(num, end = " ")
Output:
11 0 45 66 
 Example #2: Using while loop
# Python program to print positive Numbers in a List  # list of numberslist1 = [-10, 21, -4, -45, -66, 93]num = 0  # using while loop     while(num < len(list1)):          # checking condition    if list1[num] >= 0:        print(list1[num], end = " ")          # increment num     num += 1     
Output:
21 93 
 Example #3: Using list comprehension
# Python program to print Positive Numbers in a List  # list of numberslist1 = [-10, -21, -4, 45, -66, 93]  # using list comprehensionpos_nos = [num for num in list1 if num >= 0]  print("Positive numbers in the list: ", *pos_nos)
Output:
Positive numbers in the list:  45 93
 Example #4: Using lambda expressions
# Python program to print positive Numbers in a List  # list of numbers list1 = [-10, 21, 4, -45, -66, 93, -11]     # we can also print positive no's using lambda exp. pos_nos = list(filter(lambda x: (x >= 0), list1))  print("Positive numbers in the list: ", *pos_nos) 
Output:
Positive numbers in the list:  21, 4, 93
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
What does start() function do in multithreading in Java?

29 Nov, 2021
We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don’t we directly call the overridden run() function? Why always the start function is called to execute a thread?What happens when a function is called? When a function is called the following operations take place:  
The arguments are evaluated.A new stack frame is pushed into the call stack.Parameters are initialized.Method body is executed.Value is returned and current stack frame is popped from the call stack.
The arguments are evaluated.
A new stack frame is pushed into the call stack.
Parameters are initialized.
Method body is executed.
Value is returned and current stack frame is popped from the call stack.
The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM.Let us see what happens if we don’t call start() and rather call run() directly. We have modified the first program discussed here.  
Java
// Java code to see that all threads are// pushed on same stack if we use run()// instead of start().class ThreadTest extends Thread{  public void run()  {    try    {      // Displaying the thread that is running      System.out.println ("Thread " +                Thread.currentThread().getId() +                " is running");     }    catch (Exception e)    {      // Throwing an exception      System.out.println ("Exception is caught");    }  }} // Main Classpublic class Main{  public static void main(String[] args)  {    int n = 8;    for (int i=0; i<n; i++)    {      ThreadTest object = new ThreadTest();       // start() is replaced with run() for      // seeing the purpose of start      object.run();    }  }}
Output:  
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
We can see from above output that we get same ids for all threads because we have directly called run(). The program that calls start() prints different ids (see this)References:  
http://www.javatpoint.com/what-if-we-call-run()-method-directly
http://www.leepoint.net/JavaBasics/methods/methods-25-calls.html
This article is contributed by kp93. 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. 
varshagumber28
surindertarika1234
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interacting with Webpage – Selenium Python

10 Sep, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways to find elements. For example, given an element defined as:  
html
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example, 
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")

Also, to find multiple elements, we can use –  
elements = driver.find_elements_by_name("passwd")

One can also look for a link by its text, but be careful! The text must be an exact match! One should also be careful when using XPATH in WebDriver. If there’s more than one element that matches the query, then only the first will be returned. If nothing can be found, a NoSuchElementException will be raised. WebDriver has an “Object-based” API, we represent all types of elements using the same interface. This means that although one may see a lot of possible methods one could invoke when one hits IDE’s auto-complete key combination, not all of them will make sense or be valid. To check all methods, checkout Locator Strategies – Selenium Python So after getting an element what next? One might want to enter text into a field, for example,  
element.send_keys("some text")

One can simulate pressing the arrow keys by using the “Keys” class:  
element.send_keys(" and some", Keys.ARROW_DOWN)

Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail. One can easily clear the contents of a text field or textarea with the clear method: 
element.clear()

Project Example – Let’s try to search something automatically at geeksforgeeks Program –  
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_id("gsc-i-id1") # send keyselement.send_keys("Arrays")
Output-  
 
a7xfor3ver
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
numpy.subtract() in Python

10 Feb, 2019
numpy.subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.
Syntax : numpy.subtract(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘subtract’)
Parameters :arr1 : [array_like or scalar]1st Input array.arr2 : [array_like or scalar]2nd Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray or scalar] The difference of arr1 and arr2, element-wise. Returns a scalar if both arr1 and arr2 are scalars.
Code #1 :
# Python program explaining# numpy.subtract() function  import numpy as geekin_num1 = 4in_num2 = 6  print ("1st Input  number : ", in_num1)print ("2nd Input  number : ", in_num2)    out_num = geek.subtract(in_num1, in_num2) print ("Difference of two input number : ", out_num) 
1st Input number :  4
2nd Input number :  6
Difference of two input number :  -2

 
Code #2 :
# Python program explaining# numpy.subtract() function  import numpy as geek  in_arr1 = geek.array([[2, -4, 5], [-6, 2, 0]])in_arr2 = geek.array([[0, -7, 5], [5, -2, 9]])   print ("1st Input array : ", in_arr1)print ("2nd Input array : ", in_arr2)       out_arr = geek.subtract(in_arr1, in_arr2) print ("Output array: ", out_arr) 
1st Input array :  [[ 2 -4  5]
 [-6  2  0]]
2nd Input array :  [[ 0 -7  5]
 [ 5 -2  9]]
Output array:  [[  2   3   0]
 [-11   4  -9]]


Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python