code-rag-bench/online-tutorials huggingface dataset:
final local variable in Java

Local variables are declared in methods, constructors, or blocks.
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
final is the only allowed access modifier for local variables.
final is the only allowed access modifier for local variables.
final local variable is not required to be initialized during declaration.
final local variable is not required to be initialized during declaration.
final local variable allows compiler to generate an optimized code.
final local variable allows compiler to generate an optimized code.
final local variable can be used by anonymous inner class or in anonymous methods.
final local variable can be used by anonymous inner class or in anonymous methods.
abstract class AnonymousInner {
   public abstract void display();
}

public class Tester {
   public static void main(String args[]) {

      final int value;
      value = 100;
      AnonymousInner inner = new AnonymousInner() {
         public void display() {
            System.out.println("Accessing value: " + value);
         }
      };
      inner.display();
   }
}
Accessing value: 100
How to programmatically turn on Wifi on Android device?

This example demonstrates how do I programmatically turn on wifi in android device.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Wifi On!"
      android:onClick="enableWifi"/>
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Wifi Off!"
      android:onClick="disableWifi" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   private WifiManager wifiManager;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
   }
   public void enableWifi(View view){
      wifiManager.setWifiEnabled(true);
      Toast.makeText(this, "Wifi enabled", Toast.LENGTH_SHORT).show();
   }
   public void disableWifi(View view){
      wifiManager.setWifiEnabled(false);
      Toast.makeText(this, "Wifi Disabled", Toast.LENGTH_SHORT).show();
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
   <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Increment and Decrement Operators in Python?

Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use
a += 1
to decrement a value, use−
a -= 1
>>> a = 0
>>>
>>> #Increment
>>> a +=1
>>>
>>> #Decrement
>>> a -= 1
>>>
>>> #value of a
>>> a
0
Python does not provide multiple ways to do the same thing .
However, be careful if you are coming from a languae like C, Python doesn’t have “variables” in the sense that C does, instead python uses names and objects and in python integers(int’s) are immutable.
Let’s understand it with an example−
>>> a =1
>>> print(id(a))
1919375088
>>> print(hex(id(a)))
0x726756f0
So what above statement means in python is: create an object of type int having value 1 and give the name a to it. The object is an instance of int having value 1 and the name a refers to it. The assigned name a and the object to which it refers are distinct.
Now lets increment a
>>> a +=1
>>> print(id(a))
1919375104
>>> print(hex(id(a)))
0x72675700
As int are immutable, python understand above statement as
Look up the object that a refers to (it is an int and id 0x726756f0)
Look up the object that a refers to (it is an int and id 0x726756f0)
Look up the value of object 0x726756f0 (it is 1).
Look up the value of object 0x726756f0 (it is 1).
Add 1 to that value (1+1 =2)
Add 1 to that value (1+1 =2)
Create a new int object with value 2 (object with id 0x72675700).
Create a new int object with value 2 (object with id 0x72675700).
Rebind the name a to this new object (0x72675700)
Rebind the name a to this new object (0x72675700)
Now a refers to object 0x72675700 and the previous object (0x726756f0) is no longer refered to by the name a. If there aren’t any other names referring to the original object it will be garbage collected later.
Now a refers to object 0x72675700 and the previous object (0x726756f0) is no longer refered to by the name a. If there aren’t any other names referring to the original object it will be garbage collected later.
So from above, you can understand when we do:
a += 1
This will reassign a to a+1. That’s not an increment operator, because it does not increment a, but it reassign it.
Let’s understand above increment/decrement with some more example−
>>> a = b = c =1
>>> id(a)
1919375088
>>> id(b)
1919375088
>>> id(c)
1919375088
>>> #Above all have the same id
>>>
>>> # Now increment a
>>> a +=1
>>> id(a)
1919375104
>>> id(b)
1919375088
>>> id(c)
1919375088
From above you can understand we have a single object that a, b and c refers to (an int with id 1919375088)
On incrementing the value of a, now a is reasign to a+1 (id: 1919375104) and other b and c refers to same object (1919375088).
Also python does come up with ++/-- operator.
>>> a =1
>>> ++a
1
>>> --a
1
How to parse JSON object in JavaScript?

To parse JSON object in JavaScript, implement the following code −
<!DOCTYPE html>
<html>
   <body>
      <script>
         myData = JSON.parse('{"event1":{"title":"Employment period","start":"12\/29\/2011 10:20 ","end":"12\/15\/2013 00:00 "},"event2":{"title":"Employment period","start":"12\/14\/2011 10:20 ","end":"12\/18\/2013 00:00 "}}')
         myArray = []
         for(var e in myData){
            var dataCopy = myData[e]
            for(key in dataCopy){
               if(key == "start" || key == "end"){
                  dataCopy[key] = new Date(dataCopy[key])
               }
            }
            myArray.push(dataCopy)
         }
         document.write(JSON.stringify(myArray));
      </script>
   </body>
</html>
Removing leading zeros from a String using apache commons library in Java

The stripStart() method of the org.apache.commons.lang.StringUtils class accepts two strings and removes the set of characters represented by the second string from the string of the first string.
To remove leading zeros from a string using apache communal library −
Add the following dependency to your pom.xml file
Add the following dependency to your pom.xml file
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>
Get the string.
Get the string.
Pass the obtained string as first parameter and a string holding 0 as second parameter to the stripStart() method of the StringUtils class.
Pass the obtained string as first parameter and a string holding 0 as second parameter to the stripStart() method of the StringUtils class.
The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the stripStart() method of the StringUtils class.
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class LeadingZeroesCommons {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String: ");
      String str = sc.nextLine();
      String result = StringUtils.stripStart(str, "0");
      System.out.println(result);
   }
}
Enter a String:
000Hello how are you
Hello how are you
Python program to convert seconds into hours, minutes and seconds

