code-rag-bench/online-tutorials huggingface dataset:
How to use the ValidateCount attribute in PowerShell Function?

The validateCount attribute in PowerShell function is to validate the length of an array, which means
that you can pass the specific number of arguments into the parameter. In the below example we need array should contain a minimum 1 and maximum 4 values when we pass the values. For that, we will
write the below script,
Function ValidateArray {
   Param (
      [ValidateCount(1,3)]
      [String[]]$Animals
   )
   return $PSBoundParameters
}
PS C:\> ValidateArray -Animals Cow, Dog, Cat
Key Value
--- -----
Animals {Cow, Dog, Cat}
The above output is valid but when we pass the null or 4 values, it becomes invalid because we have
declared an array should have a length between 1 to 3.
PS C:\> ValidateArray -Animals @()
ValidateArray: Cannot validate argument on parameter 'Animals'. The parameter req
uires at least 1 value(s) and no more than 3 value(s) - 0 value(s) were provided.
PS C:\> ValidateArray -Animals Cow, Dog, Cat, Tiger
ValidateArray: Cannot validate argument on parameter 'Animals'. The parameter req
uires at least 1 value(s) and no more than 3 value(s) - 4 value(s) were provided.
Explain unformatted input and output functions in C language

Unformatted input and output functions read a single input sent by the user and permits to display the value as the output at the console.
The unformatted input functions in C programming language are explained below −
It reads a character from the keyboard.
The syntax of getchar() function is as follows −
Variablename=getchar();
For example,
Char a;
a = getchar();
Following is the C program for getchar() function −
 Live Demo
#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("file.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("file.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){
      if(fp){
         char word[100];
         while(fscanf(fp,"%s",word)!=EOF) // read words from file{
            printf("%s\n", word); // print each word on separate lines.
         }
         fclose(fp); // close file.
      }else{
         printf("file doesnot exist");
         // then tells the user that the file does not exist.
      }
   }
   return 0;
}
When the above program is executed, it produces the following result −
enter the text then press cntrl Z:
This is an example program on getchar()
^Z
text on the file:
This
is
an
example
program
on
getchar()
It reads a string from the keyboard
The syntax for gets() function is as follows −
gets(variablename);
 Live Demo
#include<stdio.h>
#include<string.h>
main(){
   char str[10];
   printf("Enter your name: \n");
   gets(str);
   printf("Hello %s welcome to Tutorialspoint", str);
}
Enter your name:
Madhu
Hello Madhu welcome to Tutorialspoint
The unformatted output functions in C programming language are as follows −
It displays a character on the monitor.
The syntax for putchar() function is as follows −
Putchar(variablename);
For example,
Putchar(‘a’);
It displays a string on the monitor.
The syntax for puts() function is as follows −
puts(variablename);
For example,
puts("tutorial");
Following is the C program for putc and getc functions −
 Live Demo
#include <stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w");
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){
      putchar(ch);
   }
   fclose(fp);
   return 0;
}
When the above program is executed, it produces the following result −
enter the text.press cntrl Z:
This is an example program on putchar()
^Z
text on the file:
This is an example program on putchar()
Java Concurrency - Executor Interface

