code-rag-bench/online-tutorials huggingface dataset:
Java Examples - Producer Consumer Problem

How to solve the producer consumer problem using thread?
Following example demonstrates how to solve the producer consumer problem using thread.
public class ProducerConsumerTest {
   public static void main(String[] args) {
      CubbyHole c = new CubbyHole();
      Producer p1 = new Producer(c, 1);
      Consumer c1 = new Consumer(c, 1);
      p1.start(); 
      c1.start();
   }
}
class CubbyHole {
   private int contents;
   private boolean available = false;
   
   public synchronized int get() {
      while (available == false) {
         try {
            wait();
         } catch (InterruptedException e) {}
      }
      available = false;
      notifyAll();
      return contents;
   }
   public synchronized void put(int value) {
      while (available == true) {
         try {
            wait();
         } catch (InterruptedException e) { } 
      }
      contents = value;
      available = true;
      notifyAll();
   }
}
class Consumer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   
   public Consumer(CubbyHole c, int number) {
      cubbyhole = c;
      this.number = number;
   }
   public void run() {
      int value = 0;
      for (int i = 0; i < 10; i++) {
         value = cubbyhole.get();
         System.out.println("Consumer #" + this.number + " got: " + value);
      }
   }
}
class Producer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   public Producer(CubbyHole c, int number) {
      cubbyhole = c;
      this.number = number;
   } 
   public void run() {
      for (int i = 0; i < 10; i++) {
         cubbyhole.put(i);
         System.out.println("Producer #" + this.number + " put: " + i);
         try {
            sleep((int)(Math.random() * 100));
         } catch (InterruptedException e) { }
      } 
   }
} 
The above code sample will produce the following result.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Deep Search JSON Object JavaScript

Suppose we have the following nested JSON object −
const obj = {
   id: 1,
   title: 'hello world',
   child: {
      id: null,
      title: 'foobar',
      child: {
         id: null,
         title: 'i should be in results array '
      }
   },
   foo: {
      id: null,
      title: 'i should be in results array too!' },
      deep: [
      {
         id: null,
         value: 'yo'
      }, {
         id: null,
         value: 'yo2'
      }
   ]
};
We are required to write a JavaScript function that takes in one such object as the first argument, a key string as the second and a value string as the third argument. The function should then check for the given key value pair in the JSON object.
If there exists any object then the function should return an array of all such objects.
We will use the following approach to solve this problem −
if the searched item is false or if it’s not an object, then we return
if given key and value match, then we add the actual object to the result set,
we get the keys and iterate over the properties and call the function again.
At last, we return the array with the collected objects.
const obj = {
   id: 1,
   title: 'hello world',
   child: {
      id: null,
      title: 'foobar',
      child: {
         id: null,
         title: 'i should be in results array '
      }
   },
   foo: {
      id: null,
      title: 'i should be in results array too!' },
      deep: [
      {
         id: null, value: 'yo'
      }, {
         id: null, value: 'yo2'
      }
   ]
};
const findObject = (obj = {}, key, value) => {
   const result = [];
   const recursiveSearch = (obj = {}) => {
      if (!obj || typeof obj !== 'object') { return;
   };
   if (obj[key] === value){
      result.push(obj);
   };
   Object.keys(obj).forEach(function (k) {
      recursiveSearch(obj[k]);
   });
} recursiveSearch(obj);
return result;
} console.log(findObject(obj, 'id', null));
[
   {
      id: null,
      title: 'foobar',
      child: {
         id: null, title: 'i should be in results array '
      }
   },
   {
         id: null, title: 'i should be in results array '
   }, {
         id: null, title: 'i should be in results array too!'
      }, {
      id: null, value: 'yo'
      }, { id: null, value: 'yo2'
   }
]
Convert.ToString Method in C#

Convert the specified value to its equivalent string using the ToString() method.
Initialize a bool value.
bool boolVal = false;
Now, to convert it to a string, use the ToString() method.
Convert.ToString(boolVal)
The following is the complete example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      bool boolVal = false;
      Console.WriteLine(Convert.ToString(boolVal));
   }
}
False
Batch Script - REM