In this article, we will learn about the solution to the problem statement given below.
Problem statement: We are given time, we need to convert seconds into hours & minutes to seconds.
There are three approaches as discussed below−
 Live Demo
def convert(seconds):
   seconds = seconds % (24 * 3600)
   hour = seconds // 3600
   seconds %= 3600
   minutes = seconds // 60
   seconds %= 60
   return "%02d:%02d:%02d" % (hour, minutes, seconds) #formatting
n = 23451
print(convert(n))
06:30:51
 Live Demo
#using date-time module
import datetime
def convert(n):
   return str(datetime.timedelta(seconds = n))
n = 23451
print(convert(n))
6:30:51
 Live Demo
#using time module
import time
def convert(seconds):
   return time.strftime("%H:%M:%S", time.gmtime(n))
n = 23451
print(convert(n))
06:30:51
In this article, we have learned about how we can convert seconds into hours, minutes and seconds.
Bootstrap nav-pills class

To turn the tabs into pills, use the class .nav-pills. You can try to run the following code to implement Bootstrap Pills
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h2>Subjects</h2>
      <ul class = "nav nav-pills">
         <li class = "active"><a href = "#">Java</a></li>
         <li><a href = "#">WordPress</a></li>
         <li><a href = "#">JavaScript</a></li>
         <li><a href = "#">AngularJS</a></li>
      </ul>
   </body>
</html>
__name__ (A Special variable) in Python

Unlike other programming languages, python is not designed to start execution of the code from a main function explicitly. A special variable called __name__ provides the functionality of the main function. As it is an in-built variable in python language, we can write a program just to see the value of this variable as below.
print type(__name__)
print __name__
Running the above code gives us the following result −
<type 'str'>
__main__
As you can see above the value of the __name__ variable is of string data type and equals to ___main__.
Below are the two key features of __name__ variable.
1. When you run any well-written stand-alone python script which is not referring to any other script, the value of __name__ variable is equal to __main__.
Let's write a program named standalone.py to illustrate this feature.
def func1():
   print 'The value of __name__ is ' + __name__
if __name__ == '__main__':
   func1()
Running the above code gives us the following result −
The value of __name__ is __main__
As expected the __name__ variable evaluates to __main__ hence the output.
2. The second feature is about importing one python script into another. In such a scenario, there seem to be two different scopes which can be considered as the main() function. The first scope can be the __main__ variable of the currently running program and the second the scope of the __main__ variable of the imported script used in the current program.
So which __main__ variable will be used 
when you run a function from the imported script, the __name__ variable will evaluate to the actual name of the script and not equal to __main__.
But when you find out the value of the name variable from the current program, without referring to the imported script, it will evaluate to __main__ as expected, as that is the scope of the program at level 0 indention.
The below program illustrates this example.
import standalone as sa

print('Running the imported script')
sa.func1()

print('\n')
print('Running the current script')
print 'The value of __name__ is ' + __name__
Running the above code gives us the following result −
Running the imported script
The value of __name__ is standalone

Running the current script
The value of __name__ is __main__
The usefulness of this approach is when the code if __name__ == "__main__": is used, the python interpreter checks if it's parsing the currently executed script, or if it's temporarily parsing another external script. This way the programmer has the ability to control the behaviors of different parts of the program by choosing to run lines of code from the external script as well as the currently executed script depending on the scenarios.
How to pass pointers as parameters to methods in C#?

