code-rag-bench/online-tutorials huggingface dataset:
IPython - Running and Editing Python Script

In this chapter, let us understand how to run and edit a Python script.
You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.
In [1]: run hello.py
Hello IPython

IPython also provides edit magic command. It invokes default editor of the operating system. You can open it through Windows Notepad editor and the script can be edited. Once you close it after saving its input, the output of modified script will be displayed.
In [2]: edit hello.py
Editing... done. Executing edited code...
Hello IPython
welcome to interactive computing

Note that hello.py initially contained only one statement and after editing one more statement was added. If no file name is given to edit command, a temporary file is created. Observe the following code that shows the same.
In [7]: edit
IPython will make a temporary file named:
C:\Users\acer\AppData\Local\Temp\ipython_edit_4aa4vx8f\ipython_edit_t7i6s_er.py
Editing... done. Executing edited code...
magic of IPython
Out[7]: 'print ("magic of IPython")'


    22 Lectures 
     49 mins

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
SQLSERVER Tryit Editor v1.0

Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Next.js - API MiddleWares

API Routes in Next.JS have built-in middlewares which helps in parsing the incoming request.
 Following are the middlewares
req.cookies − cookies object contains the cookies sent by the request. Default value is {}.
req.cookies − cookies object contains the cookies sent by the request. Default value is {}.
req.query − query object contains the query string. Default value is {}.
req.query − query object contains the query string. Default value is {}.
req.body − query object contains the request body parsed using 'content-type'. Default value is null.
req.body − query object contains the request body parsed using 'content-type'. Default value is null.
Let's create an example to demonstrate the same.
In this example, we are going to update an user.js in pages/api directory.
Let's update the nextjs project used in API Routes chapter.
Create user.js file in pages/api directory as following.
export default (req, res) => {
   res.statusCode = 200
   res.setHeader('Content-Type', 'application/json')
   res.end(JSON.stringify({ query: req.query }))
}
Run the following command to start the server −.
npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
event - build page: /api/user
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

Open http://localhost:3000/api/user?counter=1 in a browser and you will see the following output.
{"query":{"counter":"1"}}

 Print
 Add Notes
 Bookmark this page
DAX Date & Time - MONTH function

Returns the month as a number from 1 (January) to 12 (December).
MONTH (<datetime>) 

datetime
A date in datetime or text format.
An integer number from 1 to 12.
DAX uses datetime format when working with dates. Dates stored in other formats are converted implicitly.
You can enter the date used as a parameter to the MONTH function in any of the following ways −
By typing an accepted datetime format.
By providing a reference to a column that contains dates.
By using an expression that returns a date.
By using a text representation for a date.
DAX MONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,
If the current date/time settings represent dates in the format of Month/Day/Year, then the string "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 1.
If the current date/time settings represent dates in the format of Month/Day/Year, then the string "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016 and the function returns 1.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 8.
If the text representation of the date cannot be correctly converted to a datetime value, the function returns an error.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016, and the function returns 8.
If the text representation of the date cannot be correctly converted to a datetime value, the function returns an error.
= MONTH ("April 5, 2016") returns 4. 
= MONTH ("March 2, 2016 3:45 PM”) returns 3. 
= MONTH (TODAY ()) returns 12 if TODAY () returns 12/16/2016 12:00:00 AM. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: Nesting counters
How to set scrolltop position in jQuery?

To set scrolltop position in jQuery, use the scrollTop() method. The scrollTop( ) method gets the scroll top offset of the first matched element. This method works for both visible and hidden elements.
You can try to run the following code to set scrollTop() method in jQuery:
Live Demo
<html>
   <head>
      <title>jQuery scrollTop() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            $("div.demo").scrollTop( 200 );
               
            $("div.demo").mousemove(function () {
               var top = $("div.demo").scrollTop();
               $("#result").html("top offset: <span>" + top + "</span>.");
            });
               
         });
      </script>
       
      <style>
         div.demo {
            background:#CCCCCC none repeat scroll 0 0;
            border:3px
            solid #666666;
            margin:5px;
            padding:5px;
            position:relative;
            width:300px;
            height:100px;
            overflow:auto;
         }
               
         div.result {
            margin:10px;
            width:100px;
            height:100px;
            margin:5px;
            float:left;
            background-color:red;
         }
               
         p {
            margin:10px;
            padding:5px;
            border:2px solid #666;
            width:1000px;
            height:1000px;
         }
      </style>
       
   </head>
   
   <body>
   
      <div class = "demo"><p>Hello</p></div>
      <span>Scroll vertical button to see the result:</span>
      <div class = "result"><span id = "result"></span></div>
       
   </body>