This batch command is used for remarks in batch files, preventing the content of the remark from being executed.
REM remark description

@echo off 
REM This is a batch file
None

 Print
 Add Notes
 Bookmark this page
java.time.LocalDateTime.ofInstant() Method Example

The java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method obtains an instance of LocalDateTime from an Instant and zone ID.
Following is the declaration for java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method.
public static LocalDateTime ofInstant(Instant instant, ZoneId zone)

instant − the instant to create the date-time from, not null.
instant − the instant to create the date-time from, not null.
zone − the time-zone, which may be an offset, not null.
zone − the time-zone, which may be an offset, not null.
the local date, not null.
DateTimeException − if the result exceeds the supported range.
The following example shows the usage of java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method.
package com.tutorialspoint;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
 
      LocalDateTime date = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
      System.out.println(date);  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-03-17T15:50:22.770

 Print
 Add Notes
 Bookmark this page
Wiggle Sort in C++

Suppose we have an unsorted array called nums, we have to reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... and so on.
So, if the input is like nums = [3,5,2,1,6,4], then the output will be [3,5,1,6,2,4], there may be some other answers.
To solve this, we will follow these steps −
n := size of nums
n := size of nums
for initialize i := 0, when i < n - 1, update i := i + 1, do −if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])
for initialize i := 0, when i < n - 1, update i := i + 1, do −
if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])
if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, then
swap(nums[i], nums[i + 1])
swap(nums[i], nums[i + 1])
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   void wiggleSort(vector<int<& nums) {
      int n = nums.size();
      for(int i = 0; i < n - 1; i+=1){
         if((i % 2 == 0) == ( nums[i] > nums[i + 1])){
            swap(nums[i], nums[i + 1]);
         }
      }
   }
};
main(){
   vector<int< v = {3,5,2,1,6,4};
   Solution ob;
   ob.wiggleSort(v);
   print_vector(v);
}
{3,5,2,1,6,4}
[3, 5, 1, 6, 2, 4, ]
8085 program to convert an 8 bit BCD number into hexadecimal number - GeeksforGeeks

28 Aug, 2019
Problem – Write an assembly language program in 8085 microprocessor to convert an 8 bit BCD number into hexadecimal number.
Assumptions – Assume that starting address of the program is 2000, input memory locations, 2050, 2051, and output memory location is 2052.
Example –
INPUT: 2050:02H
       2051: 09H

OUTPUT:2052: 1DH 
Algorithm –
Initialize memory pointer to 2050Get the most significant digitMultiply the MSD by 10 using repeated additionAdd LSD to result obtained in above stepStore the converted result in memory 2052
Initialize memory pointer to 2050
Get the most significant digit
Multiply the MSD by 10 using repeated addition
Add LSD to result obtained in above step
Store the converted result in memory 2052
Program –
Explanation – Registers H, L, B, A are used for general purpose.
LXI H, 2050: will load the HL pair register with the address 2050 of memory location.MOV A, M: copies the content of memory into register A.ADD A: add the content of accumulator with itself.MOV B, A: move the content of accumulator into register B.ADD A: add the content of accumulator with itself.ADD A: add the content of accumulator with itself.ADD B: add the content of accumulator with register B and store the result in accumulator.INX H: increment register pair HL.ADD M: add the content of accumulator with memory and store the result in accumulator.INX H: increment register pair HL.MOV M, A: copies the content of accumulator into memory.HLT: stops executing the program and halts any further execution.
LXI H, 2050: will load the HL pair register with the address 2050 of memory location.
MOV A, M: copies the content of memory into register A.
ADD A: add the content of accumulator with itself.
MOV B, A: move the content of accumulator into register B.
ADD A: add the content of accumulator with itself.
ADD A: add the content of accumulator with itself.
ADD B: add the content of accumulator with register B and store the result in accumulator.
INX H: increment register pair HL.
ADD M: add the content of accumulator with memory and store the result in accumulator.
INX H: increment register pair HL.
MOV M, A: copies the content of accumulator into memory.
HLT: stops executing the program and halts any further execution.
Akanksha_Rai
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Logical and Physical Address in Operating System
Addressing modes in 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Computer Organization | RISC and CISC
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Memory Hierarchy Design and its Characteristics
Computer Organization | Booth's Algorithm
Difference between Von Neumann and Harvard Architecture
Architecture of 8085 microprocessor
8085 program to add two 8 bit numbers
Python | Check for ASCII string - GeeksforGeeks

