code-rag-bench/online-tutorials huggingface dataset:
JavaScript - Date setFullYear() Method

Javascript date setFullYear() method sets the full year for a specified date according to local time.
Its syntax is as follows −
Date.setFullYear(yearValue[, monthValue[, dayValue]])

yearValue − An integer specifying the numeric value of the year, for example, 2008.
yearValue − An integer specifying the numeric value of the year, for example, 2008.
monthValue − An integer between 0 and 11 representing the months January through December.
monthValue − An integer between 0 and 11 representing the months January through December.
dayValue − An integer between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue.
dayValue − An integer between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue.
If you do not specify the monthValue and dayValue parameters, the values returned from the getMonth and getDate methods are used.
Try the following example.
<html>
   
   <head>
      <title>JavaScript setFullYear Method</title>
   </head>
   
   <body>
      
      <script type = "text/javascript">
         var dt = new Date( "Aug 28, 2008 23:30:00" );
         dt.setFullYear( 2000 );
         document.write( dt );
      </script>
      
   </body>
</html>
Mon Aug 28 2000 23:30:00 GMT+0530 (India Standard Time) 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Birthday Paradox in Python

The birthday paradox is a very famous problem in the section of probability.
Problem Statement − There are several people at a birthday party, some are having the same birthday collision. We need to find the approximate number of people at a birthday party on the basis of having the same birthday.
In the probability, we know that the chance of getting ahead is 1/2, same as if we have some coins, the chance of getting 10 heads is 1/100 or 0.001.
Let us understand the concept.
The chance of two people having the different birthday is 364365 which is ⟮1−1365⟯ in a Non-leap year.
Thus, we can say that the first person having the probability of a specific birthday is ‘1’ and for others, it would be different which is,
P(different) = 1×⟮1−1365⟯×⟮1−2365⟯×⟮1−3365⟯×⟮1−4365⟯...
Thus,
P(same) = 1 − P(different)
For example, the number of people having the same birthday for which probability is 0.70.
N = √2 × 365 × log(1-1/p)
N = √2 × 365 × log(1-1/0.70) = 30
Thus, the total approximate no. of people having the same birthday is 30.
 Live Demo
import math
def findPeople(p):
   return math.ceil(math.sqrt(2*365*math.log(1/(1-p))))
print(findPeople(0.70))
Running the above code will generate the output as,
30
CharsetEncoder encode(CharBuffer in) method in Java with Examples - GeeksforGeeks

10 Jan, 2022
The encode(CharBuffer input) method is a built-in method of the java.nio.charset.CharsetEncoder which encodes the content which is remaining of a single input character buffer to a newly-allocated byte-buffer. The encode() method in itself implements an entire operation of encoding. This function should not be invoked if the operation is in progress.
Syntax:
public final ByteBuffer encode(CharBuffer input)
Parameters: The function accepts a mandatory parameter input which specifies the input character buffer.
Return Value: The function returns a newly-allocated byte buffer containing the result of the encoding operation.
Error and Exceptions: The function throws four exceptions which can be described as below:
IllegalStateException: It is thrown if an encoding operation is already in progress.
MalformedInputException: It is thrown if the character sequence starting at the input buffer’s current position is not a legal sixteen-bit Unicode sequence and the current malformed-input action is CodingErrorAction.REPORT.
UnmappableCharacterException: It is thrown if the character sequence starting at the input buffer’s current position cannot be mapped to an equivalent byte sequence and the current unmappable-character action is CodingErrorAction.REPORT
CharacterCodingException
Below is the implementation of the above function:
Program 1:
Java
// Java program to implement// the above functionimport java.nio.CharBuffer;import java.nio.charset.Charset;import java.nio.charset.CharsetEncoder;  public class Main {    public static void main(String[] args) throws Exception    {          // Gets the new encoder        CharsetEncoder encoder = Charset.forName("UTF8").newEncoder();          // Encodes        String res = "gfggfg";        System.out.println(encoder.encode(CharBuffer.wrap(res)));    }}
java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]

Program 2:
Java
// Java program to implement// the above functionimport java.nio.CharBuffer;import java.nio.charset.Charset;import java.nio.charset.CharsetEncoder;  public class Main {    public static void main(String[] args) throws Exception    {          // Gets the new encoder        CharsetEncoder encoder = Charset.forName("UTF16").newEncoder();          // Encodes        String res = "gopal";        System.out.println(encoder.encode(CharBuffer.wrap(res)));    }}
java.nio.HeapByteBuffer[pos=0 lim=12 cap=21]

