code-rag-bench/online-tutorials huggingface dataset:
File exists() method in Java with examples

12 Dec, 2021
The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.
Syntax:
public boolean exists()
file.exists()
Parameters: This method does not accept any parameter.
Return Value: The function returns the boolean value if the file denoted by the abstract filename exists or not. 
Exception: This method throws Security Exception if the write access to the file is denied
Implementation: Consider file on the local directory on a system where local directory be as below provided.
“F:\\program.txt”
Example 1:
Java
// Java Program to Illustrate exists() method of File Class // Importing input output classesimport java.io.*; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Getting the file by creating object of File class        File f = new File("F:\\program.txt");         // Checking if the specified file exists or not        if (f.exists())             // Show if the file exists            System.out.println("Exists");        else             // Show if the file does not exists            System.out.println("Does not Exists");    }}
Output: 
Exists
Now let us consider the use-case where file is writable (“F:\\program1.txt”)
Example 2:
Java
// Java program to demonstrate// exists() method of File Class // Importing input output classesimport java.io.*; // Main classpublic class GFG {     // Main driver method    public static void main(String args[])    {        // Getting the file        File f = new File("F:\\program1.txt");         // Checking if the specified file        // exists or not        if (f.exists())             // Print message if it exists            System.out.println("Exists");        else             // Print message if it does not exists            System.out.println("Does not Exists");    }}
Output:  
Does not Exists
Akanksha_Rai
solankimayank
sagar0719kumar
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <td> valign Attribute

22 Feb, 2022
The HTML <td> valign Attribute is used to specify the vertical alignment of text content in a cell.
Syntax:
<td valign="top | middle | bottom | baseline">
Attribute Value:
top: It sets the content to top-align.
middle: It sets the content to middle-align.
bottom: It sets the content to bottom-align.
baseline: It sets the content to baseline. The baseline is the line where most of the characters sit. It is a default value.
Note: The <td> valign Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML td valign Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML td valign Attribute</h2>      <table border="1" width="500">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>          <tr style="height:50px;">            <td valign="top">BITTU</td>            <td valign="center">22</td>            <td valign="bottom">CSE</td>        </tr>          <tr style="height:50px;">            <td valign="bottom">RAKESH</td>            <td valign="center">25</td>            <td valign="top">EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <td> valign Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Class getAnnotation() method in Java with Examples - GeeksforGeeks

27 Dec, 2019
The getAnnotation() method of java.lang.Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object.
Syntax:
public T getAnnotation(Class<T> annotationClass)

Parameter: This method accepts a parameter annotationClass which is the type of the annotation to get.
Return Value: This method returns the specified object of the annotation class.
Exception: This method throws:
NullPointerException: if the given annotation class is null.
Below programs demonstrate the getAnnotation() method.
Example 1:
// Java program to demonstrate// getAnnotation() method  import java.util.*;import java.lang.annotation.*;  // create a custom Annotation@Retention(RetentionPolicy.RUNTIME)@interface Annotation {      // This annotation has two attributes.    public String key();      public String value();}  // call Annotation for method// and pass values for annotation@Annotation(key = "GFG", value = "GeeksForGeeks")public class Test {      public static void main(String[] args)        throws ClassNotFoundException    {          // returns the Class object for this class        Class myClass = Test.class;          System.out.println("Class represented by myClass: "                           + myClass.toString());          // Get the annotation        // using getAnnotation() method        System.out.println(            "Annotation of myClass: "            + myClass.getAnnotation(                  Annotation.class));    }}
Output:
Class represented by myClass: class Test
Annotation of myClass: @Annotation(key=GFG, value=GeeksForGeeks)

Example 2:
// Java program to demonstrate// getAnnotation() method  import java.util.*;import java.lang.annotation.*;  // Class with no annotations// getAnnotation() will return nullpublic class Test {      public static void main(String[] args)        throws ClassNotFoundException    {          // returns the Class object for this class        Class myClass = Test.class;          System.out.println("Class represented by myClass: "                           + myClass.toString());          // Get the annotation        // using getAnnotation() method        System.out.println(            "Annotation of myClass: "            + myClass.getAnnotation(                  Annotation.class));    }}
Output:
Class represented by myClass: class Test
Annotation of myClass: null

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getAnnotation-java.lang.Class-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples
How to change npm start script of node.js ? - GeeksforGeeks