</html>
Lodash _.toQuery() Method - GeeksforGeeks

29 Sep, 2020
The Lodash _.toQuery() method takes an object and converts it into an equivalent URL query string.
Syntax:
_.toQuery( Object);

Parameters: This method accepts a single parameter as mentioned above and described below:
Object: This method takes an Object to convert.
Return Value: This method returns the equivalent URL query String.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib.
Example 1:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var s  = _.toQuery({     name: 'GeeksforGeeks',     address: 'Noida',    contact: '9876543210'});     console.log("The generated URL Query String is : ", s);
Output:
The generated URL Query String is : 
name=GeeksforGeeks&address=Noida&contact=9876543210

Example 2:
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var s  = _.toQuery(    { 'https://practice.geeksforgeeks.org/courses/?ref':     'gfg_header' });    console.log("The generated URL Query String is : ", s);
Output:
The generated URL Query String is : 
https%3A%2F%2Fpractice.geeksforgeeks.org%2Fcourses%2F%3Fref=gfg_header

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Compare DATE string with string from MySQL DATETIME field?

You can compare DATE string with string from DATETIME field with the help of DATE() function in MySQL.The syntax is as follows −
select *from yourTableName where DATE(yourColumnName) = ’anyDateString’;
To understand the above syntax, let us create a table and set some datetime values in the table. The query to create a table −
mysql> create table DateTimeDemo
   −> (
   −> ArrivalTime datetime
   −> );
Query OK, 0 rows affected (0.61 sec)
Let us insert some records in the table with the help of insert command. The following is the query to insert records −
mysql> insert into DateTimeDemo values(now());
Query OK, 1 row affected (0.11 sec)

mysql> insert into DateTimeDemo values(date_add(now(),interval 2 year));
Query OK, 1 row affected (0.47 sec)

mysql> insert into DateTimeDemo values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.19 sec)

mysql> insert into DateTimeDemo values(date_add(now(),interval 4 year));
Query OK, 1 row affected (0.13 sec)

mysql> insert into DateTimeDemo values(date_add(now(),interval -2 year));
Query OK, 1 row affected (0.17 sec)

mysql> insert into DateTimeDemo values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.17 sec)
Display all records with the help of select statement. The query to display all records from the table −
mysql> select *from DateTimeDemo;
The following is the output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2018-12-06 10:12:45 |
| 2020-12-06 10:13:10 |
| 2019-12-06 10:13:21 |
| 2022-12-06 10:13:27 |
| 2016-12-06 10:13:42 |
| 2017-12-06 10:13:50 |
+---------------------+
6 rows in set (0.00 sec)
Now implement the syntax we discussed above for comparing string with date time field. The query is as follows −
mysql> select *from DateTimeDemo where date(ArrivalTime) = '2022-12-06';
The following is the output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2022-12-06 10:13:27 |
+---------------------+
1 row in set (0.14 sec)
How to change the separation between tick labels and axis labels in Matplotlib?

To change the separation between tick labels and axis labels in Matplotlib, we can use labelpad in xlabel() method.
Set the figure size and adjust the padding between and around the subplots.
Plot data points of a list using plot() method.
Set the ticks on the axes.
Set X and Y axes margins to 0.
Set the X-axis label with labelpad.
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

plt.plot([1, 2, 3, 4, 5])

plt.xticks([1, 2, 3, 4, 5])
plt.margins(x=0, y=0)
plt.xlabel("X-axis", labelpad=7)

plt.show()
Euclidean Algorithm for calculating GCD in JavaScript

In mathematics, Euclid's algorithm, is a method for computing the greatest common divisor (GCD) of two numbers, the largest number that divides both of them without leaving a remainder.
The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number.
For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 − 105 = 147.
Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until the two numbers become equal. When that occurs, they are the GCD of the original two numbers.
By reversing the steps, the GCD can be expressed as a sum of the two original numbers each multiplied by a positive or negative integer, e.g., 21 = 5 × 105 + (−2) × 252.
We are required to write a JavaScript function that takes in two numbers and makes use of Euclid's algorithm to compute their GCD (greatest common divisor)
Following is the code −
const num1 = 252;
const num2 = 105;
const findGCD = (num1, num2) => {
   let a = Math.abs(num1);
   let b = Math.abs(num2);
   while (a && b && a !== b) {
      if(a > b){
         [a, b] = [a - b, b];
      }else{
         [a, b] = [a, b - a];
      };
   };
   return a || b;
};
console.log(findGCD(num1, num2));
Following is the output on console −
21
Convert object of objects to array in JavaScript