The exception programs cannot be demonstrated in programs.
Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/CharsetEncoder.html#encode(java.nio.CharBuffer)
varshagumber28
Java-CharsetEncoder
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
“extern” keyword in C

External variables are also known as global variables. These variables are defined outside the function. These variables are available globally throughout the function execution. The value of global variables can be modified by the functions. “extern” keyword is used to declare and define the external variables.
Scope − They are not bound by any function. They are everywhere in the program i.e. global.
Default value − Default initialized value of global variables are Zero.
Lifetime − Till the end of the execution of the program.
Here are some important points about extern keyword in C language,
External variables can be declared number of times but defined only once.
External variables can be declared number of times but defined only once.
“extern” keyword is used to extend the visibility of function or variable.
“extern” keyword is used to extend the visibility of function or variable.
By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy.
By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy.
Variables with “extern” keyword are only declared not defined.
Variables with “extern” keyword are only declared not defined.
Initialization of extern variable is considered as the definition of the extern variable.
Initialization of extern variable is considered as the definition of the extern variable.
Here is an example of extern variable in C language
 Live Demo
#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
   auto int a = 28;
   extern int b;
   printf("The value of auto variable : %d\n", a);
   printf("The value of extern variables x and b : %d,%d\n",x,b);
   x = 15;
   printf("The value of modified extern variable x : %d\n",x);
   return 0;
}
The value of auto variable : 28
The value of extern variables x and b : 32,8
The value of modified extern variable x : 15
VBA - Comparison Operators

There are following comparison operators supported by VBA.
Assume variable A holds 10 and variable B holds 20, then −
Try the following example to understand all the Comparison operators available in VBA.
Private Sub Constant_demo_Click()
   Dim a: a = 10
   Dim b: b = 20
   Dim c

   If a = b Then
      MsgBox ("Operator Line 1 : True")
   Else
      MsgBox ("Operator Line 1 : False")
   End If

   If a<>b Then
      MsgBox ("Operator Line 2 : True")    
   Else
      MsgBox ("Operator Line 2 : False")    
   End If

   If a>b Then
      MsgBox ("Operator Line 3 : True")    
   Else
      MsgBox ("Operator Line 3 : False")    
   End If

   If a<b Then
      MsgBox ("Operator Line 4 : True")    
   Else
      MsgBox ("Operator Line 4 : False")    
   End If

   If a>=b Then
      MsgBox ("Operator Line 5 : True")    
   Else
      MsgBox ("Operator Line 5 : False")    
   End If

   If a<=b Then
      MsgBox ("Operator Line 6 : True")
   Else
      MsgBox ("Operator Line 6 : False")
   End If

End Sub
When you execute the above script, it will produce the following result.
Operator Line 1 : False

Operator Line 2 : True

Operator Line 3 : False

Operator Line 4 : True

Operator Line 5 : False

Operator Line 6 : True


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Redis - String Mget Command

Redis MGET command is used to get the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned.
Array, list of values at the specified keys.
Following is the basic syntax of Redis MGET command.
redis 127.0.0.1:6379> MGET KEY1 KEY2 .. KEYN

redis 127.0.0.1:6379> SET key1 "hello" 
OK 
redis 127.0.0.1:6379> SET key2 "world" 
OK 
redis 127.0.0.1:6379> MGET key1 key2 someOtherKey 
1) "Hello" 
2) "World" 
3) (nil)


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Pickle your Machine Learning objects | Towards Data Science

