code-rag-bench/online-tutorials huggingface dataset:
Scala String toLowerCase() method with example

29 Oct, 2019
The toLowerCase() method is utilized to convert all the characters in the String into the lowercase.
Method Definition: String toLowerCase()
Return Type: It returns the resultant string after converting each character of the string into the lowercase.
Example: 1#
// Scala program of toLowerCase()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying toLowerCase method        val result = "NIDHI".toLowerCase()                  // Displays output        println(result)          }} 
nidhi

Example: 2#
// Scala program of toLowerCase()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying toLowerCase method        val result = "gEEKs".toLowerCase()                  // Displays output        println(result)          }} 
geeks

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
How to Install Scala with VSCode?
Scala | Option
Hello World in Scala
Scala | Traits
Scala ListBuffer
Scala Sequence
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Introduction to Scala
Scala | Functions - Basics
AngularJS - Upload File

We are providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>
   
   <body ng-app = "myApp">
	
      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>
      
      <script>
         var myApp = angular.module('myApp', []);
         
         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;
                  
                  element.bind('change', function() {
                     scope.$apply(function() {
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);
         myApp.service('fileUpload', ['$https:', function ($https:) {
            this.uploadFileToUrl = function(file, uploadUrl) {
               var fd = new FormData();
               fd.append('file', file);
            
               $https:.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })
               .success(function() {
               })
               .error(function() {
               });
            }
         }]);
         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload) {
            $scope.uploadFile = function() {
               
               var file = $scope.myFile;
               console.log('file is ' );
               console.dir(file);
               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);
      </script>
      
   </body>
</html>
Open above saved code file in a web browser. See the result.
How to open two files together in Python?

24 Jan, 2021
Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened with the open() method supported in Python 2.7 version or greater. The following syntax is used to open multiple files : 
with open(file_1) as f1, open(file_2) as f2
file_1: specifies the path of the first file
file_2: specifies the path of the second file
Different names are provided to different files. The files can be opened in read, write or append modes respectively. The operation is performed synchronously and both the files are opened at the same time. By default, the files are opened to support read operations. 
The following text files are used in the later sections of codes : 
Steps used to open multiple files together in Python :
Both the files are opened with open() method using different names for each
The contents of the files can be accessed using readline() method.
Different read/write operations can be performed over the contents of these files.
Example 1:
Python3
# opening both the files in reading modeswith open("file1.txt") as f1, open("file2.txt") as f2:      # reading f1 contents  line1 = f1.readline()      # reading f2 contents  line2 = f2.readline()      # printing contents of f1 followed by f2   print(line1, line2)
Output :
Geeksforgeeks is a complete portal. Try coding here!
Example 2:
The following code indicates storing the contents of one file into another. 
Python3
# opening file1 in reading mode and file2 in writing modewith open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:      # writing the contents of file1 into file2  f2.write(f1.read())
Output: The contents of file2 after this operation are as follows : 
Picked
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to get the number of pages in a PDF document using PHP ?

29 Jul, 2020
PHP offers inbuilt functions and extensions that can be used to count the number of pages in a document with .pdf extension. There are numerous ways by which this can be done. Following are the methods used to count the pages in a pdf document:
Method 1: Using ImageMagic extension: The extension offered by PHP is ImageMagic which is able to understand the pdf document. The command used for the same is “identify” command. So the complete PHP function dedicated to the required purpose is Imagick::identifyImage().
Method 2: Using TCPDI function: Another way to do this is by using the TCPDI function. It does not use any PHP library for performing this task. The following line of code can be used.
$pageCount = (new TCPDI())->setSourceData((string)file_get_contents($fileName));
Method 3: Using pdfinfo: For Linux users, there is a faster way to count the number of pages in a pdf document than “identity” function. The command given below can be used for the same. Before executing this command, pdfinfo needs to be installed. This command works very fast when the number of pages in the pdf document is too large. For Windows users, the pdfinfo is available as pdfinfo.exe. Here is the command:
exec(‘/usr/bin/pdfinfo ‘.$tmpfname.’ | awk \’/Pages/ {print $2}\”, $output);
Method 4: Using pdf as text file: Now, let us see the code in PHP which will tell us the number of pages in a pdf document. In this code, we have created a function “count” containing the logic. Also, in the variable “path”, the path of the pdf whose number of pages are to be counted is written. Make sure, you write the path correctly.
<?php $path = 'pdf/GFG.pdf';$totalPages = count($path);    echo $totoalPages;    function count($path) {  $pdf = file_get_contents($path);  $number = preg_match_all("/\/Page\W/", $pdf, $dummy);  return $number;}  ?>
Output:
4
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
Python slice() function

30 Sep, 2021
Python slice() function returns a slice object. 
A sequence of objects of any type(string, bytes, tuple, list or range) or the object which implements __getitem__() and __len__() method then this object can be sliced using slice() method. 
Syntax: 
slice(stop)
slice(start, stop, step)
Parameters: 
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.  
Note: If only one parameter is passed then start and step is considered to be None.
Python3
# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(3)s2 = slice(1, 5, 2) print("String slicing")print(String[s1])print(String[s2])
Output:
String slicing
Gee
ek
Python3
# Python program to demonstrate# slice() operator # List slicingL = [1, 2, 3, 4, 5]s1 = slice(3)s2 = slice(1, 5, 2)print("List slicing")print(L[s1])print(L[s2])
Output:
List slicing
[1, 2, 3]
[2, 4]
Python3
# Python program to demonstrate# slice() operator # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(3)s2 = slice(1, 5, 2)print("\nTuple slicing")print(T[s1])print(T[s2])
Output:
Tuple slicing
(1, 2, 3)
(2, 4)
In Python, negative sequence indexes represent positions from the end of the array. slice() function can also have negative values. In that case, the iteration will be performed backward i.e from end to start.
Python3
# Python program to demonstrate# slice() operator # String slicingString = 'GeeksforGeeks's1 = slice(-3)s2 = slice(-1, -5, -2)print("String slicing")print(String[s1])print(String[s2]) # List slicingL = [1, 2, 3, 4, 5]s1 = slice(-3)s2 = slice(-1, -5, -2)print("\nList slicing")print(L[s1])print(L[s2]) # Tuple slicingT = (1, 2, 3, 4, 5)s1 = slice(-3)s2 = slice(-1, -5, -2)print("\nTuple slicing")print(T[s1])print(T[s2])
Output: 
String slicing
GeeksforGe
se

List slicing
[1, 2]
[5, 3]

Tuple slicing
(1, 2)
(5, 3)
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Project Idea | Third -Eye : Aid for Blind

29 Jun, 2018
Project Title: Third Eye – Aid For Blind.
Introduction:This project aims to develop a complete portable aid(Raspberry Pi) for blind pedestrians and deal with problems in existing systems efficiently. The system designed will detect an object or obstacleusing ultrasonic sensors and gives audio instructions for guidance. It also gives informationabout people looking or waving to them using face recognition.
Assumption and Constraints
Maximum range of an ultrasonic sensor is 4m.
Model won’t be able to work accurately in the crowded area.
GPS is a satellite-based radio navigation system, so it can track predefined locations only.
Raspberry pi camera module has 5-megapixel resolution and it is capable of only taking video and pictures not sound.
Object detection and face detection, recognition has limitation over accuracy.
Conceptual framework:Features Provided:
It can detect objects with the help of Ultrasonic sensor.It can detect the name of the object with the help of YOLO algorithm.It can detect the face with the help Raspberry pi camera use with face detection and recognition process.It can tell the location of the person with the help of gps used.
It can detect objects with the help of Ultrasonic sensor.
It can detect the name of the object with the help of YOLO algorithm.
It can detect the face with the help Raspberry pi camera use with face detection and recognition process.
It can tell the location of the person with the help of gps used.
Diagrams:  Relevant diagrams like ER-diagram, UML diagrams, etc
Output of Face Detection:
Output of YOLO algorithm:
Use Case diagram:
System Architecture:
Activity Diagram:
Algorithms
YOLO (You Only Look Once) algorithm use to detect object in background in real time.
Face recognition using OpenCV and haar-cascades classifiers.
Tensorflow used.
Tools Used:
Used Raspberry pi to make it portable.
Use train model to detect objects.
Python Ide.
Linux terminal.
Application:The World Health Organization (WHO) reported that there are 285 million visually-impaired people worldwide.Among these individuals, there are 39 million who are totally blind. The product developed is light in weight, compact hence does not cause fatigue to the user. So this helps the blind person to be self-dependent till particular extent by giving info of surrounding objects, person, and help in keeping the track of current location.
Team :
Chandan VanwariCharvi JainAkhil Bansal
Note: This project idea is contributed for ProGeek Cup 2.0- A project competition by GeeksforGeeks.
ProGeek 2.0
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to enable row selection in a JTable with Java

To enable row selection, use the setRowSelectionAllowed () method and set it to TRUE −
table.setCell setRowSelectionAllowed(true);
The following is an example to enable row selection in a JTable −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.orange);
      table.setRowSelectionAllowed(true);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