A java.util.concurrent.Executor interface is a simple interface to support launching new tasks.
void execute(Runnable command)
Executes the given command at some time in the future.
The following TestThread program shows usage of Executor interface in thread based environment.
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      Executor executor = Executors.newCachedThreadPool();
      executor.execute(new Task());
      ThreadPoolExecutor pool = (ThreadPoolExecutor)executor;
      pool.shutdown();
   }  

   static class Task implements Runnable {
      
      public void run() {
         
         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed");
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}
This will produce the following result.
Running Task!
Task Completed


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Count number of occurrences for each char in a string with JavaScript?

Take an array to store the frequency of each character. If similar character is found, then
increment by one otherwise put 1 into that array.
Let’s say the following is our string −
var sentence = "My name is John Smith";
Following is the JavaScript code to count occurrences −
var sentence = "My name is John Smith";
sentence=sentence.toLowerCase();
var noOfCountsOfEachCharacter = {};
var getCharacter, counter, actualLength, noOfCount;
for (counter = 0, actualLength = sentence.length; counter <
actualLength; ++counter) {
   getCharacter = sentence.charAt(counter);
   noOfCount = noOfCountsOfEachCharacter[getCharacter];
   noOfCountsOfEachCharacter[getCharacter] = noOfCount ? noOfCount + 1: 1;
}
for (getCharacter in noOfCountsOfEachCharacter) {
   if(getCharacter!=' ')
   console.log("Character="+getCharacter + " Occurrences=" +
   noOfCountsOfEachCharacter[getCharacter]);
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo40.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo40.js
Character=m Occurrences=3
Character=y Occurrences=1
Character=n Occurrences=2
Character=a Occurrences=1
Character=e Occurrences=1
Character=i Occurrences=2
Character=s Occurrences=2
Character=j Occurrences=1
Character=o Occurrences=1
Character=h Occurrences=2
Character=t Occurrences=1
How to create a column with binary variable based on a condition of other variable in an R data frame?

Sometimes we need to create extra variable to add more information about the present data because it adds value. This is especially used while we do feature engineering. If we come to know about something that may affect our response then we prefer to use it as a variable in our data, hence we make up that with the data we have. For example, creating another variable applying conditions on other variable such as creating a binary variable for goodness if the frequency matches a certain criterion.
Consider the below data frame −
 Live Demo
set.seed(100)
Group<-rep(c("A","B","C","D","E"),times=4)
Frequency<-sample(20:30,20,replace=TRUE)
df1<-data.frame(Group,Frequency)
df1
 Group Frequency
1  A    29
2  B    26
3  C    25
4  D    22
5  E    28
6  A    29
7  B    26
8  C    25
9  D    25
10 E    23
11 A    26
12 B    25
13 C    21
14 D    26
15 E    26
16 A    26
17 B    30
18 C    27
19 D    21
20 E    22
Creating a column category having two levels as Good and Bad, where Good is for those that have Frequency greater than 25−
df1$Category<-ifelse(df1$Frequency>25,"Good","Bad")
df1
 Group Frequency Category
1  A       29       Good
2  B       26       Good
3  C       25       Bad
4  D       22       Bad
5  E       28       Good
6  A       29       Good
7  B       26       Good
8  C       25       Bad
9  D       25       Bad
10 E       23       Bad
11 A       26       Good
12 B       25       Bad
13 C       21       Bad
14 D       26       Good
15 E       26       Good
16 A       26       Good
17 B       30       Good
18 C       27       Good
19 D       21       Bad
20 E       22       Bad
Let’s have a look at another example −
 Live Demo
Class<-rep(c("Lower","Middle","Upper Middle","Higher"),times=5)
Ratings<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Ratings)
df2
     Class    Ratings
1    Lower       3
2    Middle      8
3 Upper Middle   2
4    Higher      9
5    Lower       2
6    Middle      3
7 Upper Middle   4
8    Higher      4
9    Lower       4
10   Middle      5
11 Upper Middle  7
12    Higher     9
13    Lower      4
14    Middle     2
15 Upper Middle  6
16    Higher     7
17    Lower      1
18    Middle     6
19 Upper Middle  9
20    Higher     9
df2$Group<-ifelse(df2$Ratings>5,"Royal","Standard")
df2
      Class    Ratings    Group
1    Lower       3       Standard
2    Middle      8         Royal
3 Upper Middle   2       Standard
4    Higher      9         Royal
5    Lower       2       Standard
6    Middle      3       Standard
7 Upper Middle   4       Standard
8    Higher      4       Standard
9    Lower       4       Standard
10   Middle      5       Standard
11 Upper Middle  7         Royal
12    Higher     9         Royal
13    Lower      4       Standard
14    Middle     2       Standard
15 Upper Middle  6         Royal
16    Higher     7         Royal
17    Lower      1       Standard
18    Middle     6         Royal
19 Upper Middle  9         Royal
20    Higher     9         Royal
Alternatively merging two arrays - JavaScript

We are required to write a JavaScript function that takes in two arrays and merges the arrays taking elements alternatively from the arrays.
For example −
If the two arrays are −
const arr1 = [4, 3, 2, 5, 6, 8, 9];
const arr2 = [2, 1, 6, 8, 9, 4, 3];
Then the output should be −
const output = [4, 2, 3, 1, 2, 6, 5, 8, 6, 9, 8, 4, 9, 3];
Following is the code −
const arr1 = [4, 3, 2, 5, 6, 8, 9];
const arr2 = [2, 1, 6, 8, 9, 4, 3];
const mergeAlernatively = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length + arr2.length; i++){
      if(i % 2 === 0){
         res.push(arr1[i/2]);
      }else{
         res.push(arr2[(i-1)/2]);
      };
   };
   return res;
};
console.log(mergeAlernatively(arr1, arr2));
This will produce the following output in console −
[
   4, 2, 3, 1, 2, 6,
   5, 8, 6, 9, 8, 4,
   9, 3
]
Subquery in SQL