Let’s say we have the following object of objects that contains rating of some Indian players, we
need to convert this into an array of objects with each object having two properties namely
name and rating where name holds the player name and rating holds the rating object −
Following is our sample object −
const playerRating = {
   'V Kohli':{
      batting: 99,
      fielding: 99
   },
   'R Sharma':{
      batting: 98,
      fielding: 95
   },
   'S Dhawan':{
      batting: 92,
      fielding: 90
   }
}
The solution to this is quite simple and straightforward, we will use the Object.keys() method to
iterate over the object simultaneously converting it into an array like this.
Following is the complete code with output
const playerRating = {
   'V Kohli':{
         batting: 99,
      fielding: 99
   },
   'R Sharma':{
      batting: 98,
      fielding: 95
   },
   'S Dhawan':{
      batting: 92,
      fielding: 90
   }
}
const objArray = [];
Object.keys(playerRating).forEach(key => objArray.push({
   name: key,
   rating: playerRating[key]
}));
console.log(objArray);
[
   { name: 'V Kohli', rating: { batting: 99, fielding: 99 } },
   { name: 'R Sharma', rating: { batting: 98, fielding: 95 } },
   { name: 'S Dhawan', rating: { batting: 92, fielding: 90 } }
]
Adding value labels on a matplotlib bar chart

In this program, we can initialize some input values and then try to plot a bar using those values. We can instantiate a figure and axis so that we could set the label, ticks, and annotate the height and width of the bar.
Make a list of years.
Make a list of years.
Make a list of populations in that year.
Make a list of populations in that year.
Get the number of labels using np.arrange(len(years)) method.
Get the number of labels using np.arrange(len(years)) method.
Set the width of the bars.
Set the width of the bars.
Create fig and ax variables using subplots() method, where default nrows and ncols are 1.
Create fig and ax variables using subplots() method, where default nrows and ncols are 1.
Set the Y-axis label of the figure using set_ylabel().
Set the Y-axis label of the figure using set_ylabel().
Set the title of the figure, using set_title().
Set the title of the figure, using set_title().
Set the X-ticks with x that is created in step 3, using set_xticks method.
Set the X-ticks with x that is created in step 3, using set_xticks method.
Set the xtick_labels with years data, using set_xticklabels method.
Set the xtick_labels with years data, using set_xticklabels method.
Make a plot bar using ax.bar().
Make a plot bar using ax.bar().
Iterate the bar container (from step 10) to annotate to set the value for every bars.
Iterate the bar container (from step 10) to annotate to set the value for every bars.
Use plt.show() to show the figure.
Use plt.show() to show the figure.
from matplotlib import pyplot as plt
import numpy as np

years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09, 439.23, 548.16, 683.33, 846.42, 1028.74]

x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars

fig, ax = plt.subplots()

ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)

pps = ax.bar(x - width/2, population, width, label='population')
for p in pps:
   height = p.get_height()
   ax.annotate('{}'.format(height),
      xy=(p.get_x() + p.get_width() / 2, height),
      xytext=(0, 3), # 3 points vertical offset
      textcoords="offset points",
      ha='center', va='bottom')

plt.show()
Python – Replace words from Dictionary

02 Sep, 2020
Given String, replace it’s words from lookup dictionary.
Input : test_str = ‘geekforgeeks best for geeks’, repl_dict = {“geeks” : “all CS aspirants”}Output : geekforgeeks best for all CS aspirantsExplanation : “geeks” word is replaced by lookup value.
Input : test_str = ‘geekforgeeks best for geeks’, repl_dict = {“good” : “all CS aspirants”}Output : geekforgeeks best for geeksExplanation : No lookup value, unchanged result.
Method #1 : Using split() + get() + join()
In this, we initially split the list using split(), then look for lookups using get(), and if found, replaced and joined back to string using join().
Python3
# Python3 code to demonstrate working of # Replace words from Dictionary# Using split() + join() + get()  # initializing stringtest_str = 'geekforgeeks best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # lookup Dictionarylookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}  # performing split()temp = test_str.split()res = []for wrd in temp:          # searching from lookp_dict    res.append(lookp_dict.get(wrd, wrd))      res = ' '.join(res)  # printing result print("Replaced Strings : " + str(res)) 
The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