Pickle is a python module used to serialize a python object into a binary format and deserialize it back to the python object.
First Case:
You are working on a machine learning problem, using the favorite: jupyter notebook. You analyzed the data and identified principal features that will help your model. You perform feature engineering and you know that this will be the final data you will pass to the machine learning model. But feature engineering requires a lot of time and you do not want to lose the feature engineered data after you shut down the notebook.
Here’s where Pickle comes in.
You just pass the feature engineered data to Pickle and save it in a binary format. Then load the pickled data back whenever you are ready to perform modeling.
Dump the data(save it)
#Code Example#Import the moduleimport pickle#Do Some Feature Engineeringfeature_engineered_data = do_feature_engineering(data)#Dump it(save it in binary format)with open('fe_data.pickle','wb') as fe_data_file:     pickle.dump(feature_engineered_data, fe_data_file)
Load the data back
#Code Example#Import the moduleimport pickle#Load the data - No need to do Feature Engineering againwith open('fe_data.pickle','rb') as fe_data_file:     feature_engineered_data = pickle.load(fe_data_file)#Continue with your modeling
So what exactly is the advantage?
Feature engineering can be a heavy process and you do not want to redo it in case of a notebook shutdown. Hence, it is beneficial to store it in a reusable format.
Let’s say you manage separate notebooks for EDA, feature engineering, and modeling. Using Pickle, you can dump the data from one notebook and load it into a different notebook.
Second Case:
A more popular case is to pickle the machine learning model object.
You are done with feature engineering, modeling, and attained a pretty good accuracy, hurrah! Your job here is done, so you turn off the laptop and get a good night’s sleep.
The next morning you get another test set to test the model, but because you shut down your laptop, you have to train the model again, which takes 6 hours!
Here’s where Pickle comes in again
Save the trained model and load the model back whenever you have new data to test it on.
Dump the model
#import moduleimport pickle#Train the datamodel.fit(X_train, X_test)#Dump the modelwith open('fitted_model.pickle','wb') as modelFile:     pickle.dump(model,modelFile)
Load the model
#import moduleimport pickle#Load the model - No need to TRAIN it again(6 hours saved)with open('fitted_model.pickle','rb') as modelFile:     model = pickle.load(modelFile)#Predict with the test setprediction = model.predict(X_test)
You can use Pickle to save the final data and train it with multiple models, or you can save the model and test it on multiple data without training the model again. How great is that?
What do you think of these use cases, and what other use cases can you think of? Let me know in the comments!
Python PostgreSQL - Database Connection

PostgreSQL provides its own shell to execute queries. To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database.
While passing the details you can go with the default server, database, port and, user name suggested by the shell.
The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL.
The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name.
import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)


    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
Display different variables in MySQL using LIKE?

Following is the syntax −
show variables where Variable_name like 'yourVariable1%' or Variable_name like 'yourVariable2%',.............N;
Let us implement the above syntax to show(more than one) variables −
mysql> show variables where Variable_name like 'key%' or Variable_name like 'innodb_undo%' or Variable_name like 'innodb_log%';
+------------------------------------+----------+
| Variable_name                      | Value    |
+------------------------------------+----------+
| innodb_log_buffer_size             | 1048576  |
| innodb_log_checksums               | ON       |
| innodb_log_compressed_pages        | ON       |
| innodb_log_file_size               | 50331648 |
| innodb_log_files_in_group          | 2        |
| innodb_log_group_home_dir          | .\       |
| innodb_log_spin_cpu_abs_lwm        | 80       |
| innodb_log_spin_cpu_pct_hwm        | 50       |
| innodb_log_wait_for_flush_spin_hwm | 400      |
| innodb_log_write_ahead_size        | 8192     |
| innodb_undo_directory              | .\       |
| innodb_undo_log_encrypt            | OFF      |
| innodb_undo_log_truncate           | ON       |
| innodb_undo_tablespaces            | 2        |
| key_buffer_size                    | 8388608  |
| key_cache_age_threshold            | 300      |
| key_cache_block_size               | 1024     |
| key_cache_division_limit           | 100      |
| keyring_operations                 | ON       |
+------------------------------------+----------+
19 rows in set (0.01 sec)
Probability of getting at least K heads in N tosses of Coins in C++

Probability is the chances of getting the desired output from the set of data available. The range of probability lie between 0 and 1 where an integer 0 shows the chances of impossibility and 1 indicates certainty.
What is probability?
Probability in mathematics gives us the tools that tell the uncertainty of the events and reasons. In other words we can say probability deals with calculating the likelihood of a given event’s occurrence, which can be expressed as a number between 1 and 0. For example: the probability of getting a head’s when an unbiased coin is tossed, or getting a 3 when a dice is rolled.
Now, coming back to the question we have to find the probability of getting at least k heads in N tosses of coins.
Like we have 3 coins and k as 2 so there are23= 8 ways to toss the coins that is −
HHH, HTH, HHT, HTT, THH, THT, TTT, TTH.
And the sets which contains at least 2 heads are −
HHH, HTH, HHT, THH.
So the probability will be 4/8 or 0.5.
Input: k = 1, n = 3
Output: 0.875