A subquery is a query within a query i.e a nested query. It is placed inside a query and its result is used to further evaluate the outer query.
There are some rules that a subquery must follow in SQL. Some of these are −
The subquery should be placed within parenthesis.
The subquery can be used with different operators like <,>,<=,>=, IN,BETWEEN etc. Also operators like SELECT, INSERT, DELETE, UPDATE etc. be used.
The ORDER BY operator cannot be used in the subquery. However, it can be there in the main query.
A subquery cannot be written with a BETWEEN operator. But the subquery can contain the BETWEEN operator.
The subquery that returns more than one row cannot be used with all the operators. It can only be used with operators that accept multiple values like IN.
An example of subqueries in SQL is −
<Student>
Select *
from student
where student_marks IN( select student_marks from student where student_marks>50)
This query will return details about all the students who have more than 50 marks i.e. Andrew, Sara and Megan.
tclsh - Unix, Linux Command

\L’|0u-1v’\l’75u+3n_’\L’0u+1v-0u’\l’|0u-1.5n_’


\L’|0u-1v’\L’0u+1v-0u’\l’|0u-1.5n_’






Tclsh is a shell-like application that reads Tcl commands
from its standard input or from a file and evaluates them.
If invoked with no arguments then it runs interactively, reading
Tcl commands from standard input and printing command results and
error messages to standard output.
It runs until the exit command is invoked or until it
reaches end-of-file on its standard input.
If there exists a file .tclshrc (or tclshrc.tcl on
the Windows platforms) in the home directory of
the user, tclsh evaluates the file as a Tcl script
just before reading the first command from standard input.




If tclsh is invoked with arguments then the first argument
is the name of a script file and any additional arguments
are made available to the script as variables (see below).
Instead of reading commands from standard input tclsh will
read Tcl commands from the named file;  tclsh will exit
when it reaches the end of the file.



The end of the file may be marked either by the physical end of
the medium, or by the character, ’\032’ (’\u001a’, control-Z).
If this character is present in the file, the tclsh application
will read text up to but not including the character.  An application
that requires this character in the file may safely encode it as
‘‘\032’’, ‘‘\x1a’’, or ‘‘\u001a’’; or may generate it by use of commands
such as format or binary.



   
\L’|0u-1v|’





If you create a Tcl script in a file whose first line is

#!/usr/local/bin/tclsh


An even better approach is to start your script files with the
following three lines:

#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"





You should note that it is also common practise to install tclsh with
its version number as part of the name.  This has the advantage of
allowing multiple versions of Tcl to exist on the same system at once,
but also the disadvantage of making it harder to write scripts that
start up uniformly across different versions of Tcl.



   
\L’|0u-1v|’







Tclsh sets the following Tcl variables:




When tclsh is invoked interactively it normally prompts for each
command with ‘‘% ’’.  You can change the prompt by setting the
variables tcl_prompt1 and tcl_prompt2.  If variable
tcl_prompt1 exists then it must consist of a Tcl script
to output a prompt;  instead of outputting a prompt tclsh
will evaluate the script in tcl_prompt1.
The variable tcl_prompt2 is used in a similar way when
a newline is typed but the current command isn’t yet complete;
if tcl_prompt2 isn’t set then no prompt is output for
incomplete commands.




See Tcl_StandardChannels for more explanations.






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
Python String rfind() Method

Python string  method rfind() returns the last index where the substring str is found, or -1 if no such index exists, optionally restricting the search to string[beg:end].
Following is the syntax for rfind() method −
obj.rfind(str, beg=0 end=len(string))

str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
end − This is the ending index, by default its equal to the length of the string.
This method returns last index if found and -1 otherwise.
The following example shows the usage of rfind() method.
#!/usr/bin/python

str1 = "this is really a string example....wow!!!";
str2 = "is";

print str1.rfind(str2)
print str1.rfind(str2, 0, 10)
print str1.rfind(str2, 10, 0)

print str1.find(str2)
print str1.find(str2, 0, 10)
print str1.find(str2, 10, 0)
When we run above program, it produces following result −
5
5
-1
2
2
-1


    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
Create Directory or Folder with C/C++ Program

In this tutorial, we will be discussing a program to create directory or folder with C/C++ program.
To create a new directory we will be using the mkdir() command. Note that the given code will work only for windows compiler.
#include <conio.h>
#include <dir.h>
#include <process.h>
#include <stdio.h>
void main(){
   int check;
   char* dirname = "tutorialspoint";
   clrscr();
   check = mkdir(dirname);
   //checking if directory is created
   if (!check)
      printf("Directory created\n");
   else {
      printf("Unable to create directory\n");
      exit(1);
   }
   getch();
   system("dir/p");
   getch();
}
Directory created
Stream Editor - Pattern Range