To pass pointers as parameters to methods, refer the below steps −
Firstly, crate a function swap with unsafe modifier.
public unsafe void swap(int* p, int *q) {
   int temp = *p;
   *p = *q;
   *q = temp;
}
Now under static void main, add the value for the first and second variable, set pointers for both of them.
Display the values of the variables and then call the swap() method shown above. The method swaps the values and displays the result −
public unsafe static void Main() {
   Program p = new Program();
   int var1 = 10;
   int var2 = 20;
   int* x = &var1;
   int* y = &var2;

   Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
   p.swap(x, y);

   Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
   Console.ReadKey();
}
Robot Bounded In Circle C++

Suppose we have an infinite plane, a robot initially stands at position (0, 0) and faces north. The robot can receive one of three instructions −
G − go straight 1 unit;
G − go straight 1 unit;
L − turn 90 degrees to the left direction;
L − turn 90 degrees to the left direction;
R − turn 90 degrees to the right direction.
R − turn 90 degrees to the right direction.
The robot performs the instructions given in order, Instructions are repeated forever. We have to check whether there exists a circle in the plane such that the robot never leaves the circle. So if the input is like [GGLLGG], then the answer will be true. from (0,0) to (0,2), it will loop forever, so this is a closed path, and the answer is true.
To solve this, we will follow these steps −
make an array dir := [[0,1], [1,0], [0,-1], [-1,0]]
make an array dir := [[0,1], [1,0], [0,-1], [-1,0]]
make a pair temp, and initially this is (0, 0) and k := 0
make a pair temp, and initially this is (0, 0) and k := 0
for i in range 0 to size of sif s[i] is G, thentemp := (dir[k, 0], dir[k, 1])otherwise when s[i] is L, then k := (k + 1) mod 4, otherwise k := (k - 1) mod 4
for i in range 0 to size of s
if s[i] is G, thentemp := (dir[k, 0], dir[k, 1])
if s[i] is G, then
temp := (dir[k, 0], dir[k, 1])
temp := (dir[k, 0], dir[k, 1])
otherwise when s[i] is L, then k := (k + 1) mod 4, otherwise k := (k - 1) mod 4
otherwise when s[i] is L, then k := (k + 1) mod 4, otherwise k := (k - 1) mod 4
if false when temp is not (0, 0) and k > 0, otherwise true
if false when temp is not (0, 0) and k > 0, otherwise true
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
class Solution {
   public:
   bool isRobotBounded(string s) {
      pair <int, int> temp({0,0});
      int k = 0;
      for(int i = 0; i < s.size(); i++){
         if(s[i] == 'G'){
            temp.first += dir[k][0];
            temp.second += dir[k][1];
         }else if(s[i] == 'L'){
            k = (k + 1) % 4;
         }else{
            k = ((k - 1) + 4) % 4;
         }
      }
      return temp.first == 0 && temp.second == 0 || k > 0;
   }
};
main(){
   Solution ob;
   cout << (ob.isRobotBounded("GGLLGG"));
}
"GGLLGG"
1
Python | os.DirEntry.path attribute

28 Aug, 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.scandir() method of os module yields os.DirEntry objects corresponding to the entries in the directory given by specified path. os.DirEntry object has various attributes and method which is used to expose the file path and other file attributes of the directory entry.
path attribute of os.DirEntry object is used to get entry’s full path name. The full path is absolute only if the path parameter used in os.scandir() method is absolute. Also if os.scandir() method path parameter was a file descriptor then the value of os.DirEntry.path attribute is same as os.DirEntry.name attribute.
Note: os.DirEntry objects are intended to be used and thrown away after iteration as attributes and methods of the object cache their values and never refetch the values again. If the metadata of the file has been changed or if a long time has elapsed since calling os.scandir() method. we will not get up-to-date information.
Syntax: os.DirEntry.path
Parameter: None
Return value: This attribute returns a bytes value if os.scandir() path parameter is bytes otherwise returns a string value which represents the entry’s full path.
Code #1: Use of os.DirEntry.path attribute
# Python program to explain os.DirEntry.path attribute   # importing os module  import os  # Directory to be scanned# Current working directorypath = os.getcwd()  # Using os.scandir() method# scan the specified directory# and yield os.DirEntry object# for each file and sub-directory  print("Full path of all directory entry in '% s':" % path) with os.scandir(path) as itr:    for entry in itr :        # Exclude the entry name        # starting with '.'          if not entry.name.startswith('.') :            # print entry's name            # and its full path             print(entry.name, ":", entry.path)
Full path of all directory entry in '/home/ihritik':
Public : /home/ihritik/Public
Desktop : /home/ihritik/Deskop
R : /home/ihritik/R
foo.txt : /home/ihritik/foo.txt
graph.cpp : /home/ihritik/graph.cpp
tree.cpp : /home/ihritik/tree.cpp
Pictures : /home/ihritik/Pictures
abc.py : /home/ihritik/abc.py
file.txt : /home/ihritik/file.txt
Videos : /home/ihritik/Videos
images : /home/ihritik/images
Downloads : /home/ihritik/Downloads
GeeksforGeeks : /home/ihritik/GeeksforGeeks
Music : /home/ihritik/Music
Documents : /home/ihritik/Documents