Method #2 : Using list comprehension + join()
Similar to above method, difference just being 1 liner rather than 3-4 steps in separate lines.
Python3
# Python3 code to demonstrate working of # Replace words from Dictionary# Using list comprehension + join()  # initializing stringtest_str = 'geekforgeeks best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # lookup Dictionarylookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}  # one-liner to solve problemres = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split())  # printing result print("Replaced Strings : " + str(res)) 
The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

Python dictionary-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to detect Browser Language in PHP?

17 Feb, 2020
We can detect requesting browser’s language using PHP’s super global variable $_SERVER. It is a superglobal variable which holds information about headers, paths, and script locations. It is basically an associative array in PHP which has keys like SERVER_NAME, SERVER_ADDR, REQUEST_METHOD, etc.
We can use HTTP_ACCEPT_LANGUAGE key to get the language of the browser.
Syntax:
$_SERVER['HTTP_ACCEPT_LANGUAGE']
We can see an output like:
en-US, en;q=0.9, hi;q=0.8, fr;q=0.7
Example 1:In order to get the current language of the browser, we can use PHP’s built-in substr function to get the first two letters of the string like-
<?php     echo substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  ?>
After running the above program you’ll see the output as your current browser’s language –
en
You can test it by changing your browser’s language. If you are on chrome you can go to chrome://settings/languages and choose a different language.
Now run the above program again and you’ll see the output as the newly chosen language.
Example 2: If your website has different pages for different languages, you can use this method in order to redirect to the page according to the user’s browser’s language.
<?php     $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);     // Redirect browser    header("Location: https://www.geeksforgeeks.org/" . $lang . "/index.php");       exit;  ?>
The above program will redirect to links like
http://www.example.com/en/index.php
PHP-Misc
Picked
Technical Scripter 2019
PHP
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Linq Except Method

Get the difference between two arrays using the Except() method.
The following are the two arrays.
int[] arr = { 9, 12, 15, 20, 35, 40, 55, 67, 88, 92 };
int[] arr2 = { 20, 35 };
To get the difference, use Except() method that returns the first list, except the elements in the second list.
arr.AsQueryable().Except(arr2);
The following is the entire example.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
   static void Main() {
      int[] arr = { 5, 10, 15, 20, 35, 40 };
      int[] except = { 20, 35 };
      Console.WriteLine("Initial List...");
      foreach(int ele in arr)
      Console.WriteLine(ele);
      IEnumerable<int> res = arr.AsQueryable().Except(except);
      Console.WriteLine("New List...");
      foreach (int a in res)
      Console.WriteLine(a);
   }
}
Initial List...
5
10
15
20
35
40
New List...
5
10
15
40
C Program to find size of a File - GeeksforGeeks

28 Apr, 2018
Given a text file, find its size in bytes.
Examples:
Input :  file_name = "a.txt"
         Let "a.txt" contains "geeks"
Output : 6 Bytes
There are 5 bytes for 5 characters then an extra
byte for end of file.

Input :  file_name = "a.txt"
         Let "a.txt" contains "geeks for geeks"
Output : 16 Bytes

The idea is to use fseek() in C and ftell in C. Using fseek(), we move file pointer to end, then using ftell(), we find its position which is actually size in bytes.
// C program to find the size of file#include <stdio.h>  long int findSize(char file_name[]){    // opening the file in read mode    FILE* fp = fopen(file_name, "r");      // checking if the file exist or not    if (fp == NULL) {        printf("File Not Found!\n");        return -1;    }      fseek(fp, 0L, SEEK_END);      // calculating the size of the file    long int res = ftell(fp);      // closing the file    fclose(fp);      return res;}  // Driver codeint main(){    char file_name[] = { "a.txt" };    long int res = findSize(file_name);    if (res != -1)        printf("Size of the file is %ld bytes \n", res);    return 0;}
C-File Handling
cpp-file-handling
C Language
C Programs
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
Program to check minimum number of characters needed to make string palindrome in Python