Input: k = 3, n = 6
Output: 0.65625
Approach we will be following to solve the above problem −
We will take n and k as an input.
Store the value of factorial in an array and call it whenever it is required.
Perform the calculation.
Return the result.
Step 1-> declare function to calculate the probability of getting at least k heads in n tosses
   double probability(int k, int n)
   Declare and set double check = 0
   Loop For i = k and i <= n and ++i
      Set check += temp[n] / (temp[i] * temp[n - i])
   End
   Call check = check / (1LL << n)
   return check
Step 2-> declare function to precompute the value
   void precompute()
   Set temp[0] = temp[1] = 1
   Loop For i = 2 and i < 20 and ++i
      Set temp[i] = temp[i - 1] * i
Step 3-> In main
   Call precompute()
   Call probability(1, 3)
Stop
 Live Demo
#include<bits/stdc++.h>
using namespace std;
#define size 21
double temp[size];
// calculate probability of getting at least k heads in n tosses.
double probability(int k, int n) {
   double check = 0;
   for (int i = k; i <= n; ++i)
   check += temp[n] / (temp[i] * temp[n - i]);
   check = check / (1LL << n);
   return check;
}
void precompute() {
   temp[0] = temp[1] = 1;
   for (int i = 2; i < 20; ++i)
   temp[i] = temp[i - 1] * i;
}
int main() {
   precompute();
   // Probability of getting 1 head out of 3 coins
   cout<<"probability is : "<<probability(1, 3) << "\n";
   // Probability of getting 3 head out of 6 coins
   cout<<"probability is : "<<probability(3, 6) <<"\n";
   return 0;
}
probability is : 0.875
probability is : 0.65625
Python 3 - modf() Method

The modf() method returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
Following is the syntax for the modf() method
import math

math.modf( x )

Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns the fractional and integer parts of x in a two-item tuple. Both the parts have the same sign as x. The integer part is returned as a float.
The following example shows the usage of the modf() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.modf(100.12) : ", math.modf(100.12))
print ("math.modf(100.72) : ", math.modf(100.72))
print ("math.modf(119) : ", math.modf(119))
print ("math.modf(math.pi) : ", math.modf(math.pi))
When we run the above program, it produces the following result −
math.modf(100.12) :  (0.12000000000000455, 100.0)
math.modf(100.72) :  (0.7199999999999989, 100.0)
math.modf(119) :  (0.0, 119.0)
math.modf(math.pi) :  (0.14159265358979312, 3.0)


    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
Decimal.ToDouble() Method in C# - GeeksforGeeks

31 Jan, 2019
This method is used to convert the value of the specified Decimal to the equivalent double-precision floating-point number. This method can produce round-off errors as a double-precision floating-point number has few significant digits than a Decimal.
Syntax: public static double ToDouble (decimal d);Here, d is the decimal value which is to be converted.
Return value: It returns a double-precision floating-point number equivalent to d.
Example:
// C# program to demonstrate the// Decimal.ToDouble(Decimal) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              // Taking decimal variables            Decimal dec1 = 0.0000000000134563456789M;            Decimal dec2 = 4589662514452860951234M;              // using ToDouble(Decimal) Method            Double val1 = Decimal.ToDouble(dec1);                          // using ToDouble(Decimal) Method            Double val2 = Decimal.ToDouble(dec2);              // Printing the Double value            Console.WriteLine("The Double value "                              + "is : {0}", val1);                                            // Printing the Double value            Console.WriteLine("The Double value "                              + "is : {0}", val2);                                  }          catch (OverflowException e)         {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The Double value is : 1.34563456789E-11
The Double value is : 4.58966251445286E+21

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.todouble?view=netframework-4.7.2
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
C# | Constructors
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
Delete middle of linked list in C++ program