References: https://docs.python.org/3/library/os.html#os.DirEntry.path
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
How to create a hidden input field in form using HTML ?

18 Oct, 2021
In this article, we will learn how to add a hidden input field into our form using HTML. A hidden control stores the data that is not visible to the user. It is used to send some information to the server which is not edited by the user.  Normally, this hidden field usually contains the value which is common for all the users. The value must be recorded in the database. 
A hidden input field often contains those value which needs to be updated on the database when the form is submitted. 
Approach:
We create an HTML Document that contains an <input> Tag.
Use the type attribute with the <input> tag.
Set the type attribute to value “hidden“.
Syntax:
<input type="hidden">  
Example: In this code, we create a hidden field that contains a record of the user who belongs to the same country i.e India. 
HTML
<!DOCTYPE html><html>  <head>    <title>        How to create a hidden input           field in form using HTML?    </title>          <style>        h1 {            color:green;        }        body {            text-align:center;        }    </style></head>  <body>    <h1>        GeeksforGeeks    </h1>        <h3>        How to create a hidden input           field in form using HTML?    </h3>          <form action="#">        <input type="hidden" name="country_name"             id="inputID" value="India" >              Name: <input type="text">                  <input type="submit" value="Submit">    </form></body>    </html>
Output:             
hidden input field
HTML-Questions
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to Extract the Last Word From a Cell in Excel?

30 Nov, 2021
In this article, we explain how to extract the last word from a text in a cell using the Excel function.  Extracting words from a text is an important task in text processing.  
Eg.  Suppose we have a data file with a field called “Product_Category”, which was combined both product name and their respective category name with space as below.  Assume that the last word from the “Product_Category” field is a category.  We have to extract categories from the given data in column B for further analysis.
Sample Data:
We use the below list of 4 Excel user-defined functions to extract the last word.
Syntax:
REPT(text, number)
Where,
text – character to repeat
number – number of times to repeat the character
Eg: REPT(“*“,10) – returns **********
Syntax:
SUBSTITUTE( text, old_text, new_text, [instance_number] )
Where,
text – the original text 
old_text – text need to replace
new_text –text replace with old text
[instance_number] – Optional. The number indicates the instance number of old text to replace
Eg: SUBSTITUTE(“Filo Mix”,” “,REPT(“*”,10)) – returns Filo**********Mix
Syntax:
RIGHT( text, [number_of_characters] )
Where,
text – original text 
[number_of_characters] – optional. Number characters extract from the right.
Eg: RIGHT(“Filo**********Mix”) – returns *******Mix
Syntax:
TRIM(text)
Where,
text – Removes leading and trailing spaces
Eg: Eg: Trim(“Mix”) – returns Mix 
Follow the below steps to  Extract the last word from a Cell in Excel:
Step 1: Write header “Category” in cell B1.
Step 2: Write the below formula to cells “B2”.  In the given data category name is not more than 10 characters.  So we used 10 in both REPT() and SUBSTITUTE().  You can use any number greater than the maximum of the last word.
=TRIM(RIGHT(SUBSTITUTE(A2," ",REPT(" ",10)),10))
Step 3: Drag formula B2 to B14 to fill the same formula to all other cells
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Macros in Excel
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel?
Python | Reverse sequence of strictly increasing integers in a list

17 Apr, 2019
Given a list of integers, write a Python program to reverse the order of consecutively incrementing chunk in given list.
Examples:
Input : [0, 1, 9, 8, 7, 5, 3, 14]
Output : [9, 1, 0, 8, 7, 5, 14, 3]
Explanation: There are two chunks of strictly
             increasing elements (0, 1, 9) and (3, 14). 

Input : [-5, -3, 0, 1, 3, 5, -2, -12]
Output : [5, 3, 1, 0, -3, -5, -2, -12]
Explanation: Only one chunk of strictly increasing 
             elements exists i.e. (-5, -3, 0, 1, 3, 5).

 Approach #1 : Naive (Using extended slices)