Suppose we have a string s, we have to find the minimum number of characters needed to be
inserted so that the string becomes a palindrome.
So, if the input is like s = "mad", then the output will be 2, as we can insert "am" to get
"madam".
To solve this, we will follow these steps −
Define a function dp(). This will take i, j
Define a function dp(). This will take i, j
if i >= j, thenreturn 0
if i >= j, then
return 0
return 0
if s[i] is same as s[j], thenreturn dp(i + 1, j - 1)
if s[i] is same as s[j], then
return dp(i + 1, j - 1)
return dp(i + 1, j - 1)
otherwise,return minimum of dp(i + 1, j) and dp(i, j - 1) + 1
otherwise,
return minimum of dp(i + 1, j) and dp(i, j - 1) + 1
return minimum of dp(i + 1, j) and dp(i, j - 1) + 1
From the main method, do the following
From the main method, do the following
return dp(0, size of s - 1)
return dp(0, size of s - 1)
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s):
      def dp(i, j):
         if i >= j:
            return 0
         if s[i] == s[j]:
            return dp(i + 1, j - 1)
         else:
            return min(dp(i + 1, j), dp(i, j - 1)) + 1
      return dp(0, len(s) - 1)
ob = Solution()
s = "mad"
print(ob.solve(s))
s = "mad"
2
SimpleDateFormat toLocalizedPattern() Method in Java with Examples - GeeksforGeeks

30 Jan, 2019
The toLocalizedPattern() Method of SimpleDateFormat class is used to return a localized pattern formatted string describing this date format. In other words a particular date is converted to a local pattern such as M/d/yy h:mm a.
Syntax:
public String toLocalizedPattern()
Parameters: The method does not take any parameter.
Return Value: The method returns localized pattern String of the Date Formatter.
Below programs illustrate the working of toLocalizedPattern() Method of SimpleDateFormat:
Example 1:
// Java code to illustrate// toLocalizedPattern() method  import java.text.*;import java.util.Calendar;  public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        // Initializing date Formatter        SimpleDateFormat SDFormat            = new SimpleDateFormat();          // Initializing the calender Object        Calendar cal = Calendar.getInstance();          // Displaying the date        System.out.println("Date: "                           + SDFormat.format(                                 cal.getTime()));          // Use of toLocalizedPattern() method        System.out.println("In localized pattern: "                           + SDFormat                                 .toLocalizedPattern());    }}
Date: 1/29/19 8:02 AM
In localized pattern: M/d/yy h:mm a

Example 2:
// Java code to illustrate// toLocalizedPattern() method  import java.text.*;import java.util.Calendar;  public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        // Initializing date Formatter        SimpleDateFormat SDFormat            = new SimpleDateFormat();          // Initializing the calender Object        Calendar cal = Calendar.getInstance();          // Displaying the date        System.out.println("Date: "                           + SDFormat                                 .format(                                     cal.getTime()));          // Use of toLocalizedPattern() method        System.out.println("In localized pattern: "                           + SDFormat                                 .toLocalizedPattern());    }}
Date: 1/29/19 12:46 PM
In localized pattern: M/d/yy h:mm a

Java-Functions
Java-SimpleDateFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
Convert NumberLong to String in MongoDB?

In order to convert NumberLong to String in MongoDB, you can use toString() −
NumberLong('yourValue').valueOf().toString();
To convert NumberLong to String, you can use valueOf() as well −
NumberLong('yourValue').valueOf();
Let us implement both the above syntaxes.
Following is the query to convert NumberLong to String with toString() −
> NumberLong('1000').valueOf().toString();
This will produce the following output −
1000
Following is the query to convert NumberLong to Number with valueOf()
> NumberLong('1000').valueOf();
This will produce the following output −
1000
Which datatype should I use for flag in MySQL?

To set a flag, you can set the type as tinyint(1) type.
 Following is the syntax −