The output is as follows. Here, we have selected a row. We can select a row now since setRowSelectionAllowed() is set TRUE above −
How to parse an URL in JavaScript?

It is very simple to parse an URL in javascript by using DOM method rather than Regular expressions. If regular expressions are used then code will be much more complicated. In DOM method just a function call will return the parsed URL. 
In the following example, initially a function is created and then an anchor tag "a" is created inside it using a DOM method. Later on the provided URL was assigned to the anchor tag using href. Now, when function returns the parts of the URL, it tries to return the parsed parts as shown in the output. Since the url is parsed, JSON.stringify() method is used so as to display the output.
Live Demo
<html>
<body>
<script>
   function URL(url) {
      var urlParser = document.createElement('a');
      urlParser.href = url;
      return {
         protocol: urlParser.protocol,
         host: urlParser.host,
         hostname: urlParser.hostname,
         port: urlParser.port,
         pathname: urlParser.pathname,
         search: urlParser.search,
         hash: urlParser.hash
      };
   }
   document.write(JSON.stringify(URL("https://www.youtube.com/watch?v=tNJJSrfKYwQ")));
</script>
</body>
</html>
{"protocol":"https:","host":"www.youtube.com","hostname":"www.youtube.com","port":"","pathname":"/watch","search":"?v=tNJJSrfKYwQ","hash":""}
Initialize HashSet in Java