A naive approach to solve the given problem is to use extended slice. We initialize two variables ‘res’ (to store final output) and block( to store chunks of incrementing integers) with empty lists. Now using a for loop, every time we check if the current element is less than the last element of block or not. If yes, add reversed chunk to ‘res’ using extended slicing (block[::-1]) and clean block (block[:] = [i]). otherwise, simply append the element to ‘block’. At last, extend ‘res’ by reversing block and output it.
# Python3 program to Reverse order # of incrementing integers in list  def reverseOrder(lst):    res = []     block = []    for i in lst:          # check if the current element is less         # than the last element of block         if block and i < block[-1]:              # add reversed chunk to 'res'            res.extend(block[::-1])             block[:] = [i]              else:              # append the element to 'block'            block.append(i)          # extend 'res' by reversing block        res.extend(block[::-1])    return(res)              # Driver codelst = [0, 1, 9, 8, 7, 5, 3, 14]print(reverseOrder(lst))
[9, 1, 0, 8, 7, 5, 14, 3]

 Approach #2 : Using list comprehension
An efficient approach to the above problem is to use list comprehension. It first finds out all the positions where the incrementing integers begin and stores them in a variable ‘break_’. After this, all the chunks are reversed and are managed in the form of sublists, which are in turn stored in ‘block’. Finally, ‘block’ is unzipped and returned.
# Python3 program to Reverse order # of incrementing integers in list  def reverseOrder(lst):    break_ = [0] + [i for i in range(1, len(lst))     if lst[i-1] > lst[i]] + [len(lst)]          block =[list(reversed(lst[i:j]))     for i, j in zip(break_[:-1], break_[1:])]          return(sum(block, []))               # Driver codelst = [0, 1, 9, 8, 7, 5, 3, 14]print(reverseOrder(lst))
[9, 1, 0, 8, 7, 5, 14, 3]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to disable (grey out) a checkbutton in Tkinter?

Tkinter provides a variety of input widgets such as entry widget, text widget, listbox, combobox, spinbox, checkbox, etc. Checkboxes are used for taking validity input and the state gets active whenever the user clicks on the checkbutton. In terms of a particular application, we can enable and disable the state of CheckButtons by using the state property.
#Import the required library
from tkinter import*
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x250")
#Create CheckButtons
chk= ttk.Checkbutton(win, text="Python")
chk.pack()
chk.config(state=DISABLED)
win.mainloop()
Running the example code will display a window with a check button that is initially disabled.
We can change the state of the checkbuttons by changing the values of the state property to NORMAL or DISABLED.
Generating dynamic URLs in Flask

15 Oct, 2021
Prerequisites: Basics of Flask
When creating an application, it’s quite cumbersome to hard-code each URL. A better way to resolve this problem is through building Dynamic URLs.  Let us briefly understand the meaning of a few common terms first.
Dynamic Routing: It is the process of getting dynamic data(variable names) in the URL and then using it.
Variable Rules: Variable sections can be added to a URL by marking sections with <variable_name>.
Let us first create a basic flask application:
Python3
#importing the flask Modulefrom flask import Flask # Flask constructor takes the name of# current module (__name__) as argumentapp = Flask(__name__) @app.route('/')# ‘/’ URL is bound with hello_world() function.def home():    return 'You are at home page.' @app.route('/allow')def allow():    return 'You have been allowed to enter.' @app.route('/disallow')def disallow():    return 'You have not been allowed to enter.' # main driver functionif __name__ == '__main__':    # run() method of Flask class runs the application    # on the local development server.    app.run()
Output:
Now consider a situation where you have many users and you want to route the user to a specific page with his or her name or ID in the URL as well as the template. If you try to do this manually then you have to manually type the complete URL for every user. Doing this can be very tedious and next to impossible. However, this can be solved using the flask with something called dynamic routing. 
We shall now look at a better approach using Variable Rules. We will add a <variable name> with each route. Optionally, we can also define the converter with each variable name <converter: variable name>. By default, the converter is String.
Example:
@app.route('allow/<variable name>')

OR

@app.route('allow/<converter: variable name>')
Some converters are:
Let’s allow the user with having an ID of less than 25 to visit the page. The modified code with dynamic URL binding is given below. The function uses the <variable name> passed in route() decorator as an argument.  
@app.route('/allow/<int:Number>')
def allow(Number):
    if Number < 25:
        return f'You have been allowed to enter because\
         your number is {str(Number)}'
    else:
       return f'You are not allowed'