In the previous chapter, we learnt how SED handles an address range. This chapter covers how SED takes care of a pattern range. A pattern range can be a simple text or a complex regular expression. Let us take an example. The following example prints all the books of the author Paulo Coelho.
[jerry]$ sed -n '/Paulo/ p' books.txt

On executing the above code, you get the following result:
3) The Alchemist, Paulo Coelho, 197 
5) The Pilgrimage, Paulo Coelho, 288

In the above example, the SED operates on each line and prints only those lines that match the string Paulo.
We can also combine a pattern range with an address range. The following example prints lines starting with the first match of Alchemist until the fifth line.
[jerry]$ sed -n '/Alchemist/, 5 p' books.txt

On executing the above code, you get the following result:
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

We can use the Dollar($) character to print all the lines after finding the first occurrence of the pattern. The following example finds the first occurrence of the pattern The and immediately prints the remaining lines from the file
[jerry]$ sed -n '/The/,$ p' books.txt

On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

We can also specify more than one pattern ranges using the comma(,) operator. The following example prints all the lines that exist between the patterns Two and Pilgrimage.
[jerry]$ sed -n '/Two/, /Pilgrimage/ p' books.txt 

On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288

Additionally, we can use the plus(+) operator within a pattern range. The following example finds the first occurrence of the pattern Two and prints the next 4 lines after that.
[jerry]$ sed -n '/Two/, +4 p' books.txt

On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352 
3) The Alchemist, Paulo Coelho, 197 
4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
5) The Pilgrimage, Paulo Coelho, 288 
6) A Game of Thrones, George R. R. Martin, 864 

We have supplied here only a few examples to get you acquainted with SED. You can always get to know more by trying a few examples on your own.

    53 Lectures 
     3.5 hours 

 Senol Atac

    14 Lectures 
     44 mins

 Zach Miller

    13 Lectures 
     2 hours 

 Sandip Bhattacharya

    28 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    16 Lectures 
     1.5 hours 

 Taurius Litvinavicius

    38 Lectures 
     2 hours 

 Davida Shensky
 Print
 Add Notes
 Bookmark this page
Controlling a Stepper Motor with Arduino

A stepper motor divides the full rotation into a number of discrete steps, ranging from as low as 12 to as high as 200 steps per revolution (corresponding to angles of 30 degrees per step to 1.8 degrees per step). While a DC motor rotates continuously, a stepper motor rotates discretely, in step angles.
The circuit diagram and the required components for both Unipolar and Bipolar stepper motors can be found here − https://www.arduino.cc/en/Tutorial/LibraryExamples/StepperOneRevolution
Note that the stepper motor is connected to pins 8-11 of Arduino Uno, via a Darlington Array (for unipolar stepper) or H-bridge (for bipolar stepper). The stepper motor is powered using an external supply as it draws too much power to be directly powered from the Arduino board.
We will be walking through an example code. Go to File → Examples → Stepper → stepper_oneRevolution.
Alternatively, the code can be found on GitHub − https://github.com/arduinolibraries/Stepper/blob/master/examples/stepper_oneRevolution/stepper_oneRevolution.ino
Through this code, we make the stepper motor rotate one revolution in one direction, and another revolution in the opposite direction.
We begin with the inclusion of the Stepper library and defining the number of steps per revolution (change this according to the specification of your stepper motor)
#include <Stepper.h>

const int stepsPerRevolution = 200;
Next, we initialize the Stepper object using the stepsPerRevolution and the four pins of the Arduino which are connected to the Stepper motor.
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
Within the setup, we set the speed of the stepper motor in RPM, and initialize Serial.
void setup() {
   // set the speed at 60 rpm:
   myStepper.setSpeed(60);
   // initialize the serial port:
   Serial.begin(9600);
}
Within the loop, we make the motor step stepsPerRevolution in one direction, and then step stepsPerRevolution in the opposite direction (by just appending a negative sign)
void loop() {
   // step one revolution in one direction:
   Serial.println("clockwise");
   myStepper.step(stepsPerRevolution);
   delay(500);

   // step one revolution in the other direction:
   Serial.println("counterclockwise");
   myStepper.step(-stepsPerRevolution);
   delay(500);
}
Function Pointer in C