In this tutorial, we are going to learn how to delete the middle node in a linked list.
The solution to the problem is straightforward. We will have two pointers one moves one node at a time and the other one moves two nodes at a time. By the time the second pointer reaches the final node, the first will be in the middle of the linked list.
Let's see the steps to solve the problem.
Write a struct Node for the linked list node.
Write a struct Node for the linked list node.
Initialize the linked list with the dummy data.
Initialize the linked list with the dummy data.
Write a function to delete the linked list.Initialize two-pointers (slow and fast) with linked list head pointer.Iterate over the linked list until the fast pointer reaches the end.Move the slow pointer to one next node.Move the fast pointer to the next node of the next node.Return the head pointer
Write a function to delete the linked list.
Initialize two-pointers (slow and fast) with linked list head pointer.
Initialize two-pointers (slow and fast) with linked list head pointer.
Iterate over the linked list until the fast pointer reaches the end.
Iterate over the linked list until the fast pointer reaches the end.
Move the slow pointer to one next node.
Move the slow pointer to one next node.
Move the fast pointer to the next node of the next node.
Move the fast pointer to the next node of the next node.
Return the head pointer
Return the head pointer
Print the linked list.
Print the linked list.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
struct Node* deleteMiddleNode(struct Node* head) {
   if (head == NULL) {
      return NULL;
   }
   if (head->next == NULL) {
      delete head;
      return NULL;
   }
   struct Node* slow_ptr = head;
   struct Node* fast_ptr = head;
   struct Node* prev;
   while (fast_ptr != NULL && fast_ptr->next != NULL) {
      fast_ptr = fast_ptr->next->next;
      prev = slow_ptr;
      slow_ptr = slow_ptr->next;
   }
   prev->next = slow_ptr->next;
   delete slow_ptr;
   return head;
}
void printLinkedList(struct Node* node) {
   while (node != NULL) {
      cout << node->data << " -> ";
      node = node->next;
   }
   cout << "Null" << endl;
}
Node* newNode(int data) {
   struct Node* temp = new Node;
   temp->data = data;
   temp->next = NULL;
   return temp;
}
int main() {
   struct Node* head = newNode(1);
   head->next = newNode(2);
   head->next->next = newNode(3);
   head->next->next->next = newNode(4);
   head->next->next->next->next = newNode(5);
   head->next->next->next->next->next = newNode(6);
   cout << "Linked list before deleting middle node: ";
   printLinkedList(head);
   head = deleteMiddleNode(head);
   cout << "Linked List after deleting middle node: ";
   printLinkedList(head);
   return 0;
}
If you execute the above program, then you will get the following result.
Linked list before deleting middle node: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Null
Linked List after deleting middle node: 1 -> 2 -> 3 -> 5 -> 6 -> Null
If you have any queries in the tutorial, mention them in the comment section.
How to create a horizontal slider with custom min, max, and initial value in Java

While creating horizontal slider, we can set custom values as well. Let us take three integer variable and set the int values for min, max as well as the initial value of the slider −
int val = 75;
int min = 0;
int max = 100;
Set it to the slider while creating a new slider. Here, we have set the constant to be HORIZONTAL, since we are creating a horizontal slider −
JSlider slider = new JSlider(JSlider.HORIZONTAL,min, max, val);
The following is an example to create a horizontal slider with custom min, max and initial value −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Frame with Slider");
      int val = 75;
      int min = 0;
      int max = 100;
      JSlider slider = new JSlider(JSlider.HORIZONTAL,min, max, val);
      slider.setMinorTickSpacing(10);
      slider.setMajorTickSpacing(25);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true); slider.setBackground(Color.MAGENTA);
      slider.setForeground(Color.black);
      slider.setSnapToTicks(true);
      System.out.println("Snapping to tick marks? = "+slider.getSnapToTicks());
      Font font = new Font("Serif", Font.BOLD, 13);
      slider.setFont(font);
      JPanel panel = new JPanel();
      panel.add(slider);
      frame.add(panel);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}
This will produce the following output −
C++ Program to find the smallest digit in a given number

Given a non-negative number, the task is to find its smallest digit.
For example
Input:
N = 154870
Output:
0
Explanation: In the given number '154870', the smallest digit is '0'.
The simplest approach to solve this problem is to extract the last digit in the given number using the remainder
theorem. While traversing the number, we will check if the extracted digit is less than the last digit, then return the output.
Take a number n as the input.
An integer function smallest_digit(int n) takes 'n' as the input and returns the smallest digit in the given number.
Now initialize min as the last digit of the given number.
Iterate through the number and check if the number extracted is less than the minimum number. If true, then update the minimum number and return the output.
Remove the last digit by n/10 and check if there is another digit which is lesser than the current digit.
Return the output.
Live Demo
#include <iostream>
using namespace std;
int smallest_digit(int n) {
   int min = n % 10; //assume that last digit is the smallest
   n /= 10; //to start from the second last digit
   while (n != 0) {
      if (min > n % 10)
         min = n % 10;
      n /= 10;
   }
   return min;
}
int main() {
   int n = 154870;
   cout << smallest_digit(n);
   return 0;
}
Running the above code will generate the output as,
0
Explanation: In the given number '154870', the smallest digit is '0'.
Java Math min() method with Examples - GeeksforGeeks