A set is a collection which does not allows duplicate values. HashSet is an implementation of a Set. Following are the ways in which we can initialize a HashSet in Java.
Using constructor − Pass a collection to Constructor to initialize an HashSet.
Using constructor − Pass a collection to Constructor to initialize an HashSet.
Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet.
Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet.
Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set.
Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set.
Using add() − Using add(element) method of Set.
Using add() − Using add(element) method of Set.
Following is an example of using above ways.
Infinity
Now consider the following code snippet.
 Live Demo
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

      List<Integer> list = Arrays.asList(1,2,3,4,5,6);
      //Scenario 1
      Set<Integer> set1 = new HashSet<>(list);
      System.out.println(set1);

      //Scenario 2
      Set<Integer> set2 = new HashSet<>(list);
      Collections.addAll(set2, 1,2,3,4,5,6);
      System.out.println(set2);

      //Scenario 3
      Set<Integer> set3 = Collections.unmodifiableSet(set2);
      System.out.println(set3);

      //Scenario 4
      Set<Integer> set4 = new HashSet<>();
      set4.add(1);set4.add(2);set4.add(3);
      set4.add(4);set4.add(5);set4.add(6);
      System.out.println(set4);
   }
}
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
Will a finally block execute after a return statement in a method in Java?

Yes, the finally block will be executed even after a return statement in a method. 
The finally block will always execute even an exception occurred or not in Java. If we call the System.exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crash, power failure, software crash and etc. Other than these conditions, the finally block will be always executed.
public class FinallyBlockAfterReturnTest {
   public static void main(String[] args) {
      System.out.println(count());
   }
   public static int count() {
      try {
         return 1;
      } catch(Exception e) {
         return 2;
      } finally {
         System.out.println("Finally block will execute even after a return statement in a method");
      }
   }
}
Finally block will always excute even after a return statement in a method
1
Clearing a Dictionary using Javascript

We'll implement a clear() function that simply clears the contents of the container. For example, 
clear() {
   this.container = {}
}
You can test this using − 
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
 
myMap.display();
myMap.clear();
myMap.display();
This will give the output −
{ key1: 'value1', key2: 'value2' }
You can use the clear method in the same way in ES6 maps as well. For example,
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);

console.log(myMap)
myMap.clear();
console.log(myMap)
This will give the output −
Map { 'key1' => 'value1', 'key2' => 'value2' }
Map {}
kill command in Linux with Examples - GeeksforGeeks