Function Pointers point to code like normal pointers.
In Functions Pointers, function’s name can be used to get function’s address.
A function can also be passed as an arguments and can be returned from a function.
function_return_type(*Pointer_name)(function argument list)
 Live Demo
#include<stdio.h>
int subtraction (int a, int b) {
   return a-b;
}
int main() {
   int (*fp) (int, int)=subtraction;
   //Calling function using function pointer
   int result = fp(5, 4);
   printf(" Using function pointer we get the result: %d",result);
   return 0;
}
Using function pointer we get the result: 1
How to generate sequences in Python?

List comprehensions in python are useful for such tasks. These are very powerful expressions that you can use to generate sequences in a very concise and efficient manner. For example, if you want first 100 integers from 0, you can use −
a = [i for i in range(100)]
print(a)
This will give the output −
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Want the squares for first 10 even numbers? You can get it using −
a = [i * i for i in range(20) if i % 2 == 0]
print(a)
This will give the output −
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
These expressions can get much more powerful once you know how to use them.
Web Scrapping using cURL in PHP - GeeksforGeeks

19 Jan, 2022
We all have tried getting data from a website in many ways. In this article, we will learn how to web scrape using bots to extract content and data from a website. 
We will use PHP cURL to scrape a web page, it looks like a typo from leaving caps lock on, but that’s really how you write it. cURL is the system used to make HTTP requests with PHP. It is the way of calling web pages from within your script.
The “Scrape Data, Not Content” this statement is for all the people who want to learn web scraping. cURL and web scraping are powerful tools that can be used to automate what would otherwise be somewhat long and tedious repetitive tasks. We should only scrape information, not full articles and content.
Example: The following example demonstrates the scraping of images from the article https://www.geeksforgeeks.org/matlab-data-types/ 
PHP
<?php // Initialize curl$ch = curl_init(); // URL for Scrapingcurl_setopt($ch, CURLOPT_URL,    'https://www.geeksforgeeks.org/matlab-data-types/'); // Return Transfer Truecurl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); // Closing cURLcurl_close($ch); // For web page displayecho '<head>';echo '<meta http-equiv="content-type"    content="text/html; charset=utf-8" />';echo '</head>';echo '<body>'; echo '<h1>Web Scraping using cURL</h1>'; // Checking for imagespreg_match_all('!https://media.geeksforgeeks.org/wp-content/uploads/(.*)/(.*).png!',    $output, $data); foreach ($data[0] as $list) {    echo "<img src='$list'/>";} echo '</body>'; ?>
Output:
web scrape
sagartomar9927
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need 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?
Python strftime() function

15 Mar, 2021
The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.
Syntax :
strftime(format)

Returns : It returns the string representation of the date or time object.
List of format codes : Reference table for the format codes.
Example:
# Python program to demonstrate# strftime() function    from datetime import datetime as dt  # Getting current date and timenow = dt.now()print("Without formatting", now)  # Example 1s = now.strftime("%a %m %y")print('\nExample 1:', s)  # Example 2s = now.strftime("%A %-m %Y")print('\nExample 2:', s)  # Example 3s = now.strftime("%-I %p %S")print('\nExample 3:', s)  # Example 4s = now.strftime("%-j")print('\nExample 4:', s)
Output:
Without formatting 2019-12-17 18:21:39.211378

Example 1: Tue-12-19

Example 2: Tuesday-12-2019

Example 3: 6 PM 39

Example 4: 351

Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Inserting Records in Batch Using JDBC