Python3
#importing the flask Modulefrom flask import Flask # Flask constructor takes the name of# current module (__name__) as argumentapp = Flask(__name__) @app.route('/')# ‘/’ URL is bound with hello_world() function.def home():    return 'You are at home page.' # Use of <converter: variable name> in the# route() decorator.@app.route('/allow/<int:Number>')def allow(Number):    if Number < 25:        return f'You have been allowed to enter because your number is {str(Number)}'    else:       return f'You are not allowed' # main driver functionif __name__ == '__main__':    # run() method of Flask class runs the application    # on the local development server.    app.run()
Output:
simmytarika5
surindertarika1234
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Typedef in Dart

08 Oct, 2020
Typedef in Dart is used to create a user-defined identity (alias) for a function, and we can use that identity in place of the function in the program code. When we use typedef we can define the parameters of the function.
Syntax: typedef function_name ( parameters );

With the help of typedef, we can also assign a variable to a function.
Syntax:typedef variable_name = function_name;

After assigning the variable, if we have to invoke it then we go as:
Syntax: variable_name( parameters );

By this we will be able to use a single function in different ways:
Example 1:  Using typedef in Dart.
Dart
// Dart program to show the usage of typedef // Defining alias nametypedef GeeksForGeeks(int a, int b); // Defining Geek1 functionGeek1(int a, int b) {  print("This is Geek1");  print("$a and $b are lucky geek numbers !!");} // Defining Geek2 functionGeek2(int a, int b) {  print("This is Geek2");  print("$a + $b is equal to ${a + b}.");} // Main Functionvoid main(){  // Using alias name to define  // number with Geek1 function    GeeksForGeeks number = Geek1;  // Calling number  number(1,2);     // Redefining number  // with Geek2 function  number = Geek2;  // Calling number  number(3,4);}
Output:
This is Geek1
1 and 2 are lucky geek numbers !!
This is Geek2
3 + 4 is equal to 7.

Note: Apart from this, typedef can also act as parameters of a function.
Example 2: Using typedef as a parameter of a function.
Dart
// Dart program to show the usage of typedef // Defining alias nametypedef GeeksForGeeks(int a, int b); // Defining Geek1 functionGeek1(int a, int b) {  print("This is Geek1");  print("$a and $b are lucky geek numbers !!");} // Defining a function with a typedef variablenumber(int a, int b, GeeksForGeeks geek) {  print("Welcome to GeeksForGeeks");  geek(a, b);} // Main Functionvoid main(){  // Calling number function  number(21,23, Geek1);}
Output:
Welcome to GeeksForGeeks
This is Geek1
21 and 23 are lucky geek numbers !!

addamkoroma
Dart Function
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Dart Tutorial
Flutter - Stack Widget
Flutter - Search Bar
Container class in Flutter
Operators in Dart
Flutter - Dialogs
Flutter - FutureBuilder Widget
Convert 2D array to object using map or reduce in JavaScript

Let’s say, we have a two-dimensional array that contains some data about the age of some
people.
The data is given by the following 2D array
const data = [
   ['Rahul',23],
   ['Vikky',27],
   ['Sanjay',29],
   ['Jay',19],
   ['Dinesh',21],
   ['Sandeep',45],
   ['Umesh',32],
   ['Rohit',28],
];
We are required to write a function that takes in this 2-D array of data and returns an object with
key as the first element of each subarray i.e., the string and value as the second element.
We will use the Array.prototype.reduce() method to construct this object, and the code for doing this will be −
const data = [
   ['Rahul',23],
   ['Vikky',27],
   ['Sanjay',29],
   ['Jay',19],
   ['Dinesh',21],
   ['Sandeep',45],
   ['Umesh',32],
   ['Rohit',28],
];
const constructObject = arr => {
   return arr.reduce((acc, val) => {
      const [key, value] = val;
      acc[key] = value;
      return acc;
   }, {});
};
console.log(constructObject(data));
The output in the console will be −
{
   Rahul: 23,
   Vikky: 27,
   Sanjay: 29,
   Jay: 19,
   Dinesh: 21,
   Sandeep: 45,
   Umesh: 32,
   Rohit: 28
}
D3.js | d3.mean() function