yourColumnName tinyint(1) DEFAULT 1;
Let us first create a table −
mysql> create table DemoTable
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(20),
   isMarried tinyint(1) DEFAULT 1
);
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> INSERT INTO DemoTable(ClientName,isMarried) values('Larry',0);
Query OK, 1 row affected (0.16 sec)
mysql> INSERT INTO DemoTable(ClientName) values('David');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO DemoTable(ClientName,isMarried) values('Mike',1);
Query OK, 1 row affected (0.19 sec)
mysql> INSERT INTO DemoTable(ClientName) values('Carol');
Query OK, 1 row affected (0.14 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output that displays one of the column, which is set as flag −
+----------+------------+-----------+
| ClientId | ClientName | isMarried |
+----------+------------+-----------+
| 1        | Larry      | 0         |
| 2        | David      | 1         |
| 3        | Mike       | 1         |
| 4        | Carol      | 1         |
+----------+------------+-----------+
4 rows in set (0.00 sec)
How to retrieve a nested object in MongoDB?

To retrieve a nested object in MongoDB, use $ operator. Let us first create a collection with documents −
> db.queryNestedObject.insertOne(
...    {
...       "StudentName" : "James",
...       "StudentSubjectScore" : [
...          {"StudentMongoDBScore":98},
...          {"StudentCScore":92},
...          {"StudentJavaScore":91}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf49a9dceb9a92e6aa1962")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.queryNestedObject.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ccf49a9dceb9a92e6aa1962"),
   "StudentName" : "James",
   "StudentSubjectScore" : [
      {
         "StudentMongoDBScore" : 98
      },
      {
         "StudentCScore" : 92
      },
      {
         "StudentJavaScore" : 91
      }
   ]
}
Following is the query to retrieve a nested object −
> db.queryNestedObject.find({'StudentSubjectScore.StudentJavaScore' : 91},{'StudentSubjectScore.$': 1 , _id: 0});
This will produce the following output −
{ "StudentSubjectScore" : [ { "StudentJavaScore" : 91 } ] }
Transpose a matrix in Python?

Transpose a matrix means we’re turning its columns into its rows. Let’s understand it by an example what if looks like after the transpose.
Let’s say you have original matrix something like -
x = [[1,2][3,4][5,6]]
In above matrix “x” we have two columns, containing 1, 3, 5 and 2, 4, 6.
So when we transpose above matrix “x”, the columns becomes the rows. So the transposed version of the matrix above would look something like -
x1 = [[1, 3, 5][2, 4, 6]]
So the we have another matrix ‘x1’, which is organized differently with different values in different places.
Below are couple of ways to accomplish this in python -
Method 1 - Matrix transpose using Nested Loop -
#Original Matrix
x = [[1,2],[3,4],[5,6]]
result = [[0, 0, 0], [0, 0, 0]]
# Iterate through rows
for i in range(len(x)):
   #Iterate through columns
   for j in range(len(x[0])):
      result[j][i] = x[i][j]
   for r in Result
print(r)
[1, 3, 5]
[2, 4, 6]
Method 2 - Matrix transpose using Nested List Comprehension.
#Original Matrix
x = [[1,2],[3,4],[5,6]]
result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))]
for r in Result
   print(r)
[1, 3, 5]
[2, 4, 6]
List comprehension allows us to write concise codes and should be used frequently in python.
Method 3 - Matrix Transpose using Zip
#Original Matrix
x = [[1,2],[3,4],[5,6]]
result = map(list, zip(*x))
for r in Result
   print(r)
[1, 3, 5]
[2, 4, 6]
Method 4 - Matrix transpose using numpy library
Numpy library is an array-processing package built to efficiently manipulate large multi-dimensional array.
import numpy
#Original Matrix
x = [[1,2],[3,4],[5,6]]
print(numpy.transpose(x))
[[1 3 5]
[2 4 6]]
Java extends Keyword

❮ Java Keywords