07 Jul, 2021
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the database’s website. Considering the example of the MySQL database, you will need to go to the MySQL website, download the MySQL JDBC driver .jar file (also called Connector/J), and add it to your project.
Now let’s discuss the methods that they operate on. So, the above two methods namely addBatch() and executeBatch() method is as follows:
Method 1: addBatch()
This method adds the parameter values to the batch internally. You can now add another set of values, to be inserted into the SQL statement. Each set of parameters are inserted into the SQL and executed separately, once the full batch is sent to the database.
Method 2: executeBatch()
This method is called, which executes all the batch updates. The SQL statement plus the parameter sets are sent to the database in one go. The int[] array returned by the executeBatch() method is an array of int telling how many records were affected by each executed SQL statement in the batch.
Syntax: Creation of the database 
create table emp(eid varchar(200) unique,ename varchar(200)
Example:
Java
// Step 1: Importing DB(SQL) classesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement; // Classpublic class insertion {     // Main driver method    public static void main(String[] args) throws Exception    {         // Try block to check for exceptions        try {            // Step 2: Loading and registering drivers             // Loading drivers using forName() method            Class.forName("com.mysql.jdbc.Driver");             // Registering driver using DriverManager            Connection con = DriverManager.getConnection(                "jdbc:mysql://localhost/test", "root", "");             // Step 3: Create a statement            Statement st = con.createStatement();            String sql                = "insert into emp (eid,ename) values (?, ?)";             // Step 4: Execute the query            PreparedStatement pstmt;            pstmt = con.prepareStatement(sql);            final int batchSize = 5000;            int count = 0;            for (int i = 4000; i <= 4500; i++) {                 pstmt.setString(1, "181FA0" + i);                pstmt.setString(2, "181FA0" + i);                 pstmt.addBatch();                 count++;                 if (count % batchSize == 0) {                    System.out.println("Commit the batch");                    pstmt.executeBatch();                }                pstmt.executeBatch();            }        }        catch (Exception e) {            System.out.println("Error:" + e.getMessage());        }    }}
 
 
Output:
 
 
simranarora5sos
JDBC
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Compare Time in MS SQL Server?

03 Jun, 2021
Here, we are going to see how to Compare Time in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database.
Here, we will first create a database named “geeks”. After, that we will execute our query on that database.
CREATE DATABASE geeks;
USE geeks;
Here, we could create two variables of datetime, that we need to compare.
Syntax:
declare  @input1 datetime;
declare  @input2 datetime;
select   @input1 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)
select   @input2 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)

if @input1 <= @input2
  print '@input1 less then @input2'
else
  print '@input1 more then @input2'
In MS SQL Server the query can be designed to compare two or more datetime variables using just the “if” statements.
Example:
declare  @day1 datetime;
declare  @day2 datetime;
select   @day1 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
select   @day2 = CONVERT(varchar(20),CONVERT(datetime, '2020-02-11 08:00:00'), 114)
if @day1 <= @day2
 print '@@day1 less then @@day2'
else
 print '@@day1 more then @@day2'
Output :
@@day1 less then @@day2
The GETDATE() function in SQL can also be used to compare multiple dates.
Example:
declare  @day1 datetime;
declare  @day2 datetime;
select   @day1 = CONVERT(varchar(20),GETDATE(), 114)
select   @day2 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
if @day1 <= @day2
 print '@@day1 less then @@day2'
else
 print '@@day1 more then @@day2'
Output:
@@day1 more then @@day2
anikakapoor
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
How do we insert/store a file into MySQL database using JDBC?

In general, the contents of a file are stored under Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype in MySQL database.
JDBC provides support for the Clob datatype, to store the contents of a file in to a table in a database.
The setCharacterStream() method of the PreparedStatement interface accepts an integer representing the index of the parameter and, a Reader object as a parameter.
And sets the contents of the given reader object (file) as value to the parameter (place holder) in the specified index.
Whenever you need to send very large text value you can use this method.
If you need to store a file in a database using JDBC program create table with a Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype as shown below:
CREATE TABLE Articles(Name VARCHAR(255), Article LONGTEXT);
Now, using JDBC connect to the database and prepare a PreparedStatement to insert values into the above created table:
String query = "INSERT INTO Tutorial(Name, Article) VALUES (?,?)";PreparedStatement pstmt = con.prepareStatement(query);
Set values to the place holders using the setter methods of the PreparedStatement interface and for the Clob datatype set value using the setCharacterStream() method.
Following is an example demonstrating how to insert file
in to a MySQL database using JDBC program. Here we are have created a table with a Clob datatype, inserted values in to it.
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertingFileToDatabase {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Inserting values
      String query = "INSERT INTO Articles(Name, Article) VALUES (?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "article1");
      FileReader reader = new FileReader("E:\\data\\article1.txt");
      pstmt.setCharacterStream(2, reader);
      pstmt.execute();
      pstmt.setString(1, "article2");
      reader = new FileReader("E:\\data\\article2.txt");
      pstmt.setCharacterStream(2, reader);
      pstmt.execute();
      pstmt.setString(1, "article3");
      reader = new FileReader("E:\\data\\article3.txt");
      pstmt.setCharacterStream(2, reader);
      pstmt.execute();
      System.out.println("Data inserted......");
   }
}
Connection established......
Data inserted......
Using MySQL workbench, you can export the contents of a table to various files such as html files, .csv files text files etc. If you export the contents of the table after inserting data to a HTTML file its output will look like:
GATE | GATE CS 2012 | Question 15