26 Jun, 2019
The d3.mean() function in D3.js is used to return the mean or average of the given array’s elements. If the array is empty then it returns undefined.
Syntax:
d3.mean(Array)
Parameters: This function accepts a parameters Array which is an array of elements whose mean are to be calculated. Here elements should be integers not string otherwise it returns undefined.
Return Value: It returns the mean or average of the given array’s element.
Below programs illustrate the d3.mean() function in D3.js.
Example 1:
<html>  <head>    <title>      Getting mean of the      elements of given array  </title></head>  <body>    <script src='https://d3js.org/d3.v4.min.js'>  </script>      <script>        // initialising the array of elements        var Array1 = [10, 20, 30, 40, 50, 60];        var Array2 = [1, 2];        var Array3 = [0, 1.5, 6.8];        var Array4 = [.8, .08, .008];          // Calling to d3.mean() function        A = d3.mean(Array1);        B = d3.mean(Array2);        C = d3.mean(Array3);        D = d3.mean(Array4);          // Getting mean of the given array's element        document.write(A + "<br>");        document.write(B + "<br>");        document.write(C + "<br>");        document.write(D + "<br>");    </script></body>  </html>
Output:
35
1.5
2.766666666666667
0.296
Example 2:
<html>  <head>    <title>      Getting mean of the       elements of given array  </title></head>  <body>    <script src='https://d3js.org/d3.v4.min.js'>  </script>      <script>        // initialising the array of elements        var Array1 = [];        var Array2 = ["a", "b", "c"];        var Array3 = [1, "B", "C"];        var Array4 = ["Geek", "Geeks", 2, 3, "GeeksforGeeks"];          // Calling to d3.mean() function        A = d3.mean(Array1);        B = d3.mean(Array2);        C = d3.mean(Array3);        D = d3.mean(Array4);          // Getting mean of the given array's element        document.write(A + "<br>");        document.write(B + "<br>");        document.write(C + "<br>");        document.write(D + "<br>");    </script></body>  </html>
Output:
undefined
undefined
1
2.5
Note: In the above output, if the parameter is empty or strings then it returns undefined and if the parameter is string including some integers value then the mean of the integer’s value is returned.
Ref: https://devdocs.io/d3~4/d3-array#mean
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
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 ?
How to overwrite or remove PowerShell alias?

You can overwrite the Powershell alias by redefining it. For example, if the alias is created Edit for Notepad.exe and if you want to overwrite it with another program, say wordpad.exe then use the below command.
We will overwrite the Edit alias cmdlet with Wordpad.exe using the Set-Alias command. When you close the PowerShell session, it will remove newly created aliases and modified
aliases.
Set-Alias edit "C:\Program Files\Windows NT\Accessories\wordpad.exe"
You cannot overwrite pre-defined aliases. It will throw an exception.
For example, when you try to modify dir alias which points to Get-Content, error output will be as below.
To remove newly created aliases without closing the PowerShell console, you need to use RemoveAlias command.
Remove-Alias -AliasName Edit
You can also use Del command to remove the alias.
Del alias:Edit
Again you cannot remove the Aliases which are permanent. Only newly created aliases can be removed and automatically deleted when the session ends.
Where Does Python Look for Modules?

20 Aug, 2021
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module in that file and then we can use them. Modules can exist in various directories.
In this article, we will discuss where does python looks for modules.
Python looks for modules in 3 steps:-
First, it searches in the current directory.If not found then it searches in the directories which are in shell variable PYTHONPATHIf that also fails python checks the installation-dependent list of directories configured at the time Python is installed
First, it searches in the current directory.
If not found then it searches in the directories which are in shell variable PYTHONPATH
If that also fails python checks the installation-dependent list of directories configured at the time Python is installed
Now we will discuss each of these steps:
Step 1: Firstly the python searches in the current directory. From the current directory we mean the directory in which the file calling the module exists. We can check the working directory from os module of python by os.getcwd() method. The directory returned from this method is referred to as the current directory. The code for getting the current directory is:
Python
# importing os moduleimport os        # printing the current working directoryprint(os.getcwd())
The output of the above code will be the current working directory which will be first searched for a module to be imported.
Step 2: If the module that needs to be imported is not found in the current directory. Then python will search it in the PYTHONPATH which is a list of directory names, with the same syntax as the shell variable PATH. To know the directories in PYTHONPATH we can simply get them by the sys module. The sys.path gives us the list of all the paths where the module will be searched when it is needed to import. To see these directories we have to write the following code:
Python
# importing the sys moduleimport sys         # printing sys.path variable of sys moduleprint(sys.path)
Step 3: If the module is not found in the above 2 steps the python interpreter then tries to find it in installation dependent list of directories that are configured at the time of installation of python. These directories are also included in sys.path variable of sys module and can be known in the same way as the above step. The code will be:
Python
# importing the sys moduleimport sys         # printing sys.path variable of sys moduleprint(sys.path)
simranarora5sos
Picked
python-modules
python-os-module
Python-sys
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to avoid ConcurrentModificationException while iterating a collection in java?