25 Jun, 2019
Many times it is desirable to work with the strings that only contain alphabets and the other special characters are undesirable and sometimes this very task becomes the point to filter the strings and hence requires the way to check if a string is whole ASCII. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using ord() + all()The combination of this method can be used to achieve the desirable task. In this method, we search for all the string and check for each character, a value in range of ASCII characters.
# Python3 code to demonstrate# Check for ASCII string# using all() + ord()  # initializing string test_string = "G4G is best"  # printing original string print("The original string : " + str(test_string))  # using all() + ord()# Check for ASCII stringres = all(ord(c) < 128 for c in test_string)  # print resultprint("Is the string full ASCII ? : " + str(res))
The original string : G4G is best
Is the string full ASCII ? : True

 
Method #2 : Using lambda + encode()This task can also be achieved using the above functions. In this combination, lambda function is used to extend the size check logic to whole string and encode function checks if the size of original and encoded strings match.
# Python3 code to demonstrate# Check for ASCII string# using lambda + encode()  # initializing string test_string = "G4G is best"  # printing original string print("The original string : " + str(test_string))  # using lambda + encode()# Check for ASCII stringres = lambda ele: len(ele) == len(ele.encode())  # print resultprint("Is the string full ASCII ? : " + str(res(test_string)))
The original string : G4G is best
Is the string full ASCII ? : True

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
CSS - border-collapse

border-collapse determines the border model used in the rendering of a table.
collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border.
collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border.
separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table.
separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table.
Elements with a display of table or inline-table.
object.style.borderCollapse = "Any of the two values";

Following is the example to show both values −
<html>
   <head>
      <style type = "text/css">
         table.one {border-collapse:collapse;}
         table.two {border-collapse:separate;}
         
         td.a {
            border-style:dotted; 
            border-width:3px; 
            border-color:#000000; 
            padding: 10px;
         }
         td.b {
            border-style:solid; 
            border-width:3px; 
            border-color:#333333; 
            padding:10px;
         }
      </style>
   </head>

   <body>
   
      <table class = "one">
         <caption>Collapse Border Example</caption>
         <tr><td class = "a"> Cell A Collapse Example</td></tr>
         <tr><td class = "b"> Cell B Collapse Example</td></tr>
      </table>
      <br />
      
      <table class = "two">
         <caption>Separate Border Example</caption>
         <tr><td class = "a"> Cell A Separate Example</td></tr>
         <tr><td class = "b"> Cell B Separate Example</td></tr>
      </table>
      
   </body>
</html>
This will produce following result −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Cloning Table in MySQL - GeeksforGeeks

26 Jul, 2020
There may be a number of occasions where you need to create an exact copy of an already defined (or created) table. MySQL enables you to perform this operation. Because we may need such duplicate tables for testing over the data without having any impact over the original table and the data stored in it.
Original_table –
Steps to replicate (Clone) an existing table schema (structure) and it’s content –
Step 1 : To clone a table, use the query below. Using this query an empty schema (structure) of the table gets created with the same attributes of original table :
CREATE TABLE Contact List(Clone_1) LIKE Original_table;
Output : Contact List (Clone_1)
Step 2 : If you want to create a table which is bedecked with all the content of your original table, use this MySQL query :
CREATE TABLE Contact List(Clone_1) AS SELECT * 
FROM Original_table; 
                 OR
INSERT INTO Contact List(Clone_1) SELECT * 
FROM original_table;
Output : Contact List (Clone_1)
SQLmysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Introduction of Relational Algebra in DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
Python unittest - assertFalse() function - GeeksforGeeks