09 Oct, 2019
Which of the following statements are TRUE about an SQL query?P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clauseQ : An SQL query can contain a HAVING clause only if it has a GROUP BY clauseR : All attributes used in the GROUP BY clause must appear in the SELECT clauseS : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause
(A) P and R(B) P and S(C) Q and R(D) Q and SAnswer: (B)Explanation: According to standard SQL answer should be option (C) which is answer key given by GATE authority.
If we talk about different SQL implementations like MySQL, then option (B) is also right. But in question they seem to be talking about standard SQL not about implementation. For example below is a
P is correct in most of the implementations. HAVING clause can also be used with aggregate function. If we use a HAVING clause without a GROUP BY clause, the HAVING condition applies to all rows that satisfy the search condition. In other words, all rows that satisfy the search condition make up a single group. See this for more details.
S is correct . To verify S, try following queries in SQL.
CREATE TABLE temp 
  ( 
     id   INT, 
     name VARCHAR(100) 
  ); 

INSERT INTO temp VALUES (1, "abc"); 
INSERT INTO temp VALUES (2, "abc"); 
INSERT INTO temp VALUES (3, "bcd"); 
INSERT INTO temp VALUES (4, "cde"); 

SELECT Count(*) 
FROM   temp 
GROUP  BY name; 

Output:
count(*)
--------
2
1
1

Alternative way –
Statement (P) “An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause” is correct because Having caluse is applied after the aggregation phase and must be used if you want to filter aggregate results and Having doesn’t require Group By clause. A HAVING clause without a GROUP BY clause is valid and (arguably) useful syntax in Standard SQL. Consider this example, which is valid Standard SQL:
 SELECT 'T' AS result
   FROM Book
 HAVING MIN(NumberOfPages) < MAX(NumberOfPages);

Statement (S) "Not all attributes used in the GROUP BY clause need to appear in the SELECT clause" is correct but if we use Group By clause must, there are limitations on what we can put into the Select clause.
Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
DBMS Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.max() Method

02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.max() method is used to find the maximum element from the array. If the array is empty then undefined is returned.
Syntax:
_.max( array )
Parameters: This method accepts a single parameter as mentioned above and described below:
array: It is the array that the method iterates over to get the maximum element.
Return Value: This method returns the maximum element from the array.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.max() method let max_val = _.max([]);         // Printing the output  console.log(max_val);
Output:
undefined
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.max() method let max_val = _.max([15, 7, 38, 46, 82]);         // Printing the output  console.log(max_val);
Output:
82
Example 3:  
Javascript
// Requiring the lodash library  const _ = require("lodash");      // Use of _.max() method let max_val = _.max([-15, 7, 38, -46, -82]);         // Printing the output  console.log(max_val);
Output:
38
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
PHP | DOMXPath evaluate() Function

13 Jul, 2021
The DOMXPath::evaluate() function is an inbuilt function in PHP which is used to execute the given XPath expression which is a pattern defined to select a set of nodes.Syntax:  
mixed DOMXPath::evaluate( string $expression, 
          DOMNode $contextnode, bool $registerNodeNS )
Parameters: This function accept three parameters as mentioned above and described below:  
$expression: It specifies the XPath expression to execute.
$contextnode (Optional): It specifies the contextnode for doing relative XPath queries. By default, the queries are relative to the root element.
$registerNodeNS (Optional): It specifies whether to disable automatic registration of the context node.
Return Value: This function returns TRUE on success.Exceptions: This function throws DOMXPathException on error.Below examples illustrate the DOMXPath::evaluate() function in PHP:Example 1:  
php
<?php  // Create a new DOMDocument instance$document = new DOMDocument();  // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><bookstore><book>  <title lang="en">GeeksforGeeks</title>  <price>400</price></book><book>  <title lang="en">Intro to XML</title>  <price>300</price></book></bookstore>XML;  // Load the XML$document->loadXML($xml);  // Create a new DOMXPath instance$xpath = new DOMXPath($document);  // Get the$tbody = $document->    getElementsByTagName('bookstore')->item(0);  // Query to get the number of titles with lang// attribute "en"$query = 'count(//title[@lang=\'en\'])';  // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo "Number of elements with lang = \"en\": $entries\n";?>
Output:  
Number of elements with lang = "en": 2
Example 2:  
php
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><GeeksforGeeks>  Keep Learning.</GeeksforGeeks>XML; // Load the XML$document->loadXML($xml); // Create a new DOMXPath instance$xpath = new DOMXPath($document); // Get the$tbody = $document->getElementsByTagName('GeeksforGeeks')->item(0); // Get the element with name GeeksforGeeks$query = '//GeeksforGeeks'; // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo $entries[0]->nodeValue;?>
Output:  
Keep Learning.
Reference: https://www.php.net/manual/en/domxpath.evaluate.php 
sagar0719kumar
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to programmatically fire a click event for a file input element in JavaScript ?