13 Jul, 2021
The Java.lang.math.min() function is an inbuilt function in java that returns the minimum of two numbers. The arguments are taken in int, double, float and long. If a negative and a positive number is passed as an argument then the negative result is generated. And if both parameters passed are negative then the number with the higher magnitude is generated as result.Syntax:  
dataType min(dataType num1, dataType num2)
The datatypes can be int, float, double or long.

Parameters : The function accepts two parameters num1 and num2 
among which the minimum is returned
Return value: The function returns the minimum of two numbers. The datatype will be the same as that of the arguments. Given below are the examples of the function min():  
Java
// Java program to demonstrate the// use of min() function// two double data-type numbers are passed as argumentpublic class Gfg {     public static void main(String args[])    {        double a = 12.123;        double b = 12.456;         // prints the minimum of two numbers        System.out.println(Math.min(a, b));    }}
Output:  
12.123
 
Java
// Java program to demonstrate the// use of min() function// when one positive and one// negative integers are passed as argumentpublic class Gfg {     public static void main(String args[])    {        int a = 23;        int b = -23;         // prints the minimum of two numbers        System.out.println(Math.min(a, b));    }}
Output:  
-23
 
Java
// Java program to demonstrate// the use of min() function// when two negative integers// are passed as argumentpublic class Gfg {     public static void main(String args[])    {        int a = -25;        int b = -23;         // prints the minimum of two numbers        System.out.println(Math.min(a, b));    }}
Output:  
-25
If you want to find the minimum of two numbers many times in your code, then it’s often tedious to write the complete Math.min() every time. So a shorter and a bit time-saver way out here is to directly import java.lang.Math.min as static and then use just min() instead of the complete Math.min().
Java
import static java.lang.Math.min; class GFG {    public static void main(String[] args)    {        int a = 3;        int b = 4;        System.out.println(min(a, b));    }}
3

VikramSingh20
deadlock24
Java-lang package
java-math
Java
Misc
Misc
Misc
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
Initialize an ArrayList in Java
Interfaces in Java
How to iterate any Map in Java
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
fgets() and gets() in C language
Convert your XGBoost model into if-else format | by Shiu-Tang Li | Towards Data Science

In this article, I’ll show the reader how to convert an XGBoost model to a .py file with some tricks with regular expressions, so that the only dependency of this .py file is the “numpy” package. Therefore, after you trained the XGB model, you can deploy the model in another environment where the XGBoost package is not required.
When you plan to deploy XGBoost models in AWS lambda, this trick may help you meet the package size limit. If you’re going to deploy the model with other approaches (AWS SageMaker / Docker + Flask + Nginx...), then this article may not really help you.
The tutorial is divided into a few parts: Download the data and train the model → Convert the model to a .py file → Use the .py file to predict test data.
This notebook contains all the codes below. Put it in your target folder.
Let’s use the well-known Titanic dataset to build a toy model. Download both train.csv and test.csv from the link. Create a subfolder “/data” and put the .csv there.
Because XGBoost only take numeric inputs, let’s skip categorical variables encoding and randomly select a few numeric columns for modeling.
This XGBoost model produces 3 decision trees, each with max height = 3. Because gamma (the penalty constant of number of splits) is set to a larger value, it prevents splitting for certain tree nodes.
The decision trees look like:
The predicted score for each record is given by “base score + final leaf values from all trees”.
In XGBoost Python API, you can find functions that allow you to dump the model as a string or as a .txt file, or save the model for later use. But there’s no API to dump the model as a Python function. Here’s the trick to do it: we first dump the model as a string, then use regular expressions to parse the long string and convert it to a .py file.
The code snippet which does the job:
With the base score used in model training and the trained model, we are able to convert it to a .py model which only requires “numpy” package (for missing values handling).
model_to_py(params['base_score'], model, 'xgb_model.py')
part of the generated “xgb_model.py” looks like:
We can now import the xgb_model.py we just created, and it’s straightforward to perform predictions.
Let’s compare it to the predictions produced by XGBoost models.
The results matched.
Some warnings:
The codes work well under python 3.5.2 + xgboost 0.6. It’s not guranteed to generate correct results for other versions.I haven’t done any error handling in my codes.The .py is designed for scoring python dictionaries, but you can do some minor revisions to fit your use case.Before you generate the .py file, make sure there’s no .py file with the same name in the target folder.
The codes work well under python 3.5.2 + xgboost 0.6. It’s not guranteed to generate correct results for other versions.
I haven’t done any error handling in my codes.
The .py is designed for scoring python dictionaries, but you can do some minor revisions to fit your use case.
Before you generate the .py file, make sure there’s no .py file with the same name in the target folder.
How to set Dataframe Column value as X-axis labels in Python Pandas?