29 Aug, 2020
assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.
Syntax: assertFalse(testValue, message)
Parameters: assertFalse() accepts two parameters which are listed below with explanation:
testValue:  variable of a boolean type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest  class TestStringMethods(unittest.TestCase):    # test function     def test_negative(self):        testValue = True        # error message in case if test case got failed        message = "Test value is not false."        # assetFalse() to check test value as false        self.assertFalse( testValue, message)  if __name__ == '__main__':    unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "p1.py", line 11, in test_negative
    self.assertFalse( testValue, message)
AssertionError: True is not false : Test value is not false.

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)



Example 2: Positive Test case
Python3
# unit test caseimport unittest  class TestStringMethods(unittest.TestCase):    # test function     def test_positive(self):        testValue = False        # error message in case if test case got failed        message = "Test value is not false."        # assertFalse() to check test value as false        self.assertFalse( testValue, message)  if __name__ == '__main__':    unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK




Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Is JavaScript's eval() evil? - GeeksforGeeks

22 Jun, 2020
The eval() is an in-built JS function that evaluates arguments that are expressions and executes one or more statements given to it as arguments. 
Reason eval() consider evil: There are several problems possessed by the use of eval() and out of all performance and code injection are considered the most problematic. Performance- since script compiler cannot pre-compile eval(), it runs the compiler even when the code is compiled during run-time. Even though not much but this still degrades the performance.
It is Complicated- most cases in which eval() is used don’t even require it that badly. So, in cases like these an alternative approach is preferred more than eval(). Code injection- eval() runs string as a code and it is way more easier for hackers to get into privileged information just by the use of eval(). This is a big security threat when a program takes input from the user and is running on the client-side. This in-turn can go on to manipulate the original program itself.
Harder to debug- while debugging it requires double work.
Example:
HTML
<!DOCTYPE html><html><head>    <title></title></head><body>    <script type="text/javascript">        var a=eval("4+3");        document.write(a);    </script></body></html>
Output:
7
When  eval() not evil: For cases where you are running the program on your browser. Also, you need to be very careful not to pass any information that can give rise to code injection and manipulate the program in any way possible. It is generally preferred to use an alternate function in place of eval() if there is any function that can give out the same result as eval(). Closures, object-oriented techniques, functional techniques generally are capable of replacing eval(). For cases where this can’t be done and using eval() is the only way possible it is preferred to the passcode that will not manipulate the DOM in any way.eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client. Obviously you should always sanitize the input, as to have some control over what your code consumes.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python program to count number of vowels using sets in given string - GeeksforGeeks

18 Dec, 2019
Given a string, count the number of vowels present in given string using Sets.
Prerequisite: Sets in Python
Examples:
Input : GeeksforGeeks
Output : No. of vowels : 5

Input : Hello World
Output : No. of vowels :  3

Approach:1. Create a set of vowels using set() and initialize a count variable to 0.2. Traverse through the alphabets in the string and check if the letter in the string is present in set vowel.3. If it is present, the vowel count is incremented.
Below is the implementation of above approach:
# Python3 code to count vowel in # a string using set  # Function to count voweldef vowel_count(str):          # Initializing count variable to 0    count = 0          # Creating a set of vowels    vowel = set("aeiouAEIOU")          # Loop to traverse the alphabet    # in the given string    for alphabet in str:              # If alphabet is present        # in set vowel        if alphabet in vowel:            count = count + 1          print("No. of vowels :", count)      # Driver code str = "GeeksforGeeks"  # Function Callvowel_count(str)
Output:
No. of vowels : 5

shubham_singh
Python set-programs
Python string-programs
python-set
Python
Python Programs
Strings
python-set
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
CSS | rotate3d() Function - GeeksforGeeks