22 May, 2019
kill command in Linux (located in /bin/kill), is a built-in command which is used to terminate processes manually. kill command sends a signal to a process which terminates the process. If the user doesn’t specify any signal which is to be sent along with kill command then default TERM signal is sent that terminates the process.
1. kill -l :To display all the available signals you can use below command option:
Syntax:
$kill -l

Signals can be specified in three ways:
By number (e.g. -5)
With SIG prefix (e.g. -SIGkill)
Without SIG prefix (e.g. -kill)
Note:
Negative PID values are used to indicate the process group ID. If you pass a process group ID then all the process within that group will receive the signal.
A PID of -1 is very special as it indicates all the processes except kill and init, which is the parent process of all processes on the system.
To display a list of running processes use the command ps and this will show you running processes with their PID number. To specify which process should receive the kill signal we need to provide the PID.Syntax:$ps

Syntax:
$ps

2. kill pid : To show how to use a PID with the kill command.
Syntax:
$kill pid

3. kill -s : To show how to send signal to processes.
Syntax:
kill {-signal | -s signal} pid 

4. kill -L :This command is used to list available signals in a table format.
Syntax:
kill {-l | --list[=signal] | -L | --table} 

linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
Tail command in Linux with examples
Compiling with g++
How to perform scrolling action on page in Selenium?

We can perform the following actions with respect to scrolling in Selenium −
The scrolling down to a specific pixel.
JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down by 1500 pixel with coordinates 0 and 1500 in x, y axes
j.executeScript("window.scrollBy(0,1500)");
The scrolling down to the bottom of the page.
JavascriptExecutor j = (JavascriptExecutor) driver;
// scroll down the bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
For vertical scroll down till the element is visible.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollDownVisible {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      JavascriptExecutor js = (JavascriptExecutor) driver;
      WebElement terms = driver.findElement(By.linkText("Terms of use”));
      // scroll down the web element for viewing
      js.executeScript("arguments[0].scrollIntoView();",terms);
      driver.close();
   }
}
For horizontal scroll on page.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class HScrollDown {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      JavascriptExecutor js = (JavascriptExecutor) driver;
      WebElement meets = driver.findElement(By.linkText("NetMeeting”));
      // scroll down the web element for viewing
      js.executeScript("arguments[0].scrollIntoView();", meets);
      driver.close();
   }
}
Alternate range slicing in list (Python)

Slicing is a very common technique for analyzing data from a given list in Python. But for our analysis sometimes we need to create slices of a list for a specific range of values. For example we need to print 4 elements by skipping every 4 elements from the list. In this article we will see this concept of range slicing in Python.
We create a for loop to go through the entire length of the list but choose only the elements that satisfy the divisibility test. In the divisibility test we check for the value of the remainder for the kth element in the list. If the remainder is greater than or equal to the range value, we accept the element otherwise we do not.
 Live Demo
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]
print("The given list: ",range_slicing)

# Range Value
s = 4
# Using range and len
result = [range_slicing[k] for k in range(len(range_slicing))
if k % (s * 2) >= s]

print("\nThe list after range slicing: ",result)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]
The list after range slicing: [20, 24, 29, 36, 56, 70, 73, 79]
We apply the similar logic as in previous approach but instead of using range() and len() we simply apply enumerate(). Please note the last element in the list appears in the result because it satisfies the divisibility condition.
 Live Demo
range_slicing = [6,9,11,15,20,24,29,36,39,43,47,52,56,70,73,79]
print("The given list: ",range_slicing)
# Range value
s2= 5

# Using Enumerate
result_2 = [val for m, val in enumerate(range_slicing)
if m % (s2 * 2) >= s2]

print("\nThe list after range slicing: ",result_2)
Running the above code gives us the following result:
The given list: [6, 9, 11, 15, 20, 24, 29, 36, 39, 43, 47, 52, 56, 70, 73, 79]
The list after range slicing: [24, 29, 36, 39, 43, 79]
codecs.encode() in Python - GeeksforGeeks