When you are working with collection objects, while one thread is iterating over a particular collection object, if you try to add or remove elements from it, a ConcurrentModificationException will be thrown.
Not only that, If you are iterating a collection object, add or remove elements to it and try to iterate its contents again it is considered that you are trying to access the collection object using multiple threads and ConcurrentModificationException is thrown.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
   public static void main(String args[]) {
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+", ");
      }
      //list.remove(3);
      list.add(3, "Hadoop");
      while(it.hasNext()) {
         System.out.print(it.next()+", ");
      }
   }
}
Contents of the array list (first to last):
JavaFX, Java, WebGL, OpenCV, Exception in thread "main"
java.util.ConcurrentModificationException
   at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
   at java.util.ArrayList$Itr.next(Unknown Source)
   at sample.OccurenceOfElements.main(OccurenceOfElements.java:23)
To resolve this while accessing collection objects from multiple threads use synchronized block or method and, if you are modifying data while retrieving it, get the Iterator object again after modifying the data.
 Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
   public static void main(String args[]) {
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+". ");
      }
      list.remove(3);
      System.out.println("");
      System.out.println("Contents of the array list after removal: ");
      it = list.iterator();
      while(it.hasNext()) {
         System.out.print(it.next()+". ");
      }
   }
}
Contents of the array list (first to last):
JavaFX. Java. WebGL. OpenCV.
Contents of the array list after removal:
JavaFX. Java. WebGL.
How to add a prefix to columns of an R data frame?

If we want to provide more information about the data, we have in columns of an R data frames then we might want to use prefixes. These prefixes help everyone to understand the data, for example, we can use data set name as a prefix, the analysis objective as a prefix, or something that is common among all the columns. To add a prefix to columns of an R data frame, we can use paste function to separate the prefix with the original column names.
Consider the below data frame −
set.seed(100)
Rate <-sample(1:100,20)
Level <-sample(1:10,20,replace=TRUE)
Region <-rep(1:4,times=5)
df <-data.frame(Rate,Level,Region)
df
Rate Level Region
1 74 2 1
2 89 3 2
3 78 4 3
4 23 4 4
5 86 4 1
6 70 5 2
7 4 7 3
8 55 9 4
9 95 4 1
10 7 2 2
11 91 6 3
12 93 7 4
13 43 1 1
14 82 6 2
15 61 9 3
16 12 9 4
17 51 9 1
18 72 6 2
19 18 8 3
20 25 7 4
Adding prefix to the columns of the data frame df −
colnames(df) <-paste("2FactorData",colnames(df),sep="-")
df
2FactorData-Rate 2FactorData-Level 2FactorData-Region
1 74 2 1
2 89 3 2
3 78 4 3
4 23 4 4
5 86 4 1
6 70 5 2
7 4 7 3
8 55 9 4
9 95 4 1
10 7 2 2
11 91 6 3
12 93 7 4
13 43 1 1
14 82 6 2
15 61 9 3
16 12 9 4
17 51 9 1
18 72 6 2
19 18 8 3
20 25 7 4
Let’s have a look at another example −
x1 <-1:20
x2 <-20:1
y <-rnorm(20)
df_new <-data.frame(x1,x2,y)
df_new
   x1    x2    y
1 1 20 -0.69001432
2 2 19 -0.22179423
3 3 18 0.18290768
4 4 17 0.41732329
5 5 16 1.06540233
6 6 15 0.97020202
7 7 14 -0.10162924
8 8 13 1.40320349
9 9 12 -1.77677563
10 10 11 0.62286739
11 11 10 -0.52228335
12 12 9 1.32223096
13 13 8 -0.36344033
14 14 7 1.31906574
15 15 6 0.04377907
16 16 5 -1.87865588
17 17 4 -0.44706218
18 18 3 -1.73859795
19 19 2 0.17886485
20 20 1 1.89746570
colnames(df_new) <-paste("MultipleRegression",colnames(df_new),sep="_")
df_new
MultipleRegression_x1 MultipleRegression_x2 MultipleRegression_y
1 1 20 -0.69001432
2 2 19 -0.22179423
3 3 18 0.18290768
4 4 17 0.41732329
5 5 16 1.06540233
6 6 15 0.97020202
7 7 14 -0.10162924
8 8 13 1.40320349
9 9 12 -1.77677563
10 10 11 0.62286739
11 11 10 -0.52228335
12 12 9 1.32223096
13 13 8 -0.36344033
14 14 7 1.31906574
15 15 6 0.04377907
16 16 5 -1.87865588
17 17 4 -0.44706218
18 18 3 -1.73859795
19 19 2 0.17886485
20 20 1 1.89746570