17 Feb, 2021
In this article, we will learn how to programmatically fire click events on the input file element.
Approach: Whenever you want to perform a click event programmatically, at your specific condition, just use JavaScript in-built click() function by DOM object. For example:
document.getElementById('your_input_type_file_element_id').click();
Example 1: We want to click the input file element automatically (programmatically). When the user clicks one button which is not the ‘file upload’ button of the input type file element, we can achieve it by using the following code.
HTML
<!DOCTYPE html><html><script type="text/javascript">  function open_file(){      document.getElementById('input_file').click();  }</script><body>    <input type="file" name="" id='input_file' hidden>    <button onclick="open_file()">      click event fire programmatically for input       type file element    </button></body></html>
Output:The input file type is hidden so whenever you run this code, you easily get the select dialog for file selection. After clicking the above button, we get the file select dialog box like the one below the image.
Example 2: For example, when a user registers for your service, it registers with email, username, and password, etc. Whenever a user registers successfully you give them one secret key by email or SMS. The user enters this secret in the input box on a specific page after which they are able to choose document/ image whatever needed for them.
HTML
<!DOCTYPE html><html>    <head>        <script type="text/javascript">        function open_file() {            var secret_key = document.getElementById("secret_key").value;            if (secret_key == "Geeksforgeeks") {                                // 'Geeksforgeeks' this value is just an example for                 // your understanding.                document.getElementById("input_file").click();            }        }        </script>    </head>    <body>        <p>Write down 'Geeksforgeeks'</p>        <label>Enter Secret Key :</label>        <input type="text" name="username"                id="secret_key" oninput="open_file()" />        <input type="file" name="" id="input_file" hidden />    </body></html>
Output: After entering the correct secret key into the input box, the file select dialog box will pop up. AJAX request is generated and it matches that user key to the original key via backend files.
JavaScript-Questions
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas.Categorical()

10 Mar, 2022
pandas.Categorical(val, categories = None, ordered = None, dtype = None) : It represents a categorical variable. Categorical are a pandas data type that corresponds to the categorical variables in statistics. Such variables take on a fixed and limited number of possible values. For examples – grades, gender, blood group type etc. Also, in the case of categorical variables, logical order is not the same as categorical data e.g. “one”, “two”, “three”. But the sorting of these variables uses logical order.  
Parameters- val        : [list-like] The values of categorical. 
categories : [index like] Unique categorisation of the categories. 
ordered    : [boolean] If false, then the categorical is treated as unordered. 
dtype      : [CategoricalDtype] an instance. 

Error- ValueError :  If the categories do not validate. 
TypeError  :  If an explicit ordered = True but categorical can't be sorted. 

Return- Categorical variable
Code: 
Python3
# Python code explaining# numpy.pandas.Categorical() # importing librariesimport numpy as npimport pandas as pd # Categorical using dtypec = pd.Series(["a", "b", "d", "a", "d"], dtype ="category")print ("\nCategorical without pandas.Categorical() : \n", c)  c1 = pd.Categorical([1, 2, 3, 1, 2, 3])print ("\n\nc1 : ", c1) c2 = pd.Categorical(['e', 'm', 'f', 'i',                     'f', 'e', 'h', 'm' ])print ("\nc2 : ", c2)
Output :  
   
Python3
# Ordered = Truec3 = pd.Categorical(['e', 'm', 'f', 'i',                     'f', 'e', 'h', 'm' ], ordered = True)print ("\nc3 : ", c3)
Output :  
   
Python3
# Mixed categoriesc4 = pd.Categorical(['a', 2, 3, 1, 2, 3])print ("\nc4 : ", c4) c5 = pd.Categorical(['a', 2, 3, 1, 2, 3], ordered = True)print ("\nc5 : ", c5)
Output :  
   
Python3
# using categories attributec6 = pd.Categorical([1, 2, 3, 1, 2, 3], categories = [4, 1, 3, 5])print ("\nc6 : ", c6) print("\n\nSeries : \n", pd.Series(c6)) df = pd.DataFrame({"A":[1, 2, 3, 1, 2, 3]})df["B"] = c6print ("\n\nDataframe : \n", df)
Output :  
 
sooda367
rkbhola5
Python pandas-datatypes
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python