26 Mar, 2020
With the help of codecs.encode() method, we can encode the string into the binary form .
Syntax : codecs.encode(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using codecs.encode() method, we are able to get the encoded string which can be in binary form by using this method.
# import codecsimport codecs  s = 'GeeksForGeeks'# Using codecs.encode() methodgfg = codecs.encode(s)  print(gfg)
Output :
b’GeeksForGeeks’
Example #2 :
# import codecsimport codecs  s = 'I love python.'# Using codecs.encode() methodgfg = codecs.encode(s)  print(gfg)
Output :
b’I love python.’
Python codecs-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Groovy - floor()

The method floor gives the largest integer that is less than or equal to the argument.
double floor(double d) 
double floor(float f)

Parameters − A double or float primitive data type.
Return Value − This method Returns the largest integer that is less than or equal to the argument. Returned as a double.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      double a = -100.675; 
      float b = -90; 
		
      System.out.println(Math.floor(a)); 
      System.out.println(Math.floor(b)); 
   } 
}
When we run the above program, we will get the following result −
-101.0 
-90.0 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Swing Examples - Show Alert message Dialog

Following example showcase how to show a simple message alert with Ok button in swing based application.
We are using the following APIs.
JOptionPane − To create a standard dialog box.
JOptionPane − To create a standard dialog box.
JOptionPane.showMessageDialog() − To show the simple alert message.
JOptionPane.showMessageDialog() − To show the simple alert message.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      JButton button = new JButton("Click Me!");
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, "Welcome to Swing!");
         }
      });

      panel.add(button);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}
 Print
 Add Notes
 Bookmark this page
Clear/Set a specific bit of a number in Arduino

When you delve into advanced firmware, you deal with a lot of registers, whose specific bits need to be set or cleared depending on your use case. Arduino has inbuild functions to do that.
bitSet(x, index)
and,
bitClear(x, index)
Where x is the number whose bit has to be set/ cleared and index is the position of the bit (0 for least significant or right-most bit). This function makes changes in the number x in place, and also returns the updated value of x.
Note that setting a bit means setting its value to 1, and clearing it means setting its value to 0.
The following example illustrates the use of these functions −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   int x = 6;

   Serial.println(x);
   bitSet(x,0);
   Serial.println(x);
   bitClear(x,2);
   Serial.println(x);
   bitClear(x,3);
   Serial.println(x);
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, we start off with the number 6 (0b0110).
We then set its 0th bit, yielding (0b0111), which corresponds to 7.
Then, we clear its 2nd bit, yielding (0b0011), which corresponds to 3.
We then clear its 3rd bit, which was already 0. Thus, we again get (0b0011), which corresponds to 3.
The Serial Monitor output shows these numbers in the exact sequence we just described.
Elixir - Structs

Structs are extensions built on top of maps that provide compile-time checks and default values.
To define a struct, the defstruct construct is used −
defmodule User do
   defstruct name: "John", age: 27
end
The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they are defined in. In the example given above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps −
new_john = %User{})
ayush = %User{name: "Ayush", age: 20}
megan = %User{name: "Megan"})
The above code will generate three different structs with values −
%User{age: 27, name: "John"}
%User{age: 20, name: "Ayush"}
%User{age: 27, name: "Megan"}

Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. So you cannot define your own fields once you have created the struct in the module.
When we discussed maps, we showed how we can access and update the fields of a map. The same techniques (and the same syntax) apply to structs as well. For example, if we want to update the user we created in the earlier example, then −
defmodule User do
   defstruct name: "John", age: 27
end
john = %User{}
#john right now is: %User{age: 27, name: "John"}

#To access name and age of John, 
IO.puts(john.name)
IO.puts(john.age)
When the above program is run, it produces the following result −
John
27

To update a value in a struct, we will again use the same procedure that we used in the map chapter,
meg = %{john | name: "Meg"}
Structs can also be used in pattern matching, both for matching on the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value.

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
Python | Convert byteString key:value pair of dictionary to String - GeeksforGeeks

11 Feb, 2019
Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string.
Examples:
Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' }
Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'}

Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' }
Output: {'Key1':'Geeks', 'Key2':'For', 'Key3':'Geek' }

 Method #1: By dictionary comprehension
# Python Code to convert ByteString key:value # pair of dictionary to String.  # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'}  # Convertingx = { y.decode('ascii'): x.get(y).decode('ascii') for y in x.keys() }  # printing converted dictionaryprint(x)
{'Name': 'Paras', 'EmplId': '12345', 'Company': 'Cyware'}

 Method #2: By iterating key and values