The Car class 
(subclass) inherits the attributes and methods from the Vehicle class 
(superclass):
class Vehicle {
  protected String brand = "Ford";         // Vehicle attribute
  public void honk() {                     // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}


Try it Yourself »

The extends keyword extends a class (indicates that a class is inherited from another class).
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends 
keyword.
Read more about inheritance in our Java Inheritance Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Python os.stat() Method

Python method stat() performs a stat system call on the given path.
Following is the syntax for stat() method −
os.stat(path)

path − This is the path, whose stat information is required.
path − This is the path, whose stat information is required.
Here is the list of members of stat structure −
st_mode − protection bits.
st_mode − protection bits.
st_ino − inode number.
st_ino − inode number.
st_dev − device.
st_dev − device.
st_nlink − number of hard links.
st_nlink − number of hard links.
st_uid − user id of owner.
st_uid − user id of owner.
st_gid − group id of owner.
st_gid − group id of owner.
st_size − size of file, in bytes.
st_size − size of file, in bytes.
st_atime − time of most recent access.
st_atime − time of most recent access.
st_mtime − time of most recent content modification.
st_mtime − time of most recent content modification.
st_ctime − time of most recent metadata change.
st_ctime − time of most recent metadata change.
The following example shows the usage of stat() method.
# !/usr/bin/python

import os, sys

# showing stat information of file "a2.py"
statinfo = os.stat('a2.py')

print statinfo
When we run above program, it produces following result −
posix.stat_result(st_mode=33188, st_ino=3940649674337682L, st_dev=277923425L, st
_nlink=1, st_uid=400, st_gid=401, st_size=335L, st_atime=1330498089, st_mtime=13
30498089, st_ctime=1330498089)


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Making a countdown timer with Python and Tkinter

Tkinter is a standard Python library for creating GUI-based desktop applications. It offers a variety of functions, modules, and methods that can be used to implement the functionality of an application.
In this example, we will create a countdown Time using Python standard libraries such as Tkinter and time module. The basic functionality of our application would be to run the timer for a given period of time. It will have the following components,
An Entry widget to set the timer each for HH/MM/SS.
An Entry widget to set the timer each for HH/MM/SS.
A Button to execute the function countdowntimer().
A Button to execute the function countdowntimer().
A function countdowntimer() will convert the input string into an integer value relative to the HH, MM, and SS.
A function countdowntimer() will convert the input string into an integer value relative to the HH, MM, and SS.
Using update() method, we will update the window with respect to the given function and widgets.
Using update() method, we will update the window with respect to the given function and widgets.
# Import the required library
from tkinter import *
import time

# Create an instance of tkinter frame
win = Tk()

# Set the size of the window
win.geometry('700x350')

# Make the window fixed to its size
win.resizable(False, False)

# Configure the background
win.config(bg='skyblue4')

# Create Entry Widgets for HH MM SS
sec = StringVar()
Entry(win, textvariable=sec, width=2,
   font='Helvetica 14').place(x=380, y=120)
sec.set('00')

mins = StringVar()
Entry(win, textvariable=mins, width=2, font='Helvetica 14').place(x=346, y=120)
mins.set('00')

hrs = StringVar()
Entry(win, textvariable=hrs, width=2, font='Helvetica 14').place(x=310, y=120)
hrs.set('00')

# Define the function for the timer
def countdowntimer():
   times = int(hrs.get()) * 3600 + int(mins.get()) * 60 + int(sec.get())
   while times > -1:
      minute, second = (times // 60, times % 60)
      hour = 0
      if minute > 60:
         hour, minute = (minute // 60, minute % 60)
      sec.set(second)
      mins.set(minute)
      hrs.set(hour)

      # Update the time
      win.update()
      time.sleep(1)
      if (times == 0):
         sec.set('00')
         mins.set('00')
         hrs.set('00')
      times -= 1

# Create a Label widget
Label(win, font=('Helvetica bold', 22), text='Set the Timer', bg='skyblue4', fg="white").place(x=260, y=70)

# Button widget to set the timer
Button(win, text='START', bd='2', bg='IndianRed1', font=('Helvetica bold', 10), command=countdowntimer).place(x=335, y=180)

win.mainloop()
It will display a countdown timer in the window.
If we set the timer by changing the value in the Entry boxes and click the "start" button, it will quickly start the timer for the given period of time.
What are Default Constructors in Java?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.
A program that demonstrates this is given as follows:
 Live Demo
class NumberValue {
   private int num;
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj = new NumberValue();
      obj.display();
   }
}
The number is: 0
Now let us understand the above program.
The NumberValue class is created with a data member num and single member function display() that displays the value of num. A code snippet which demonstrates this is as follows:
class NumberValue {
   private int num;
   public void display() {
      System.out.println("The number is: " + num);
   }
}
In the main() method, an object obj of class NumberValue is created and the default constructor is called. Then display() method is called. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String[] args) {
      NumberValue obj = new NumberValue();
      obj.display();
   }
}
How to get time in milliseconds using C++ on Linux?

Here we will see how to get time (the elapsed time for the program or any other kind of time).
Here we are using linux library for C++. There is a structure called timeval. This timeval stores the time in seconds, milliseconds. We can create two time for start and end, then find the difference from them.
#include <sys/time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
main() {
   struct timeval start_time, end_time;
   long milli_time, seconds, useconds;
   gettimeofday(&start_time, NULL);
   cout << "Enter something: ";
   char ch;
   cin >> ch;
   gettimeofday(&end_time, NULL);
   seconds = end_time.tv_sec - start_time.tv_sec; //seconds
   useconds = end_time.tv_usec - start_time.tv_usec; //milliseconds
   milli_time = ((seconds) * 1000 + useconds/1000.0);
   cout << "Elapsed time: " << milli_time <<" milliseconds\n";
}
Enter something: h
Elapsed time: 2476 milliseconds
C Program to display hostname and IP address

In this section we will see how to see the Host name and IP address of the local system in an easier way. We will write a C program to find the host name and IP.
Some of the following functions are used. These functions have different task. Let us see the functions and their tasks.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void check_host_name(int hostname) { //This function returns host name for
   local computer
   if (hostname == -1) {
      perror("gethostname");
      exit(1);
   }
}
void check_host_entry(struct hostent * hostentry) { //find host info from
   host name
   if (hostentry == NULL) {
      perror("gethostbyname");
      exit(1);
   }
}
void IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal
   format
   if (NULL == IPbuffer) {
      perror("inet_ntoa");
      exit(1);
   }
}
main() {
   char host[256];
   char *IP;
   struct hostent *host_entry;
   int hostname;
   hostname = gethostname(host, sizeof(host)); //find the host name
   check_host_name(hostname);
   host_entry = gethostbyname(host); //find host information
   check_host_entry(host_entry);
   IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
   //Convert into IP string
   printf("Current Host Name: %s\n", host);
   printf("Host IP: %s\n", IP);
}
Current Host Name: soumyadeep-VirtualBox
Host IP: 127.0.1.1
GATE | GATE-CS-2014-(Set-1) | Question 51 - GeeksforGeeks