31 Mar, 2021
The script is a list of commands that are used to perform some specific tasks that they are designed to perform. In Node.js there are a lot of predefined scripts created while creating a new project some of them contain a default value, and we can also change them according to our need of the operations for a specific task. 
Script keywords available in node.js  are given below npm start script is one of the most commonly used scripts in the node.js as well as in react. npm start: npm start script is used to execute the defined file in it without typing its execution command.
Package.json file
"scripts"{
"start":"node index.js"
}
index.js
// Importing http moduleconst http = require("http")  // Creating Serverconst server = http.createServer((req,res)=>{    req.statusCode=200;    console.log("Server is Started")    res.end();});  // Executing the serverserver.listen(3000,"localhost",()=>{    console.log("Server is Running ")})
Run index.js file using below command:
node index.js
Output:
When no execution file mentioned in the npm start script npm automatically runs the node server.js file if available in the project directory.
package.json
server.js
// Importing http moduleconst http = require("http")  // Creating Serverconst server = http.createServer((req,res)=>{    req.statusCode=200;    console.log("Server  is Executed")    res.end();});  // Executing the serverserver.listen(3000,"localhost",()=>{    console.log("This is server.js file")})
Run server.js file using below command:
node server.js
Output:
Node-npm
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Node.js Export Module
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Kotlin Tutorial

Kotlin is a modern, trending programming language.
Kotlin is easy to learn, especially if you already know Java (it is 
  100% compatible with Java).
Kotlin is used to develop Android apps, server side apps, and much more.
Our "Try it Yourself" editor makes it easy to learn Kotlin. You can edit the 
code and view the result in your browser:
fun main() {
  println("Hello World")
}
Click on the "Try it Yourself" button to see how it works.
We recommend reading this tutorial, in the sequence listed in the left menu.
Insert the missing part of the code below to output "Hello World".
 () {
  println("Hello World")
}

Start the Exercise
Learn by taking a quiz! This quiz will give you a signal of how much you know about Kotlin.
Take the Kotlin Quiz
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All Kotlin Examples
Download Kotlin from github:
https://github.com/JetBrains/kotlin
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.
How to configure handling and formatting of log file in Selenium with python?