# Python Code to convert ByteString key:value # pair of dictionary to String.  # Initialising dictionary x = {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware'}  # Initialising empty dictionary y = {}  # Convertingfor key, value in x.items():    y[key.decode("utf-8")] = value.decode("utf-8")  # printing converted dictionaryprint(y)
{'Company': 'Cyware', 'Name': 'Paras', 'EmplId': '12345'}

Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How can I remove the decimal part of JavaScript number?

To remove the decimal part from a number, use the JavaScript Math.trunc() method. The method returns the integer part of a number by removing the decimal part.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Value:</p>
      <script>
         var myFloat = 4.5;
         var myTrunc = Math.trunc( myFloat );
         document.write(myTrunc+ " ");
      </script>
   </body>
</html>
Value:
4
Form widget in Django

In this article, we will see how to use widgets in a Django form. Widgets can be quiet helpful to make the frontend better. Widgets are html elements that are rendered from Django form, textarea, input, password input, etc., all are widgets.
First let's create a Django project and an app. I created the project with the name "tutorial14" and app with the name "djangoFormWidget".
Add app in settings.py and include app's URL in project urls.py.
Make every basic files and folders like Templates, home.html, forms.py.
In app's urls.py −
from django.urls import path,include
from . import views
urlpatterns = [
   path('',views.home,name="home")
]
It will create a basic URL for rendering view.
In views.py −
from django.shortcuts import render
from .forms import CommentForm

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def home(request):
   if request.method=='POST':
      form=CommentForm(request.POST)
      if form.is_valid():
         form.save()
   commentform=CommentForm()
   return render(request,'home.html',{"commentform":commentform})
Here, we imported our form and handled its POST and GET requests.
In POST, we save the data and in GET, we send the form to the frontend.
In models.py −
from django.db import models

# Create your models here.
class CommentModel(models.Model):
   comment=models.CharField(max_length=500)
Here we created a model which we will use in our form. We need this model to use the form.
In home.html −
<!DOCTYPE html>
<html>
   <head>
      <title>TUT</title>
   </head>
   <body>
      {% for fm in commentform %}
      <form method="post">
         {%csrf_token%}

         {{fm.errors}}<br>
         {{fm.label}}:{{fm}}<br>
         {%endfor%}
            <button type="submit">Submit</button>
      </form>
   </body>
</html>
It is a simple frontend where we render our form.
In forms.py −
from django import forms
from .models import CommentModel
class CommentForm(forms.Form):
   comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute.

def save(self):
   data=self.data
   modelRef=CommentModel(comment=data['comment'])
   modelRef.save()
It is where we make our form. We used the built-in Django form widget
to render a textarea in the form.
How to Generate Newman Reports on Jenkins using Postman?

We can generate Newman reports on Jenkins. The reports obtained from Jenkins are a pictorial and organized representation of test execution results. These reports can also be shared with all the stakeholders of the project.
Jenkins reports can be generated in several formats and can be controlled by adding different flags in the build commands. Also, it is necessary to specify the path where the reports shall be saved in build commands.
The steps to generate Newman reports on Jenkins are listed below −
As a prerequisite, Jenkins should be configured in the system. The details available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Also, we should have a Collection with a minimum one request along with the Newman installed in the system.
Step 1 − Click on the arrow to the right of the Collection name. Next, click the Share button.
Step 2 − SHARE COLLECTION1 window opens up. Move to the Get public link tab and copy the link that has been marked in the below image.
Step 3 − Open Jenkins and move to the Jenkins Job below the Build section. Add the below command to generate CLI and JUNIT reports −
newman run "<link copied in Step2> " --reporters cli, junit
Step 4 − To specify the path where the Newman report is to be saved, we should add the command.
newman run "<link in Step2>" --reporters cli,junit --reporter-junit-export
"report/newmanreport.xml"
Here, report/newmanreport.xml is the path where the report shall be saved. If that directory does not exist, the report gets created by default within the Jenkins Workspace directory.
How to use case-insensitive switch-case in JavaScript?

To use case-insensitive switch-case in JavaScript, make the input all upper or all lowercase.
You can try to run the following code to learn how to use a case-insensitive switch:
<!DOCTYPE html>
<html>
   <body>
      <h3>JavaScript Strings</h3>
      <p id="test"></p>
      <script>
         var str = "amit";
         str = str.toUpperCase();
         switch (str) {
            case 'AMIT': document.write("The name is AMIT <br>");
            break;
            case 'JOHN': document.write("The name is JOHN <br>");
            break;
            default: document.write("Unknown name<br>")
         }
         document.write("Exiting switch block");
      </script>
   </body>