08 Aug, 2019
The rotate3d() function is an inbuilt function which is used to rotate an element around a fixed axis in 3D space.
Syntax:
rotate3d( x, y, z, angle )
Parameters: This function accepts four parameters as mentioned above and described below:
x: It holds a number denoting the x-coordinate. Its value lies between 0 to 1.
y: It holds a number denoting the y-coordinate. Its value lies between 0 to 1.
z: It holds a number denoting the z-coordinate. Its value lies between 0 to 1.
angle: It holds the angle of rotation. The positive angle represents a clockwise rotation and a negative angle represents a counter-clockwise rotation.
Below examples illustrate the rotate3d() function in CSS:
Example 1:
<!DOCTYPE html> <html> <head>     <title>CSS rotate3d() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .rotate3d_image {            transform: rotate3d(1, 1, 0, 60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotate3d() function</h2>    <br><br>          <img class="rotate3d_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body> </html>            
Output:
Example 2:
<!DOCTYPE html> <html> <head>     <title>CSS rotate3d() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .GFG {            font-size:35px;            font-weight:bold;            color:green;            transform: rotate3d(1, 1, 0, 60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotate3d() function</h2>    <br><br>          <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html>                     
Output:
Supported Browsers: The browsers supported by rotate3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Java ArrayList of Arrays - GeeksforGeeks

08 Oct, 2021
ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.
ArrayList<String[ ] > geeks = new ArrayList<String[ ] >();
Example:
Input :int array1[] = {1, 2, 3},
       int array2[] = {31, 22},
       int array3[] = {51, 12, 23}
Output: ArrayList of Arrays = {{1, 2, 3},{31, 22},{51, 12, 23}}
Approach: 
Create ArrayList object of String[] type, say, list.
Store arrays of string, say, names[], age[] and address[] into list object.
Print ArrayList of Array.
Below is the implementation of the above approach:
Java
// Java ArrayList of Arraysimport java.io.*;import java.util.*; class GFG {    public static void main(String[] args)    {        // create an ArrayList of String Array type        ArrayList<String[]> list = new ArrayList<String[]>();                 // create a string array called Names        String names[] = { "Rohan", "Ritik", "Prerit" };                 // create a string array called Age        String age[] = { "23", "20" };                 // create a string array called address        String address[] = { "Lucknow", "Delhi", "Jaipur" };                 // add the above arrays to ArrayList Object        list.add(names);        list.add(age);        list.add(address);                 // print arrays from ArrayList        for (String i[] : list) {            System.out.println(Arrays.toString(i));        }    }}
[Rohan, Ritik, Prerit]
[23, 20]
[Lucknow, Delhi, Jaipur]
varshagumber28
Java-ArrayList
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Get() method for dictionaries in Python

05 Oct, 2021
Python get() method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).
Syntax : Dict.get(key, default=None)
Parameters: 
key: The keyname of the item you want to return the value from
Value: (Optional) Value to be returned if the key is not found. The default value is None.
Returns: Returns the value of the item with the specified key.
Python
dic = {"A": 1, "B": 2}print(dic.get("A"))print(dic.get("C"))print(dic.get("C", "Not Found ! "))
Output: 
1
None
Not Found !
The get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present.
Python3
# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get()   # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))   # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is')   # printing resultprint("The nested safely accessed value is :  " + str(res))
Output:
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best
This article is contributed by Mayank Rawat. 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.
kumar_satyam
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Java program to check for prime and find next Prime in Java

Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example: 7 = 1 × 7
Following is the algorithm to find whether a number is prime or not −
Take integer variable A.
Take integer variable A.
Divide the variable A with (A-1 to 2).
Divide the variable A with (A-1 to 2).
If A is divisible by any value (A-1 to 2) it is not prime.
If A is divisible by any value (A-1 to 2) it is not prime.
Else it is prime.
Else it is prime.
Following Java program accepts an integer from the user, finds whether the given number is prime and, prints the next prime number.
import java.util.Scanner;
public class NextNumberisPrime {
   public static int isPrime(int num){
      int prime = 1;
      for(int i = 2; i < num; i++) {
         if((num % i) == 0) {
            prime = 0;
         }
      }
      return num;
   }
   public static int nextPrime(int num) {
      num++;
      for (int i = 2; i < num; i++) {
         if(num%i == 0) {
            num++;
            i=2;
         } else {
            continue;
         }
      }
      return num;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number ::");
      int num = sc.nextInt();
      int result = 0;
      int prime = isPrime(num);
      if (prime == 1) {
         System.out.println(num+" is a prime number");
      } else {
         System.out.println(num+" is not a prime number");
      }
      System.out.println("Next prime number is: "+nextPrime(num));
   }
}
Enter a number ::
25
25 is not a prime number
Next prime number is: 29
Python | Matrix creation of n*n

30 Dec, 2020
Many times while working with numbers in data science we come across the problem in which we need to work with data science we need to transform a number to a matrix of consecutive numbers and hence this problem has a good application. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionList comprehension can be used to accomplish this particular task by using the range function for each list that needs to be constructed consecutively.
# Python3 code to demonstrate# matrix creation of n * n# using list comprehension  # initializing NN = 4  # printing dimensionprint("The dimension : " + str(N))  # using list comprehension# matrix creation of n * nres = [list(range(1 + N * i, 1 + N * (i + 1)))                            for i in range(N)]  # print resultprint("The created matrix of N * N: " + str(res))
The dimension : 4
The created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

 
Method #2 : Using next() + itertools.count()The count function can be used start the count of numbers and next function does the task of creation of sublist consecutively. List comprehension handles the processing.
# Python3 code to demonstrate# matrix creation of n * n# using next() + itertools.count()import itertools  # initializing NN = 4  # printing dimensionprint("The dimension : " + str(N))  # using next() + itertools.count()# matrix creation of n * ntemp = itertools.count(1) res = [[next(temp) for i in range(N)] for i in range(N)]  # print resultprint("The created matrix of N * N: " + str(res))
The dimension : 4
The created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Python list-programs
Python matrix-program
python-list
Python
Python Programs
python-list
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to create an empty class in Python?

29 Dec, 2020
A class is a user-defined blueprint or prototype from which objects are created. Class can be considered as a user-defined data type. Generally, a class contains data members known as attributes of the class and member functions that are used to modify the attributes of the class. But have you ever wondered how to define an empty class i.e a class without members and member functions?
In Python, if we write something like the following, it would raise a SyntaxError.
# Incorrect empty class in # Python  class Geeks:
Output:
  File "gfg.py", line 5

                ^
SyntaxError: unexpected EOF while parsing

In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.
Example:
# Python program to demonstrate# empty class  class Geeks:    pass  # Driver's codeobj = Geeks()  print(obj)
Output:
<__main__.Geeks object at 0x02B4A340>

Python also allows us to set the attributes of an object of an empty class. We can also set different attributes for different objects. See the following example for better understanding.
# Python program to demonstrate# empty class    class Employee:    pass    # Driver's code# Object 1 detailsobj1 = Employee()obj1.name = 'Nikhil'obj1.office = 'GeeksforGeeks'  # Object 2 detailsobj2 = Employee()obj2.name = 'Abhinav'obj2.office = 'GeeksforGeeks'obj2.phone = 1234567889    # Printing detailsprint("obj1 Details:")print("Name:", obj1.name)print("Office:", obj1.office)print()  print("obj2 Details:")print("Name:", obj2.name)print("Office:", obj2.office)print("Phone:", obj2.phone)    # Uncommenting this print("Phone:", obj1.phone)# will raise an AttributeError
Output:
obj1 Details:
Name: Nikhil
Office: GeeksforGeeks

obj2 Details:
Name: Abhinav
Office: GeeksforGeeks
Phone: 1234567889

Traceback (most recent call last):
  File "gfg.py", line 34, in 
    print("Phone:", obj1.phone)
AttributeError: 'Employee' object has no attribute 'phone'

Python Oops-programs
Python-OOP
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
filepath.Dir() Function in Golang With Examples

10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Dir() function in Go language used to return all the elements of the specified path except the last element. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns “.”. If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
Syntax:
func Dir(path string) string

Here, ‘path’ is the specified path.
Return Value: It returns all the elements of the specified path except the last element.
Example 1:
// Golang program to illustrate the usage of// filepath.Dir() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Dir() function    fmt.Println(filepath.Dir("/Geeks/GFG/gfg.org"))    fmt.Println(filepath.Dir("/Geeks/GFG/gfg"))    fmt.Println(filepath.Dir("/Geeks/GFG/gfg/"))    fmt.Println(filepath.Dir("/GFG/gfg///"))    fmt.Println(filepath.Dir("/gfg.org"))    fmt.Println(filepath.Dir("gfg.org"))}
Output:
/Geeks/GFG
/Geeks/GFG
/Geeks/GFG/gfg
/GFG/gfg
/
.

Example 2:
// Golang program to illustrate the usage of// filepath.Dir() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Dir() function    fmt.Println(filepath.Dir(""))    fmt.Println(filepath.Dir("."))    fmt.Println(filepath.Dir("/"))    fmt.Println(filepath.Dir("//"))    fmt.Println(filepath.Dir("../gfg.org"))  }
Output:
.
.
/
/
..

Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to plot two Seaborn lmplots side-by-side (Matplotlib)?

To plot two graphs side-by-side in Seaborn, we can take the following steps −
To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7).
To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7).
Create a data frame with keys, col1 and col2, using Pandas.
Create a data frame with keys, col1 and col2, using Pandas.
Use countplot() to show the counts of observations in each categorical bin using bars.
Use countplot() to show the counts of observations in each categorical bin using bars.
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
f, axes = plt.subplots(1, 2)
df = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5)))
sns.countplot(df.col1, x='col1', color="red", ax=axes[0])
sns.countplot(df.col2, x="col2", color="green", ax=axes[1])
plt.show()
matplotlib.pyplot.imread() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The imread() function in pyplot module of matplotlib library is used to read an image from a file into an array.
Syntax: matplotlib.pyplot.imread(fname, format=None)
Parameters: This method accepts the following parameters.
fname : This parameter is the image file to read.
format: This parameter is the image file format assumed for reading the data.
Returns: This method return the following.
imagedata : This returns the image data
Below examples illustrate the matplotlib.pyplot.imread() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt  with cbook.get_sample_data('loggf.png') as image_file:    image = plt.imread(image_file)  fig, ax = plt.subplots()ax.imshow(image)ax.axis('off')  plt.title('matplotlib.pyplot.imread() function Example',                                      fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt    with cbook.get_sample_data('loggf.png') as file:    im = image.imread(file)  fig, ax = plt.subplots()  ax.plot(np.cos(10 * np.linspace(0, 1)), '-o', ms = 15,                            alpha = 0.6, mfc ='green')  ax.grid()fig.figimage(im, 10, 10, zorder = 3, alpha =.5)  plt.title('matplotlib.pyplot.imread() function Example',                                      fontweight ="bold")plt.show()
Output:
Python-matplotlib
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
How to Create Dashed Underline under TextView in Android?

06 Jun, 2021
In this article, we will explain how to create a dashed underline below a text view in android. A sample image is shown below to give an idea of what we are going to build.
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. 
Step 2: Working with dashed_underline.xml
Go to res > drawable > new > drawable resource file and create a new file and name it “dashed_underline.xml” and define all properties of the dashed line that we need. Later we will add this as the background of TextView. Below is the code for dashed_underline.xml comments is added for a better understanding of the code.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" ><!--Create a layer list and add item of shape "Rectangle to it"-->    <item        android:left="-5dp"        android:right="-5dp"        android:top="-5dp">        <shape            android:shape="rectangle">            <!--Give the dashed lines their property                 like color, width, and dashGap-->            <stroke                android:color="@color/black"                android:dashWidth="2dp"                android:dashGap="3dp"                android:width="1dp"/>        </shape>    </item></layer-list>
Step 3: Working with the activity_main.xml
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a TextView that we want to be underlined.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!--Create a Text View and inside the         background tag add the dashed_underline        that we created earlier-->    <TextView        android:id="@+id/tv_dashed"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@drawable/dashed_underline"        android:text="Welcome to GFG!"        android:textColor="@color/black"        android:textSize="24sp"        android:textStyle="bold"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.