To set Dataframe column value as X-axis labels in Python Pandas, we can use xticks in the argument of plot() method.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a dataframe using Pandas with column1 key.
Make a dataframe using Pandas with column1 key.
Plot the Pandas dataframe using plot() method with column1 as the X-axis column.
Plot the Pandas dataframe using plot() method with column1 as the X-axis column.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = pd.DataFrame({"column1": [4, 6, 7, 1, 8]})
data.plot(xticks=data.column1)
plt.show()
How to ignore an exception and proceed in Python?

We can run a try-except block without handling the exception the following ways:
try:
1/0
except:
pass
and
try:
1/0
except Exception:
pass
In the first case, using bare except: is like using except BaseException:  which will also catch KeyboardInterrupt, SystemExit and errors like that, which are derived directly from exceptions.BaseException, not exceptions.Exception.
In second case, the things mentioned above won't be caught. The pass statement makes it possible to ignore the exceptions.
Updating a MongoDB document and adding new keys only in the first document?

This can be easily achieved using MongoDB update(). Let us create a collection with documents −
> db.demo162.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3684359e4f06af551997c2")
}
> db.demo162.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3684389e4f06af551997c3")
}
> db.demo162.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36843c9e4f06af551997c4")
}
Display all documents from a collection with the help of find() method −
> db.demo162.find();
This will produce the following output −
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
Here is the query to update a document, adding new keys in first document −
> db.demo162.update({},{$set:{"StudentAge":23}},{upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo162.find();
This will produce the following output −
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
C# | Remove all elements from the Collection<T> - GeeksforGeeks

01 Feb, 2019
Collection<T>.Clear method is used to remove all elements from the Collection<T>.
Syntax:
public void Clear ();

Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to remove all// elements from the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel;  class GFG {      // Driver code    public static void Main()    {        // Creating a collection of strings        Collection<string> myColl = new Collection<string>();          // Adding elements in Collection myColl        myColl.Add("A");        myColl.Add("B");        myColl.Add("C");        myColl.Add("D");        myColl.Add("E");          // To print the count of elements in Collection        Console.WriteLine("Count : " + myColl.Count);          // Displaying the elements in myColl        foreach(string str in myColl)        {            Console.WriteLine(str);        }          // Removing all the elements from Collection        myColl.Clear();          // To print the count of elements in Collection        Console.WriteLine("Count : " + myColl.Count);          // Displaying the elements in myColl        foreach(string str in myColl)        {            Console.WriteLine(str);        }    }}
Output:
Count : 5
A
B
C
D
E
Count : 0

Example 2:
// C# code to remove all// elements from the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel;  class GFG {      // Driver code    public static void Main()    {        // Creating a collection of ints        Collection<int> myColl = new Collection<int>();          // Adding elements in Collection myColl        myColl.Add(2);        myColl.Add(3);        myColl.Add(4);        myColl.Add(5);          // To print the count of elements in Collection        Console.WriteLine("Count : " + myColl.Count);          // Displaying the elements in myColl        foreach(int i in myColl)        {            Console.WriteLine(i);        }          // Removing all the elements from Collection        myColl.Clear();          // To print the count of elements in Collection        Console.WriteLine("Count : " + myColl.Count);          // Displaying the elements in myColl        foreach(int i in myColl)        {            Console.WriteLine(i);        }    }}
Output:
Count : 4
2
3
4
5
Count : 0

Note:
Count is set to zero, and references to other objects from elements of the collection are also released.
This method is an O(n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.clear?view=netframework-4.7.2
CSharp-Collection-Class
CSharp-Collections.ObjectModel-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Replace() Method
C# | Constructors
Introduction to .NET Framework
What is a generic List in C#?

Generic List<T> is a generic collection in C#. The size can be dynamically increased using List, unlike Arrays.
Let us see an example −
We have set the List first −
List<string> myList = new List<string>()
Now add elements in the list −
List<string> myList = new List<string>() {
   "mammals",
   "reptiles",
   "amphibians"
}
Now using a property let us count the number of elements added −
using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      List<string> myList = new List() {
         "mammals",
         "reptiles",
         "amphibians"
      };
      Console.WriteLine(myList.Count);
   }
}
PHP Program to count Page Views

15 Jan, 2018
What is a session?
A PHP session is used to store data on a server rather than the computer of the user.Session identifiers or SID is unique numbers which are used to identify every user in a session based environment.The SID is used to link the user with his information on the server like posts, emails etc. You can learn about sessions in details in the article PHP | Sessions
How to use sessions for Storing Page Counts
A session mechanism can be used to store page views which increment on each refresh and show the count on a webpage. A session is user specific and for every user, a separate session is created along with a separate session variable which is associated with that session.Using this mechanism, for every user the session variable is set to 1 initially for the first visit.On consecutive visits, the value of this session variable is incremented and displayed on the output webpage.
Below is the PHP program to store page count:
<?php   session_start();   if(isset($_SESSION['views']))    $_SESSION['views'] = $_SESSION['views']+1;else    $_SESSION['views']=1;      echo"views = ".$_SESSION['views'];  ?>
Output:
ExplanationBelow is the explanation of above code:
session_start() :It is a first step which is used to start the session. It is a standard call. The session_start() should be used whenever the session variable is used.$_SESSION[‘views’] :This is the session variable which is used to store views count for a user’s session. ‘views’ is the session name. The session name should be always be enclosed within the single quote.isset() : It is a standard php function which returns true or false depending upon whether the passed parameter is set or not.
session_start() :It is a first step which is used to start the session. It is a standard call. The session_start() should be used whenever the session variable is used.
$_SESSION[‘views’] :This is the session variable which is used to store views count for a user’s session. ‘views’ is the session name. The session name should be always be enclosed within the single quote.
isset() : It is a standard php function which returns true or false depending upon whether the passed parameter is set or not.
We can also reset the session variable. Below program shows how to reset a session in PHP:
<?php  session_start();$views = $_SESSION['views'];    unset($_SESSION['views']); session_destroy();   ?>
Output:
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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 ?
Convert a NumPy array to Pandas dataframe with headers

01 Oct, 2020
To convert a numpy array to pandas dataframe, we use pandas.DataFrame() function of Python Pandas library.
Syntax: pandas.DataFrame(data=None, index=None, columns=None)
Parameters:data: numpy ndarray, dict or dataframeindex: index for resulting dataframecolumns: column labels for resulting dataframe
import numpy as npimport pandas as pd    arr = np.random.rand(4, 3)print("Numpy array:")print(arr)  # convert numpy array to dataframedf = pd.DataFrame(arr, columns =['A', 'B', 'C'])print("\nPandas DataFrame: ")df
Output:
Example 2 :
import numpy as npimport pandas as pd    arr = np.random.rand(6).reshape(2, 3)print("Numpy array:")print(arr)  # convert numpy array to dataframedf = pd.DataFrame(arr, columns =['C1', 'C2', 'C3'])print("\nPandas DataFrame: ")df
Output:
Example 3 :
import numpy as npimport pandas as pd    arr = np.array([[1, 2], [4, 5]])print("Numpy array:")print(arr)  # convert numpy array to dataframedf = pd.DataFrame(data = arr, index =["row1", "row2"],                   columns =["col1", "col2"])  print("\nPandas DataFrame: ")df
Output:
Python numpy-arrayManipulation
Python pandas-dataFrame
Python-numpy
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
moveto() function in C

25 Jan, 2018
The header file graphics.h contains moveto() function which changes the current position to (x, y)
Syntax :
 void moveto(int x, int y);

Examples :
Input : x = 70, y = 40
Output : 

Input : x = 50, y = 80
Output : 

Below is the implementation of moveto() function:
// C Implementation for moveto()#include <graphics.h>#include <stdio.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;    char arr[100];      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // sprintf stands for “String print”.    // Instead of printing on console, it    // store output on char buffer which    // are specified in sprintf    sprintf(arr, "X = %d, Y = %d", getx(),                                 gety());      // outtext function displays text at    // current position.    outtext(arr);      // moveto function    moveto(70, 40);      // The function getx returns the X    // coordinate of the current position.    // The function gety returns the y    // coordinate of current position.    sprintf(arr, "X = %d, Y = %d", getx(),                                  gety());      outtext(arr);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Ways to copy a vector in C++
Storage Classes in C
Understanding "extern" keyword in C