A log configuration consists of formatter and FileHandler methods. We
need to import a logging package and then create an object which will be
responsible for entire logging.
If we add the parameter _name_ inside the getLogger() method, we shall be able
to add the test case name for which we want to create the log file. If this parameter
is omitted in the argument, by default it prints root in the log file.
logger = logging.getLogger(_name_)
The different types of logger level are listed below. We can add all, some or at least
one logger in our test case.
logger.debug("Debug log")
logger.info("Information log")
logger.warning("Warning log")
logger.error("Error log")
logger.critical("Critical log")
Then we should specify the location to the logger object to print these logs. This is
handled with the help of addHandler() method. This method accepts the file
handler object as its arguments.
The file handler object works with the parent logging package and its method
known as the FileHandler(). This method contains the name and location of the log
file where the entire logging information will be available.
fileHandler = logging.FileHandler('logfile.log')
logger.addHandler(fileHandler)
Next we need to define the format in which the log file is to be created. This is
achieved by the Formatter() method obtained from the parent logging package.
The Formatter() method takes the format to be followed as an argument.
logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")
This has to be stored in a formatter object and it can correlate with the fileHandler
object via setFormatter() method. This method accepts the formatter object.
formatter=logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message")
fileHandler.setFormatter(formatter)
Finally, we need to set the level of logging. This is achieved by setLevel() method.
logger.setLevel(logging.ERROR)
Through this we can limit printing of all types of logger levels in the log file.
Coding Implementation of logging configuration.
import logging
def loggingDmo():
# getLogger() method takes the test case name as input
logger = logging.getLogger(__name__)
# FileHandler() method takes location and path of log file
fileHandler = logging.FileHandler('logfile.log')
# Formatter() method takes care of the log file formatting
formatter = logging.Formatter("%(asctime)s :%(levelname)s :
%(name)s :%(message)s")
fileHandler.setFormatter(formatter)
# addHandler() method takes fileHandler object as parameter
logger.addHandler(fileHandler)
# setting the logger level
logger.setLevel(logging.DEBUG)
logger.debug("Debug log")
logger.info("Information log ")
logger.warning("Warning log")
logger.error("Error log")
logger.critical("Critical log")
ES6 - gettime() Method

JavaScript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00.
You can use this method to help assign a date and time to another Date object.
Date.getTime ()  

Returns the numeric value corresponding to the time for the specified date according to universal time.
var dt = new Date("December 25, 1995 23:15:00"); 
console.log("getTime() : " + dt.getTime());  
getTime() : 819913500000   


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How to replace all dots in a string using JavaScript?

To replace the dots in a string, you need to escape the dot (.) and replace using the replace() method.
You can try to run the following code to replace all dots in a string −
<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <script>
         var str = 'Demo.Text.with.dots';
         document.write("Text with dots- "+str);
         
         var res = str.replace(/\./g,' ');
         document.write("<br>Text without dots- "+res);
      </script>
   </body>
</html>
Easiest way to get number of rows in a MySQL table?

The easiest way to get number of rows, use aggregate function COUNT(*). Let us first create a table −
mysql> create table DemoTable1575
   -> (
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (1.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1575 values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1575 values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1575 values('Adam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1575 values('Robert');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1575;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Chris     |
| Bob       |
| Adam      |
| Robert    |
+-----------+
4 rows in set (0.00 sec)
Here is how to get the number of rows −
mysql> select count(*) from DemoTable1575;
This will produce the following output −
+----------+
| count(*) |
+----------+
|        4 |
+----------+
1 row in set (0.03 sec)
Program to convert Primitive Array to Stream in Java

To convert Primitive Array to Stream, you need to use the of() method.
Let’s say the following is our Primitive Array:
int[] myArr = new int[] { 20, 50, 70, 90, 100, 120, 150 };
Now, use the of() method to convert the primitive array to stream:
IntStream stream = IntStream.of(myArr);
The following is an example to convert primitive array to stream in Java:
 Live Demo
import java.util.stream.IntStream;
import java.util.*;
public class Main {
   public static void main(String[] args) {
      int[] myArr = new int[] { 20, 50, 70, 90, 100, 120, 150 };
      System.out.println("The Primitive Array = "+Arrays.toString(myArr));
      IntStream stream = IntStream.of(myArr);
      System.out.println("Primitive Array to Stream = " + Arrays.toString(stream.toArray()));
   }
}
The Primitive Array = [20, 50, 70, 90, 100, 120, 150]
Primitive Array to Stream = [20, 50, 70, 90, 100, 120, 150]
Create a Date Picker Calendar in Tkinter

Tkinter is a popular Python library for creating and developing applications. It has
various methods and functions that can be used for adding multiple features in an
application.
Tkcalendar is one of the tkinter packages that can be used to create GUI-based calendars in the window and thus, we can perform multiple operations like selecting the data, picking and scheduling the event through the calendar application and many more.
However, in this article, we will see how we can create a Date Picker calendar using the Tkcalendar package. Before that, we have to install the package in our local environment using pip install tkcalendar.
Once installed, we will create an instance of tkcalendar and create a button to get
the date.
#Import the libraries
from tkinter import *
from tkcalendar import *

#Create an instance of tkinter frame or window
win= Tk()
win.title("Calendar")
win.geometry("700x600")

cal= Calendar(win, selectmode="day",year= 2021, month=3, day=3)
cal.pack(pady=20)

#Define Function to select the date
def get_date():
   label.config(text=cal.get_date())

#Create a button to pick the date from the calendar
button= Button(win, text= "Select the Date", command= get_date)
button.pack(pady=20)

#Create Label for displaying selected Date
label= Label(win, text="")
label.pack(pady=20)

win.mainloop()
Running the above code will create a calendar, where we can select a particular
date.
RxJS - Error Handling Operator retry

This operator will take care of retrying back on the source Observable if there is error and the retry will be done based on the input count given.
retry(retry_count: number): Observable

retry_count − The argument retry_count, is the number of times you want to retry.
It will return back source observable with retry count logic.
import { of } from 'rxjs';
import { map, retry } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

let all_nums = of(1, 6, 5, 10, 9, 20, 10);
let final_val = ajax('http://localhost:8081/getData').pipe(retry(4));
final_val.subscribe(
   x => console.log(x), => console.error(err),
   () => console.log("Task Complete")
);
In the example, we are making a call to a url using ajax. The url − http://localhost:8081/getData is giving a 404 so the retry() operator tries to make a call to url again for 4 times. The output is shown below

    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
What is Data Dependency?

A position in which an instruction is dependent on a result from a sequentially earlier instruction before it can be done its execution. In high-performance processors operating pipeline or superscalar techniques, a data dependency will learn an interruption in the flowing services of a processor pipeline or prevent the parallel issue of instructions in a superscalar processor.
Consider two instructions ik and ii of the same program, where ik precedes ii. If ik and ii have a common register or memory operand, they are data-dependent on each other, except when the common operand is used in both instructions as a source operand.
An example is when ii uses the result of ik as a source operand. In sequential execution data, dependencies do not generate any issue, because instructions are implemented rigidly in the stated sequence.
Data dependency can appear either in ‘straight-line code’ between subsequent instructions or in a loop between instructions belonging to subsequent iterations of a loop as shown in the figure.
Therefore, by ‘straight-line code’ it can define any code sequence, even instructions of a loop body that does not involve instructions from subsequent loop iterations. Straight-line code can include three different types of dependencies, known as RAW (Read after Write), WAR (Write after Read), and WAW (Write after Write) dependencies.
Data dependencies in straight-line code
Data dependencies for memory data can be interpreted in a similar method.
RAW dependencies − Consider two assembly language instructions −
i1: load r1, a;
i2: add  r2, r1, r1;
Therefore, instruction i2 uses r1 as a source. As a result, i2 cannot be directly implemented just before r1 has been loaded by i1. Thus, i2 is RAW-dependent on it. RAW dependencies are also known as flow dependencies. They are true dependencies because they cannot be abandoned.
RAW dependencies can be divided into load-use and define-use dependencies. In the following example, the requested source operand has to be loaded first. This method can handle a load-use dependency. By compare, if the requested source operand is represented in the previous instruction, in the instruction sequence.
i1: mul r1, r4, r5;
i2: add r2, r1, r1;
This type of RAW dependency is labeled as a define-use dependency.
WAR dependencies − Consider the execution of the following instructions −
i1: mul r1, r2, r3;
i2: add r2, r4, r5;
In this case, i2 writes r2 while i1 uses r2 as a source. If for any reason, i2 were to be implemented ahead of i1 then the initial content of r2 would be rewritten previously than it is read by instruction r1, which can lead to an incorrect result.
WAW dependencies: Two instructions are WAW-dependent (or output dependent) if they both write the similar destination, as in the following example −
i1: mul r1, r2, r3;
i2: add r1, r4, r5;
This type of dependency is also a false dependency and can be removed in a similar method as WAR dependencies through register renaming. A WAW dependency determination when the execution of the contained logically preceding instruction will be done and the produced result can refresh the program state.
Printing source of a C program itself

Given the task is to print the written C program itself.
We have to write a C program which will print itself. So, we can use file system in C to print the contents of the file of which we are writing the code, like we are writing the code in “code 1.c” file, so we open the file in the read mode and read all the contents of the file and print the results on the output screen.
But, before opening a file in read mode, we must know the name of the file we are writing code in. So, we can use “__FILE__” which is a macro and is by default, returns the path of the current file.
Example for the macro “__FILE__”
#include<stdio.h>
int main() {
   printf(“%s”, __FILE__);
}
The above program will print the source of the file in which the code is written
The macro __FILE__ returns a string with the path of the current program in which this macro is mentioned.
So, when we merge it into the file system to open the current file in which the code is in read mode, we do like −
fopen(__FILE__, “r”);
Start
Step 1-> In function int main(void)
   Declare a character c
   Open a FILE “file” “__FILE__” in read mode
   Loop do-while c != End Of File
      Set c = fgetc(file)
      putchar(c)
   Close the file “file”
Stop
#include <stdio.h>
int main(void) {
   // to print the source code
   char c;
   // __FILE__ gets the location
   // of the current C program file
   FILE *file = fopen(__FILE__, "r");
   do {
      //printing the contents
      //of the file
      c = fgetc(file);
      putchar(c);
   }
   while (c != EOF);
   fclose(file);
   return 0;
}
#include <stdio.h>
int main(void) {
   // to print the source code
   char c;
   // __FILE__ gets the location
   // of the current C program file
   FILE *file = fopen(__FILE__, "r");
   do {
      //printing the contents
      //of the file
      c = fgetc(file);
      putchar(c);
   }
   while (c != EOF);
   fclose(file);
   return 0;
}
asksaveasfile() function in Python Tkinter

TKinter is a Python module which is used for GUI programming in Python. We create a Canvas and place our UI components with many properties and behaviors in it. In this article, we will see e how to use the ask essay file function to save files created through Python programs into the local drives.
We first create a canvas on which we again place a button using the TTK dot button function. Then declare another function that will use the ask fine to define the file type and save the file into location in the local drive.
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import asksaveasfile

base = Tk()
base.geometry('300x250')

def SaveFile():
   data = [('All tyes(*.*)', '*.*')]
   file = asksaveasfile(filetypes = data, defaultextension = data)

save_btn = ttk.Button(base, text = 'Click to save file ', command = lambda : SaveFile())
save_btn.pack(side = TOP, pady = 20,padx = 50)

mainloop()
Running the above code gives us the following result −
Next on clicking the “click to save file as” button, we get the next window as below.
HBase - Drop a Table

Using the drop command, you can delete a table. Before dropping a table, you have to disable it.
hbase(main):018:0> disable 'emp'
0 row(s) in 1.4580 seconds

hbase(main):019:0> drop 'emp'
0 row(s) in 0.3060 seconds

Verify whether the table is deleted using the exists command.
hbase(main):020:07gt; exists 'emp'
Table emp does not exist
0 row(s) in 0.0730 seconds

This command is used to drop the tables matching the “regex” given in the command. Its syntax is as follows:
hbase> drop_all ‘t.*’ 

Note: Before dropping a table, you must disable it.
Assume there are tables named raja, rajani, rajendra, rajesh, and raju.
hbase(main):017:0> list
TABLE
raja
rajani
rajendra 
rajesh
raju
9 row(s) in 0.0270 seconds

All these tables start with the letters raj. First of all, let us disable all these tables using the disable_all command as shown below.
hbase(main):002:0> disable_all 'raj.*'
raja
rajani
rajendra
rajesh
raju
Disable the above 5 tables (y/n)?
y
5 tables successfully disabled

Now you can delete all of them using the drop_all command as given below.
hbase(main):018:0> drop_all 'raj.*'
raja
rajani
rajendra
rajesh
raju
Drop the above 5 tables (y/n)?
y
5 tables successfully dropped

You can delete a table using the deleteTable() method in the HBaseAdmin class. Follow the steps given below to delete a table using java API.
Instantiate the HBaseAdmin class.
// creating a configuration object
Configuration conf = HBaseConfiguration.create();

// Creating HBaseAdmin object
HBaseAdmin admin = new HBaseAdmin(conf); 

Disable the table using the disableTable() method of the HBaseAdmin class.
admin.disableTable("emp1");

Now delete the table using the deleteTable() method of the HBaseAdmin class.
admin.deleteTable("emp12");

Given below is the complete java program to delete a table in HBase.
import java.io.IOException;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;

public class DeleteTable {

   public static void main(String[] args) throws IOException {

      // Instantiating configuration class
      Configuration conf = HBaseConfiguration.create();

      // Instantiating HBaseAdmin class
      HBaseAdmin admin = new HBaseAdmin(conf);

      // disabling table named emp
      admin.disableTable("emp12");

      // Deleting emp
      admin.deleteTable("emp12");
      System.out.println("Table deleted");
   }
}
Compile and execute the above program as shown below.
$javac DeleteTable.java
$java DeleteTable

The following should be the output:
Table deleted

 Print
 Add Notes
 Bookmark this page
Sorting max to min value in MySQL

To sort from max to min value, use ORDER BY length(). Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Price varchar(20)
   -> );
Query OK, 0 rows affected (0.92 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('80');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('800');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('108');
Query OK, 1 row affected (0.50 sec)
mysql> insert into DemoTable values('765');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Price |
+-------+
| 80    |
| 800   |
| 108   |
| 765   |
+-------+
4 rows in set (0.00 sec)
Here is the query to sort max to min value in MySQL −
mysql> select *from DemoTable
   -> order by length(Price) DESC,Price DESC;
This will produce the following output −
+-------+
| Price |
+-------+
| 800   |
| 765   |
| 108   |
| 80    |
+-------+
4 rows in set (0.00 sec)
Program to decode a run-length form of string into normal form in Python

Suppose we have a string s. The s is a run-length encoded string, we have to find the decoded version of it. As we know, run-length encoding is a fast and simple method of encoding strings. The idea is as follows − The repeated successive elements (characters) as a single count and character. For example, if the string is like "BBBBAAADDCBB" would be encoded as "4B3A2D1C2B".
So, if the input is like s = "4B3A2D1C2B", then the output will be "BBBBAAADDCBB"
To solve this, we will follow these steps −
output := blank string
num:= blank string
for each character i in s, doif i is alphabet, thenoutput := output + i*(num as number)num:= blank stringotherwise,num := num + i
if i is alphabet, thenoutput := output + i*(num as number)num:= blank string
output := output + i*(num as number)
num:= blank string
otherwise,num := num + i
num := num + i
return output
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s):
      output = ""
      num=""
      for i in s:
         if i.isalpha():
            output+=i*int(num)
            num=""
         else:
            num+=i
      return output
ob = Solution() print(ob.solve("4B3A2D1C2B"))
"4B3A2D1C2B"
BBBBAAADDCBB
Finding the Start Index of the Specified Range in C# - GeeksforGeeks

28 Jun, 2021
The Range Structure is introduced in C# 8.0. It represents a range that has start and end indexes. You are allowed to find the start index of the given range with the help of the Start Property provided by the Range struct.Syntax:  
public property Index Start { Index get(); };
Here, Index represents the inclusive start index of the range.Example 1: 
CSharp
// C# program to illustrate the use// of Start property of Range structusing System; namespace range_example { class GFG {     // Main Method    static void Main(string[] args)    {         // Creating range        // using Range Constructor        var r1 = new Range(0, 5);         // Creating range        // using range operator        Range r2 = 3..7;         // Finding the Starting        // index of r1 and r2 ranges        // Using Start property        var res1 = r1.Start;        Console.WriteLine("Starting index of r1 range: " + res1);         var res2 = r2.Start;        Console.WriteLine("Starting index of r2 range: " + res2);    }}}
Output: 
Starting index of r1 range: 0
Starting index of r2 range: 3
Example 2: 
CSharp
// C# program to illustrate how to use// Start property of Range structureusing System; namespace range_example { class GFG {     // Main Method    static void Main(string[] args)    {        // Creating and initializing an array        string[] arr = new string[8] {"Archery", "Badminton", "Cricket", "Bowling",                                   "Boxing", "Curling", "Tennis", "Skateboarding"};         // Creating ranges        // Using Range(Index, Index)        // Constructor        var r1 = new Range(0, 3);        var r2 = new Range(4, 7);         // Finding the start index        // of the specified range        // Using Start property        var res1 = r1.Start;        var res2 = r2.Start;        Console.WriteLine("Start Index of Range {0} is {1}"+               " and the item is {2}", r1, res1, arr[res1]);         Console.WriteLine("Start Index of Range {0} is {1}"+               " and the item is {2}", r2, res2, arr[res2]);    }}}
Output: 
Start Index of Range 0..3 is 0 and the item is Archery
Start Index of Range 4..7 is 4 and the item is Boxing
 
khushboogoyal499
saurabh1990aror
CSharp-8.0
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
Python - Make pair from two list such that elements are not same in pairs

In this article, we are going to learn how to make pairs from two lists such that no similar elements make a pair. Follow the below steps to solve the problem.
Initialize the lists with elements.
Iterate over the lists and append the pair into a list if the corresponding elements from the lists are not same.
Print the result.
Let's see the code.
# initializing the lists
list_1 = [1, 2, 3, 4, 5]
list_2 = [5, 8, 7, 1, 3, 6]

# making pairs
result = [(i, j) for i in list_1 for j in list_2 if i != j]

# printing the result
print(result)
If you run the above code, then you will get the following result.
[(1, 5), (1, 8), (1, 7), (1, 3), (1, 6), (2, 5), (2, 8), (2, 7), (2, 1), (2, 3), (2, 6), (3, 5), (3, 8), (3, 7), (3, 1), (3, 6), (4, 5), (4, 8), (4, 7), (4, 1), (4, 3), (4, 6), (5, 8), (5, 7), (5, 1), (5, 3), (5, 6)]

We can solve the problem with itertools module as well. It provides a method called product that makes pairs of all the elements. We can filter the pairs after finding the pairs.
Let's see the code.
# importing the module
import itertools

# initializing the lists
list_1 = [1, 2, 3, 4, 5]
list_2 = [5, 8, 7, 1, 3, 6]

# pairs
pairs = itertools.product(list_1, list_2)

# filtering the pairs
result = [pair for pair in pairs if pair[0] != pair[1]]

# printing the result
print(result)
If you run the above code, then you will get the following result.
[(1, 5), (1, 8), (1, 7), (1, 3), (1, 6), (2, 5), (2, 8), (2, 7), (2, 1), (2, 3), (2, 6), (3, 5), (3, 8), (3, 7), (3, 1), (3, 6), (4, 5), (4, 8), (4, 7), (4, 1), (4, 3), (4, 6), (5, 8), (5, 7), (5, 1), (5, 3), (5, 6)]

If you run the above code, then you will get the following result.
How to implement the listeners using lambda expressions in Java?

When we are using a lambda expression for java listener, we do not have to explicitly implement the ActionListener interface. Instead, we can use the below syntax.
button.addActionListener(e -> { // some statements });
An ActionListener interface defines only one method actionPerformed(). It is a functional interface which means that there's a place to use lambda expressions to replace the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LambdaListenerTest extends JFrame {
   public static void main(String args[]) {
      new LambdaListenerTest();
   }
   private JButton button;
   public ClickMeLambdaTest() {
      setTitle("Lambda Expression Test");
      button = new JButton("Click Me!");
      button.addActionListener(ae -> button1Click());   // lambda expression for ActionListener 

      getContentPane().add(button, BorderLayout.NORTH);
      setSize(450, 300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   private int clickCount = 0;
   public void button1Click() {
      clickCount++;
      if(clickCount == 1)
         button.setText("Clicked!!!");
      else
         button.setText("Clicked " + clickCount + " times!!!");
   }
}
Difference Between Algorithm and Pseudocode

In this post, we will understand the differences between algorithm and pseudocode −
It is defined as a sequence of well-defined steps.
These steps provide a solution/ a way to solve a problem in hand.
It is a systematic, and a logical approach, where the procedure is defined step-wise.
It gives the solution to a specific problem.
This solution would be translated to machine code, which is then executed by the system to give the relevant output.
Many simple operations are combined to help form a more complicated operation, which is performed with ease by the computer.
Algorithms can be represented using natural language, flowchart and so on.
It is difficult to understand.
Plain text is used.
It is easy to debug.
Its construction is tough.
There are no rules to follow while constructing it.
It can be understood as the pseudocode for a program.
Algorithm for linear search
Start searching for an element from the left-most part of the array.
Compare one element every iteration with the item_to_be_searched.
If no matches are found, return -1.
Otherwise, return the index at which the element is present.
It can be understood as one of the methods that helps in the representation of an algorithm.
It is a simpler version of coding in a programming language.
It is written in plain English, and uses short phrases to write the functionalities that s specific line of code would do.
There is no specific syntax which is actually present in other programming languages.
This means it can't be executed on a computer.
There are many formats that could be used to write pseudo-codes.
Most of these formats take the structure from languages such as C, LIST, FORTRAN, and so on.
Pseudocode is not actually a programming language.
Control structures such as 'while', 'if-then-else', 'repeat-until', and so on can be used.
Pseudocode for Linear Search
FUNCTION linear_search(array, search_item):
   FOR index FROM 0 -> length(array):
   IF array [index] == search_item THEN
      RETURN index
   ENDIF
   ENDLOOP
      RETURN -1
END FUNCTION
No specific language was used, but the functionalities were clearly mentioned.
Java Program to convert java.util.Date to ZonedDateTime

Create a Date object −
Date date = new Date();
Now, set the ZonedId to default −
final ZoneId id = ZoneId.systemDefault();
Convert java.util.date to ZonedDateTime −
System.out.println(ZonedDateTime.ofInstant(date.toInstant(), id));
 Live Demo
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      final ZoneId id = ZoneId.systemDefault();
      System.out.println(ZonedDateTime.ofInstant(date.toInstant(), id));
   }
}
2019-04-19T00:37:33.344+05:30[Asia/Calcutta]
Explain the inference rules for functional dependencies in DBMS

Functional dependencies are the constraints that are derived from the meaning and interrelationship of the data. Let F is a set of all functional dependencies. The set of all dependencies that include F as well as all dependencies that can be inferred from F is called CLOSURE of F denoted by F+.
Given below is an example of functional dependency in database management system (DBMS) −
F= { SSN-> {ENMAE,BDATE,ADDRESS,DNUMBER}, DNUMBER-> {DNAME,DMGRSSN} }
You will get the following result −
Given below is another example of functional dependency in the DBMS −
F+ = { SSN-> {ENAME,BDATE,ADDRESS,DNUMBER},
   DNUMBER-> {DNAME, DMGRSSN},
   SSN -> {DNAME, DMGRSSN},
   ENO->ENO,
   DNUMBER-> DNAME }
To determine a systematic way to infer dependencies, we must discover a set of interface rules that can be used to infer new dependencies from a given set of dependencies.
There are six inference rules which are as follows −
Reflexivity: X->X // An attribute(s) determines itself
Augmentation: if X->Y then XZ->YZ
Transitivity: if X->Y & Y->Z then X->Z
Additivity or Union : if X->Y & X->Z then X->YZ
Projectivity or Decomposition: If X->YZ then X-> Y & X->Z
Pseudo-Transitivity: If X->Y, YZ->W then XZ->W
Let’s take a relation R with attributes R(A,B,C,D,E,F)
F: AB->C, BC->AD, D->E, E->F, CF->B, then prove that F logically implies CD->B
D->E, E->F THEN D=>F { Transitivity property}.
D->E, CF-> THEN D=>B {Pseudo-Transitivity}
D->E, E->F THEN D=>F {Transitivity}
D->F THEN CD->CF {Augmentation}
CD->CF, CF-> B THEN => CD-> B {Transitivity}
ruby - Unix, Linux Command

If you want a language for easy object-oriented programming, or you
don’t like the Perl ugliness, or you do like the concept of LISP, but
don’t like too much parentheses, Ruby may be the language of your
choice.


















































#! /usr/local/bin/ruby

# This line makes the next one a comment in Ruby \

  exec /usr/local/bin/ruby -S $0 $*





  $F = $_.split












% echo matz > /tmp/junk

% cat /tmp/junk

matz

% ruby -p -i.bak -e ’$_.upcase!’ /tmp/junk

% cat /tmp/junk

MATZ

% cat /tmp/junk.bak

matz






while gets

  ...

end




% echo matz | ruby -p -e ’$_.tr! "a-z", "A-Z"’

MATZ






#! /usr/local/bin/ruby -s

# prints "true" if invoked with ‘-xyz’ switch.

print "true\n" if $xyz


On some systems
"$0"
does not always contain the full pathname, so you need the
-S
switch to tell Ruby to search for the script if necessary.  To handle
embedded spaces or such.  A better construct than
"$*"
would be
${1+"$@"},
but it does not work if the script is being interpreted by
csh(1).












e.g.:

  RUBYLIB="$HOME/lib/ruby:$HOME/lib/rubyext"




e.g.

  RUBYOPT="-w -Ke"












Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Solidity - Structs

Struct types are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
To define a Struct, you must use the struct keyword. The struct keyword defines a new data type, with more than one member. The format of the struct statement is as follows −
struct struct_name { 
   type1 type_name_1;
   type2 type_name_2;
   type3 type_name_3;
}
struct Book { 
   string title;
   string author;
   uint book_id;
}
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the struct to define variables of structure type. The following example shows how to use a structure in a program.
Try the following code to understand how the structs works in Solidity.
pragma solidity ^0.5.0;

contract test {
   struct Book { 
      string title;
      string author;
      uint book_id;
   }
   Book book;

   function setBook() public {
      book = Book('Learn Java', 'TP', 1);
   }
   function getBookId() public view returns (uint) {
      return book.book_id;
   }
}
Run the above program using steps provided in Solidity First Application chapter.
First Click setBook Button to set the value as LARGE then click getBookId to get the selected book id.
uint256: 1


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Remove All Special Characters from String in R - GeeksforGeeks

23 Aug, 2021
In this article, we are going to remove all special characters from strings in R Programming language. 
For this, we will use the str_replace_all() method to remove non-alphanumeric and punctuations which is available in stringr package.
To install this library type the below command in the terminal.
install.packages("stringr")  
We will remove non-alphanumeric characters by using str_replace_all() method.
Syntax: str_replace_all(string, “[^[:alnum:]]”, “”)
where
string is the input string
[^[:alnum:]] is the parameter that removes the non-alphanumeric characters.
Example 1: R program to remove non-alphanumeric characters from the string
R
# load the stringr packagelibrary("stringr")  # stringstring = "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"  # display original stringprint(string)  # remove non alphanumeric charactersprint(str_replace_all(string, "[^[:alnum:]]", ""))
Output:
[1] "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"
[1] "a37935fguiegfkeuVYVJTFYJ"
Example 2: Remove the punctuations from the string
Syntax: str_replace_all(string, “[[:punct:]]”, “”)
Where, [[:punct:]: This will remove the punctuations from the string
R
# load the stringr packagelibrary("stringr")  # stringstring = "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"  # display original stringprint(string)  # remove punctuations charactersprint(str_replace_all(string, "[[:punct:]]", ""))
Output:
[1] "a37935fguiegfkeu#$^VYVJ&(*&TFYJ"
[1] "a37935fguiegfkeu$^VYVJTFYJ"
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
How to create a constructor reference for an array in Java?

A constructor reference is similar to method reference except that the name of a method is new. We can also create a constructor reference with an array type. For instance, if we need to create an integer array by using the constructor reference: int[]:: new, where the parameter is a length of an array.
ArrayTypeName[]::new
@FunctionalInterface
interface ArrayCreator {
   int[] makeArray(int number);
}
public class ArrayConstructorRefTest {
   public static void main(String[] args) {
      ArrayCreator arrayCreator = int[]::new;   // Constructor Reference for an Array
      int[] intArray = arrayCreator.makeArray(10);
      for(int i = 0; i < intArray.length; i++) {
         intArray[i] = i * i - i / 2;
         System.out.println("[" + i + "] = " + intArray[i]);
      }
   }
}
[0] = 0
[1] = 1
[2] = 3
[3] = 8
[4] = 14
[5] = 23
[6] = 33
[7] = 46
[8] = 60
[9] = 77
Tryit Editor v3.7

Tryit: Using the object-position property