</html>
Replacing array of object property name in JavaScript

Following is the code to replace array of object property name in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Replacing array of object property name</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to change the property name of an object in array</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   var person = [
      { name: "Rohan Sharma", age: 16 },
      { name: "Vinit Mehta", age: 18 },
   ];
   person = person.map((item) => {
      return {
         fullName: item.name,
         age: item.age,
      };
   });
   BtnEle.addEventListener("click", () => {
      person.forEach((item) => {
         resEle.innerHTML += "fullName = " + item.fullName + " : Age = " + item.age + "";
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
How can we use WHERE clause with MySQL INSERT INTO command?

We can use conditional insert i.e. WHERE clause with INSERT INTO command in the case of new row insertion. It can be done with following ways −
In this case, we insert the value from dummy table along with some conditions. The syntax can be as follows −
INSERT INTO table_name(column1,column2,column3,...) Select value1,value2,value3,... From dual WHERE [conditional predicate];
mysql> Create table testing(id int, item_name varchar(10));
Query OK, 0 rows affected (0.15 sec)

mysql> Insert into testing (id,item_name)Select 1,'Book' From Dual Where 1=1;
Query OK, 1 row affected (0.11 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+------+-----------+
| id   | item_name |
+------+-----------+
| 1    | Book      |
+------+-----------+

1 row in set (0.00 sec)
In the example above, we have created a table ‘testing’ and for inserting rows into it we have used dummy table dual with a condition. If the condition is true MySQL insert the row into table otherwise not.
If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement.
mysql> Insert into dummy1(id,name)select id, name from dummy Where id =1;
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> select * from dummy;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
| 2    | Aarav |
+------+--------+

2 rows in set (0.00 sec)

mysql> select * from dummy1;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
+------+--------+

1 row in set (0.00 sec)
Here in the example above, we have inserted the values in table ‘dummy1’, having the same structure as table ‘dummy’, with a condition to insert only that row where ‘id = 1’.
How do you make a button that adds text in HTML <input>?

Let’s say the following is our HTML button −
<button id="clickButton">Click the button to add the input into the belowText Box</button>
Use document.getElementById() to add a text in <input> on button click. Following is the code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button id="clickButton">Click the button to add the input into the
below Text Box</button>
<br/><br />
<input id="readTheInput" />
<script>
   document.getElementById("clickButton").addEventListener("click", () =>{
      document.getElementById("readTheInput").value += "JavaScript";
   });
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Here, I am going to click the button two times. This will produce the following output −
Search a 2D Matrix II in Python

Suppose we have one m x n matrix. We have to write an efficient algorithm that searches for a value in that matrix. This matrix has the following properties −
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
So if the matrix is like −
If target is 5, then return true, if target is 20, then return false
To solve this, we will follow these steps −
len := number of columns, c1 := 0, c2 := len – 1
while trueif matrix[c1, c2] = target, then return trueelse if matrix[c1, c2] > target, then c2 := c2 – 1, continuec1 := c1 + 1if c1 >= row count or c2 < 0, then return falsereturn false
if matrix[c1, c2] = target, then return true
else if matrix[c1, c2] > target, then c2 := c2 – 1, continue
c1 := c1 + 1
if c1 >= row count or c2 < 0, then return false
return false
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def searchMatrix(self, matrix, target):
      try:
         length = len(matrix[0])
         counter1, counter2 = 0, length-1
         while True:
            if matrix[counter1][counter2] == target:
               return True
            elif matrix[counter1][counter2]>target:
               counter2-=1
               continue
            counter1 = counter1 + 1
            if counter1 >= len(matrix) or counter2<0:
               return False
         except:
            return False
ob1 = Solution()
print(ob1.searchMatrix([[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], 5))
[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
5
True
Run a Python program from PHP

In PHP, the ‘shell_exec’ function can be used. It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all.
Below is a code demonstration of the same −
<?php
   $command_exec = escapeshellcmd('path-to-.py-file');
   $str_output = shell_exec($command_exec);
   echo $str_output;
?>
The right privileges need to be given so that the python script is successfully executed.
Note − While working on a Unix type of platform, PHP code is executed as a web user. Hence, the web user should be given the necessary rights to the directories and sub-directories.