11 Sep, 2020
Consider the following pseudo code. What is the total number of multiplications to be performed?
D = 2
for i = 1 to n do
   for j = i to n do
      for k = j + 1 to n do
           D = D * 3
(A) Half of the product of the 3 consecutive integers.(B) One-third of the product of the 3 consecutive integers.(C) One-sixth of the product of the 3 consecutive integers.(D) None of the above.Answer: (C)Explanation: The statement “D = D * 3” is executed n*(n+1)*(n-1)/6 times. Let us see how. For i = 1, the multiplication statement is executed (n-1) + (n-2) + .. 2 + 1 times. For i = 2, the statement is executed (n-2) + (n-3) + .. 2 + 1 times ............................. ............................ For i = n-1, the statement is executed once. For i = n, the statement is not executed at all 
So overall the statement is executed following times [(n-1) + (n-2) + .. 2 + 1] + [(n-2) + (n-3) + .. 2 + 1] + ... + 1 + 0 
The above series can be written as S = [n*(n-1)/2 + (n-1)*(n-2)/2 + ..... + 1] 
The sum of above series can be obtained by trick of subtraction the series from standard Series S1 = n2 + (n-1)2 + .. 12. The sum of this standard series is n*(n+1)*(2n+1)/6 
S1 – 2S = n + (n-1) + ... 1 = n*(n+1)/2 2S = n*(n+1)*(2n+1)/6 – n*(n+1)/2 S = n*(n+1)*(n-1)/6
The above solution is relies on a trick to obtain the sum of the series, but there is a much more straightforward way of obtaining the same result :
For i = 1, the multiplication statement is executed (n-1) + (n-2) + .. 2 + 1 times.
For i = 2, the statement is executed (n-2) + (n-3) + .. 2 + 1 times 
Therefore, for each i, the number of times the statement is executed is: 
This is the sum of n natural numbers from 1 to n – i. Therefore, it can be simplified to:
Multiplying, we will get the following:
Now, this is the number of times the statement will be executed for each i. Therefore, in total, the number of times the statement will be executed is:
Ignore the half for the moment. Expanding the summation is simple. You can distribute it across the expression to get this:
Using the formulae for sum of n natural numbers and the sum of squares of n natural numbers, we get:
Simplifying further and taking n/6 as a common term will give you:
Now, take 2 as the common term and use it to cancel out the half that we ignored before. This gives you:
Finally, using a2-b2, you get the required answer:
This should make the solution clear to you now!
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
Importance of function prototype in C

Here we will see why we should use function prototype in C. The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. By this information, the compiler cross-checks the function signatures before calling it. If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output.
If some function is called somewhere, but its body is not defined yet, that is defined after the current line, then it may generate problems. The compiler does not find what is the function and what is its signature. In that case, we need to function prototypes. If the function is defined before then we do not need prototypes.
#include<stdio.h>
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}
The value of x is: 50
This shows the output, but it is showing some warning like below:
[Warning] conflicting types for 'function'
[Note] previous implicit declaration of 'function' was here
Now using function prototypes, it is executing without any problem.
#include<stdio.h>
void function(int); //prototype
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}
The value of x is: 50