code-rag-bench/online-tutorials huggingface dataset:
Tcl - Namespaces

Namespace is a container for set of identifiers that is used to group variables and procedures. Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there was single global scope. Now with namespaces, we have additional partitions of global scope.
Namespaces are created using the namespace command. A simple example for creating namespace is shown below −
#!/usr/bin/tclsh

namespace eval MyMath {
  # Create a variable inside the namespace
  variable myResult
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
  set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23

puts $::MyMath::myResult
When the above code is executed, it produces the following result −
33

In the above program, you can see there is a namespace with a variable myResult and a procedure Add. This makes it possible to create variables and procedures with the same names under different namespaces.
Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below −
#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
}

namespace eval extendedMath {
   # Create a variable inside the namespace
   namespace eval MyMath {
      # Create a variable inside the namespace
      variable myResult
   }
}
set ::MyMath::myResult "test1"
puts $::MyMath::myResult
set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult
When the above code is executed, it produces the following result −
test1
test2

You can see in the previous namespace examples, we use a lot of scope resolution operator and it's more complex to use. We can avoid this by importing and exporting namespaces. An example is given below −
#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}

namespace import MyMath::*
puts [Add 10 30]
When the above code is executed, it produces the following result −
40

You can remove an imported namespace by using forget subcommand. A simple example is shown below −
#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}
namespace import MyMath::*
puts [Add 10 30]
namespace forget MyMath::*
When the above code is executed, it produces the following result −
40

 Print
 Add Notes
 Bookmark this page
Tailwind CSS Visibility

23 Mar, 2022
This class accepts two values in tailwind CSS. It is the alternative to the CSS visibility property. This class is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document. Use the display property to remove or hide and delete an element from the browser.
Visibility:
Invisible
Visible
invisible: This class is used to hide the element from the page but takes up space in the document
Syntax:
<element class="invisible">...</element>
Example:
HTML
<!DOCTYPE html><html> <head>     <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"           rel="stylesheet"> </head>   <body class="text-center">     <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>     <b>Tailwind CSS Visibility Class</b>     <div id="main" class="flex flex-row justify-evenly">         <div class="bg-green-700 w-24 h-12">1</div>         <div class="invisible bg-green-600 w-24 h-12">2</div>         <div class="bg-green-500 w-24 h-12">3</div>         <div class="bg-green-400 w-24 h-12">4</div>     </div> </body>   </html>
Output:
visible: It is the default value. The element is shown or visible normally in the web document.
Syntax:
<element class="invisible">...</element>
Example:
HTML
<!DOCTYPE html> <html> <head>     <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"           rel="stylesheet"> </head>   <body class="text-center">     <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>     <b>Tailwind CSS Visibility Class</b>     <div id="main" class="flex flex-row justify-evenly">         <div class="bg-green-700 w-24 h-12">1</div>         <div class="visible bg-green-600 w-24 h-12">2</div>         <div class="bg-green-500 w-24 h-12">3</div>         <div class="bg-green-400 w-24 h-12">4</div>     </div> </body>   </html>
Output:
anikaseth98
Tailwind CSS
Tailwind-Layout
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <hr> align Attribute

17 Dec, 2021
The HTML <hr> align Attribute is used to specify the alignment of the horizontal line. If the width attribute is not set to 100% then the align attribute will not create any effect.Syntax: 
<hr align="left | center | right">
Attribute Values:  
left: It sets the left-align to horizontal line.
center: It sets the center-align to horizontal line. It is the default value.
right: It sets the right-align to horizontal line.
Note: The <hr> align Attribute is not supported by HTML 5.Example:  
html
<!DOCTYPE html><html> <head>    <style>        h1,h2        {            text-align:center;        }        h4        {            font-weight:bold;        }        .gfg        {           text-align:right;            font-weight:bold;        }        .gfg2        {            font-weight:bold;            text-align:center;        }    </style></head> <body>         <h1>GeeksforGeeks</h1>    <h2>        HTML hr align Attribute     </h2>    <h4>        hr align="left"    </h4>    <hr width="300px;"        size="10"        align="left">    <h4 class="gfg">        hr align="right"    </h4>    <hr width="50%" align="right"        size="10">        <h4 class="gfg2">           hr align="center"               </h4>         <hr width="50%"        size="10"        align="center"></body> </html>
Output: 
 Supported Browsers: The browser supported by HTML <hr> align Attribute are listed below: 
Google Chrome
Internet Explorer
Firefox
Safari
Opera 
hritikbhatnagar2182
kk9826225
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2021 | Set 1 | Question 56

24 May, 2021
Consider the following pseudocode, where S is a semaphore initialized to 5 in line #2 and counter is a shared variable initialized to 0 in line #1. Assume that the increment operation in line #7 is not atomic.
1.  int counter =0;
2.  Semaphore S= init(5);
3.  void parop(void)
4.  {
5.        wait(S);
6.        wait(S);
7.        counter++;
8.        signal(S);
9.        signal(S);
10.  } 
If five threads execute the function parop concurrently, which of the following program behavior(s) is/are possible?(A) The value of counter is 5 after all the threads successfully complete the execution of parop(B) The value of counter is 1 after all the threads successfully complete the execution of parop(C) The value of counter is 0 after all the threads successfully complete the execution of parop(D) There is a deadlock involving all the threadsAnswer: (A) (B) (D)Explanation: First of all, since the value of counter is 5, and if there are two wait() and two signal() for each thread. So, if when these threads will be completed, final counter value can never be 0.So, option (C) is false.
Counter value 5 is possible if threads run in any sequence, i.e., one by one.So, option (A) is true.
Counter value 1 is also possible if a thread which is entered in first and read the counter = 0 and writing counter value 5 at the end of after executing all other threads.So, option (B) is true.
Five threads getting pre-empted after executing only first wait(S); line-5.Now, second wait(S); line-6, will cause deadlock.So, option (D) is true.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to open a binary file in append mode with Python?

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like GIFs, audio files like MP3s or binary document formats like Word or PDF. To open files in binary append mode, when specifying a mode, add 'ab' to it.
 f = open('my_file.mp3', 'ab')
file_content = f.read()
f.close()
Above code opens my_file.mp3 in binary append mode and stores the file content in file_content variable.
Auto Logout in Linux Shell Using TMOUT Shell Variable - GeeksforGeeks

07 Mar, 2021
TMOUT is a Linux-Unix shell variable that provides the user security for their login session in the system. It provides the “Auto Logout Functionality” for the login shell in case of no activity for a specified time.
Generally when the user leaves the Linux system idle (situation when a user doesn’t perform any administrative task by running a command or using GUI ( Graphical User Interface )) after the login as a root privilege, that time if anyone got physical access to the system via malicious attack that he has the full power as you and can execute any script that causes you a great loss. 
So, It is a good idea to have the feature like auto-logout after a definite idle time.
All process is given the following stepwise and to follow the process run the following commands.
Step 1: Enable this globally (system-wide for all users), set the TMOUT variable in the /etc/profile shell initialization file.
$ sudo nano /etc/profile 
Step 2: insert the given line 
TMOUT=300 
Note: Here 300 representing 300 seconds or 5 minutes.
Step 3: save and exit
Press Ctrl+x followed by "Y"
From now the user will automatically log out from the login session if there is no activity for a specific time (here that time is 5 minutes (300 seconds)).
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
nohup Command in Linux with Examples
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
page_source driver method – Selenium Python

03 Dec, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. 
This article revolves around page_source driver method in Selenium. page_source method gets the source of the current page.
Syntax – 
driver.page_source
Example – Now one can use page_source method as a driver method as below – 
driver.get("https://www.geeksforgeeks.org/")
driver.page_source
To demonstrate, page_source method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get page_source,
Program – 
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get page_sourceprint(driver.page_source)
Output – Screenshot added –  
Terminal output –  
 
Akanksha_Rai
Python-selenium
selenium
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
SQL Query to Match Any Part of String

10 Sep, 2021
SQL Pattern Matching :
It is used for searching a string or a sub-string to find certain character or group of characters from a string. We can use LIKE Operator of SQL to search sub-string. The LIKE operator is used with the WHERE Clause to search a pattern in string of column. The LIKE operator is used in a conjunction with the two wildcards characters.
Percentage sign( % ) : It represents zero, one or multiple characters of variable length. Underscore ( _ ) : It represents one, single character of fixed length.
Percentage sign( % ) : It represents zero, one or multiple characters of variable length.
 Underscore ( _ ) : It represents one, single character of fixed length.
Example :
In this example we will create a schema for our database and named it as geeksforgeeks. After that we will create a table inside it with the name geeks_data and tried to search a sub string from the data of table.
Step 1: Create a database :
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
In order to create a database we need to use the CREATE operator.
CREATE DATABASE geeksforgeeks;
Step 2: Create a table inside the database :
In this step we will create the table geeks_data inside the geeksforgeeks database.
CREATE TABLE geeksforgeeks.geeks_data(id INT, 
                                    first_name VARCHAR(255),
                                    last_name VARCHAR(255),
                                    text_description  VARCHAR(255),
                                    PRIMARY KEY(id));
Step 3: Insert data into the table :
In order to insert the data inside the database we need to use INSERT operator.
INSERT INTO geeksforgeeks.geeks_data (id, first_name, last_name, text_description) 
VALUES (1, "Rahul", "Khanna", "I am a backend developer who also like to technical content writing");
Step 4: Searching the pattern using Like operator :
SELECT first_name FROM geeksforgeeks.geeks_data WHERE text_description LIKE '%backend%developer%';
Step 5: Output :
We will get the first_name where in the description backend developer is present.
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matlab M-Files - Import Data

In this chapter, we will understand how to import data from an existing m-file in MATLAB.
Consider the m-file firstmfile.m. The contents of the file are as follows −
a = 5; b = 7;
c = a + b
d = c + sin(b)
e = 5 * d
f = exp(-d)

When you execute the file, the data variables are available in the workspace, as shown below −
Let us clear the workspace and the command prompt. Hence, we can now import the file and also check the data available.
To clear workspace, the command is clear all.
The workspace is empty now.
Let us clean the command window by using clc command as shown below −
We have an empty command window.
Now, type the m-file name as shown below. It will execute the code inside the file
The workspace is loaded with all the variables that are used inside the file.
You can also check the details of the variables by using the whos command as shown below −

    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
How to add/merge two hash tables in PowerShell?

Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.
Here, we have two hash tables: htableandhtable1.
$htable = [Ordered]@{EmpName="Charlie";City="New York";EmpID="001"}
$htable1 = [Ordered]@{Fruit='Apple';Color='Red'}
We will now add two hash tables,
$htable + $htalble1
PS C:\WINDOWS\system32> $htable+$htable1

Name       Value
----       -----
EmpName    Charlie
City       New York
EmpID      001
Fruit      Apple
Color      Red
Tryit Editor v3.7

CSS Grid Container
Tryit: Grid container
MySQL query to select date from timestamp?

Let us first create a table. One of the column is a timestamp −
mysql> create table DemoTable
   -> (
   -> CustomerName varchar(100),
   -> CustomerShippingDate timestamp
   -> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','2019-01-21');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('David','2019-03-01');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('Robert','2019-06-04');
Query OK, 1 row affected (0.25 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+----------------------+
| CustomerName | CustomerShippingDate |
+--------------+----------------------+
| Chris        | 2019-01-21 00:00:00  |
| David        | 2019-03-01 00:00:00  |
| Robert       | 2019-06-04 00:00:00  |
+--------------+----------------------+
3 rows in set (0.00 sec)
Following is the query to select date on timestamp −
mysql> select *,date(CustomerShippingDate) from DemoTable;
This will produce the following output −
+--------------+----------------------+----------------------------+
| CustomerName | CustomerShippingDate | date(CustomerShippingDate) |
+--------------+----------------------+----------------------------+
| Chris        | 2019-01-21 00:00:00 | 2019-01-21                  |
| David        | 2019-03-01 00:00:00 | 2019-03-01                  |
| Robert       | 2019-06-04 00:00:00 | 2019-06-04                  |
+--------------+----------------------+----------------------------+
3 rows in set (0.00 sec)
Batch Script - TREE

This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth.
Tree

@echo off 
tree
The above command will display the tree structure of the current directory. Following is an example of the output.
Folder PATH listing for volume Windows8_OS
Volume serial number is E41C-6F43
C:.
├───newdir
├───newdir1
└───newdir2

 Print
 Add Notes
 Bookmark this page
Can we write any code after throw statement in Java?

No, we can not place any code after throw statement, it leads to compile time error Unreachable Statement.
The throw keyword is used to throw an exception manually.
Whenever it is required to suspend the execution of the functionality based on the user-defined logical error condition, we will use this throw keyword to throw an exception.
We need to handle these exceptions using try and catch blocks.
The throw keyword must follow Throwable type of object.
The throw keyword must be used only in the method logic.
Since it is a transfer statement, we cannot place statements after throw statement. It leads to a compile-time error Unreachable code.
We can throw user-defined and predefined exceptions using throw keyword.
Live Demo
public class ThrowKeywordDemo {
   public static void main(String[] args) {
      try {
         throw new ArithmeticException();
         System.out.println("In try block"); // compile-time error, unreachable statement
      } catch (Exception e) {
         System.out.println(e);
         e.printStackTrace();
      }
   }
}
The above code doesn't execute because there is a statement after a throw statement in the try block, it can cause the compile-time error. So we cannot put any statements after a throw statement in Java.
unreachable statement
System.out.println("In try block");
How to send keyboard input to a textbox on a webpage using Python Selenium webdriver?

We can send keyboard input to a textbox on a webpage in Selenium webdriver in Python using the method send_keys. The text to be entered is passed as a parameter to that method.
To perform keyboard actions, we can also use the send_keys method and then pass the class Keys.<key to be pressed> as a parameter to that method. To use the Keys class, we have to add from selenium.webdriver.common.keys import Keys statement to the code.
i = driver.find_element_by_name("txt")
i.send_keys("Selenium")
i.send_keys(Keys.RETURN)
Let us try to send keyboard input to a textbox on a page −
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.google.com/")
#identify text box
l = driver.find_element_by_class_name("gLFyf")
#send input
l.send_keys("Selenium")
#send keyboard input
l.send_keys(Keys.RETURN)
Bootstrap Button Groups

Bootstrap allows you to group a series of buttons together (on a single line) in a button group:


Use a <div> element with class .btn-group to create a button group:
Tip: Instead of applying button sizes to every button in a 
group, use class .btn-group-lg|sm|xs to size all buttons in the group:
Bootstrap also supports vertical button groups:


Use the class .btn-group-vertical to create a vertical button group:
To span the entire width of the screen, use the .btn-group-justified 
class:
Example with <a> elements:
Note: For <button> elements, you must wrap each button in a .btn-group class:
Tablet
Smartphone
Nest button groups to create dropdown menus:
Tablet
Smartphone
Add a Bootstrap class to group the buttons together.
<div class="">
  <button class="btn btn-primary">Apple</button>
  <button class="btn btn-primary">Samsung</button>
  <button class="btn btn-primary">Sony</button>
</div>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to repeat a column of a data frame and join it with another data frame in R by rows?

Suppose we have a data frame df1 that contains 5 columns and another data frame df2 that contains only column but the data type of the columns in both the data frames is same. Now we might want to add the column of the second data frame starting at the end of the rows of the first data frame by creating the same number of columns as in first data frame. This might be required by researchers to understand the impact of an external variable on the result of the analysis and it can be done with the help of sapply function.
Consider the below data frame −
 Live Demo
set.seed(259)
x1<-sample(0:9,20,replace=TRUE)
x2<-sample(1:10,20,replace=TRUE)
x3<-sample(11:20,20,replace=TRUE)
x4<-sample(16:20,20,replace=TRUE)
x5<-sample(41:50,20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4,x5)
df1
  x1 x2 x3  x4  x5
1 3  2  19  16  41
2 8  3 14 17 47
3 6  10 13 17 50
4 1  10 18 20 50
5 5  5 13 18 49
6 3  10 13 19 48
7 3  8 13 16 48
8 8   1 15 17 49
9 9  6 13 16 50
10 7 5 19 19 43
11 3 10 12 17 42
12 4 5 17 18 47
13 7 9 13 19 48
14 8 5 11 19 41
15 3 1 19 18 50
16 9 2 16 17 41
17 0 5 17 19 42
18 2 7 11 17 42
19 3 1 14 18 41
20 1 2 19 18 47
 Live Demo
x1<-sample(0:50,20)
df2<-data.frame(x1)
df2
x1
1 45
2 25
3 24
4 46
5 32
6 3
7 30
8 6
9 14
10 36
11 1
12 34
13 47
14 9
15 22
16 21
17 16
18 44
19 31
20 26
Joining df2 columns with df1 by repeating the column of df2 to the number of columns in df1 −
data.frame(sapply(df1,c,unlist(df2)),row.names=NULL)
  x1 x2 x3 x4 x5
1 9  4  12 16 48
2 2  9  16 19 47
3 6  7  17 17 46
4 1  8  17 16 44
5 3  8  12 18 44
6 4  8  16 20 42
7 6  3  13 17 41
8 0  3  18 18 43
9 8  9  11 17 46
10 4 9  14 16 44
11 2 3  20 18 44
12 9 3  11 20 45
13 4 1  12 17 42
14 6 8  11 17 47
15 3 8  20 18 47
16 8 8  12 20 43
17 5 4  18 18 48
18 4 4  15 16 43
19 9 7  11 17 50
20 2  7  11 20 44
21 34  34 34 34 34
22 8 8  8 8 8
23 30  30 30 30 30
24 6 6 6 6 6
25 12 12 12 12 12
26 7 7 7 7 7
27 36 36 36 36 36
28 31 31 31 31 31
29 44 44 44 44 44
30 24 24 24 24 24
31 26 26 26 26 26
32 22 22 22 22 22
33 14 14 14 14 14
34 2 2 2 2 2 35
33 33 33 33 33
36 9 9 9 9 9
37 15 15 15 15 15
38 11 11 11 11 11
39 19 19 19 19 19
40 32 32 32 32 32
How to convert an MySQL database characterset and collation to UTF-8?

Firstly, we will check which MySQL version is currently being used with the help of version()
function −
The query is as follows −
mysql> SELECT version();
The following is the output
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.00 sec)
As you can see in the above output, version 8.0.12 is being used. Now, we can check the current
character encoding using the following syntax −
SELECT CCSA.character_set_name FROM information_schema.`TABLES`T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA WHERE CCSA.collation_name
-> =T.table_collation AND T.table_schema = "yourDatabaseName" AND T.table_name =
"yourTableName";
Apply the above query −
mysql> SELECT CCSA.character_set_name FROM information_schema.`TABLES`T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA WHERE CCSA.collation_name
-> =T.table_collation AND T.table_schema = "sample" AND T.table_name = "mytable";
The following is the output:
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4            |
+--------------------+
1 row in set (0.00 sec)
Here is the query by which we can set utf8 for a database −
mysql> ALTER DATABASE sample CHARACTER SET utf8 COLLATE utf8_general_ci;
Query OK, 1 row affected, 1 warning (0.27 sec)
Let us check −
mysql> SELECT CCSA.character_set_name FROM information_schema.`TABLES`T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA WHERE CCSA.collation_name
-> =T.table_collation AND T.table_schema = "sample" AND T.table_name = "mytable";
The following is the output
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4            |
+--------------------+
1 row in set (0.00 sec)
IntStream limit() method in Java

The limit() method of the IntStream class is used to return a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. Here, maxSize is the parameter.
The syntax is as follows
IntStream limit(long maxSize)
Here, the maxSize parameter is the count of elements the stream is limited to.
At first, an IntStream is created with the range() method to set a sequential order of elements
IntStream intStream = IntStream.range(20, 40);
Now, use the limit() method, whose parameter is the maxSize i.e. the count of elements the stream is limited to
intStream.limit(8)
The following is an example to implement IntStream limit() method in Java
 Live Demo
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.range(20, 40);
      intStream.limit(8).forEach(System.out::println);
   }
}
20
21
22
23
24
25
26
27
response.text - Python requests - GeeksforGeeks

04 Sep, 2021
response.text returns the content of the response, in unicode. Basically, it refers to Binary Response content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.text out of a response object. 
To illustrate use of response.text, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Prerequisites – 
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
Example code – 
Python3
import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request textprint(response.text)
Example Implementation –
Save above file as request.py and run using 
Python request.py
Output – 
Check the content at the start of output, it shows the entire content in unicode.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.  
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. 
sumitgumber28
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
How To Convert Python Dictionary To JSON?
Convert.ToDouble(String, IFormatProvider) Method in C#

The Convert.ToDouble() method in C# converts the specified string representation of a number to an equivalent double-precision floating-point number, using the specified culture-specific formatting information.
Following is the syntax −
public static double ToDouble (string val, IFormatProvider provider);
Above, the value value is a string that contains the number to convert, whereas the provider is an object that supplies culture-specific formatting information.
Let us now see an example to implement the Convert.ToDouble() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main(){
      String val = "876876, 878";
      NumberFormatInfo formatProvider = new NumberFormatInfo();
      formatProvider.NumberDecimalSeparator = ", ";
      formatProvider.NumberGroupSeparator = ".";
      formatProvider.NumberGroupSizes = new int[] { 2 };
      Console.WriteLine("Converted Decimal value...");
      double res = Convert.ToDouble(val, formatProvider);
      Console.Write("{0}", res);
   }
}
This will produce the following output −
Converted Decimal value...
876876.878
RSpec - Test Doubles

In this chapter, we will discuss RSpec Doubles, also known as RSpec Mocks. A Double is an object which can “stand in” for another object. You’re probably wondering what that means exactly and why you’d need one.
Let’s say you are building an application for a school and you have a class representing a classroom of students and another class for students, that is you have a Classroom class and a Student class. You need to write the code for one of the classes first, so let’s say that, start with the Classroom class −
class ClassRoom 
   def initialize(students) 
      @students = students 
   end 
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
end
This is a simple class, it has one method list_student_names, which returns a comma delimited string of student names. Now, we want to create tests for this class but how do we do that if we haven’t created the Student class yet? We need a test Double.
Also, if we have a “dummy” class that behaves like a Student object then our ClassRoom tests will not depend on the Student class. We call this test isolation.
If our ClassRoom tests don’t rely on any other classes, then when a test fails, we can know immediately that there is a bug in our ClassRoom class and not some other class. Keep in mind that, in the real world, you may be building a class that needs to interact with another class written by someone else.
This is where RSpec Doubles (mocks) become useful. Our list_student_names method calls the name method on each Student object in its @students member variable. Therefore, we need a Double which implements a name method.
Here is the code for ClassRoom along with an RSpec Example (test), yet notice that there is no Student class defined −
class ClassRoom 
   def initialize(students) 
      @students = students 
   end
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
end

describe ClassRoom do 
   it 'the list_student_names method should work correctly' do 
      student1 = double('student') 
      student2 = double('student') 
      
      allow(student1).to receive(:name) { 'John Smith'} 
      allow(student2).to receive(:name) { 'Jill Smith'} 
      
      cr = ClassRoom.new [student1,student2]
      expect(cr.list_student_names).to eq('John Smith,Jill Smith') 
   end 
end
When the above code is executed, it will produce the following output. The elapsed time may be slightly different on your computer −
. 
Finished in 0.01 seconds (files took 0.11201 seconds to load) 
1 example, 0 failures

As you can see, using a test double allows you to test your code even when it relies on a class that is undefined or unavailable. Also, this means that when there is a test failure, you can tell right away that it’s because of an issue in your class and not a class written by someone else.

    9 Lectures 
     37 mins

 Harshit Srivastava

    27 Lectures 
     7 hours 

 Atul Tiwari
 Print
 Add Notes
 Bookmark this page
How to style a header with CSS?

To style a header using CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      margin: 0;
   }
   .header {
      padding: 30px;
      text-align: center;
      background: #bc1a6b;
      color: white;
      font-size: 30px;
   }
   main {
      padding: 20px;
      font-size: 18px;
   }
</style>
</head>
<body>
<div class="header">
<h1>My website ⇅</h1>
</div>
<main>
<h1>Some heading</h1>
<p>Some sample content.Some sample content.</p>
<p>Some sample content.Some sample content.</p>
<p>Some sample content.Some sample content.</p>
</main>
</body>
</html>
The above code will produce the following output −
What are variables and types of variables in C++?

A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. A very simple example of a variable is −
int my_val = 5;
Here we have a variable my_val of type int(integer) and having the value 5. More generally variables are defined as −
type variable_name;
Or if you also want to initialize them −
type variable_name = value;
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive. Following are the basic types available in C++ −
C++ also allows us to create more complex variables like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
 Enumerations or enums is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language.
 Pointers are special ints that store addresses of other variables.
 A Reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
 A data structure(struct) is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.
 Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members.
cycle - Django Template Tags - GeeksforGeeks

02 Dec, 2021
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, cycle etc. This article revolves about how to use cycle tag in Templates. It produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again. 
Syntax:
{% cycle 'value_1' 'value_2' %}
Example:This tag is particularly useful in a loop: 
html
{% for o in some_list %}    <tr class="{% cycle 'row1' 'row2' %}">        ...    </tr>{% endfor %}
The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop. 
Illustration of How to use cycle tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. 
Refer to the following articles to check how to create a project and an app in Django. 
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Now create a view through which we will pass the context dictionary, In geeks/views.py, 
Python3
# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request):    # create a dictionary    context = {        "data" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],    }    # return response    return render(request, "geeks.html", context)
Create a url path to map to this view. In geeks/urls.py,
Python3
from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [    path('', geeks_view),]
Create a template in templates/geeks.html, 
html
{% for i in data %}    <div class="{% cycle 'row1' 'row2' %}">        {{ i }}    </tr>{% endfor %}
Let’s check what is displayed on “/” are displayed in the template. 
Let’s check page source for the same. 
One can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this: 
html
{% for o in some_list %}    <tr class="{% cycle rowvalue1 rowvalue2 %}">        ...    </tr>{% endfor %}
surindertarika1234
Django-templates
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Filter even values from a list

As part of data analysis require to filter out values from a list meeting certain criteria. In this article we'll see how to filter out only the even values from a list.
We have to go through each element of the list and divide it with 2 to check for the remainder. If the remainder is zero then we consider it as an even number. After fetching these even numbers from a list we will put a condition to create a new list which excludes this even numbers. That new list is the result of the filtering condition we applied.
This is the simplest way to read element of the list and check for divisibility with 2. The below code contains for loop which reads the elements and checks for divisibility by 2. Then it appends the correct element to an empty list, which will be the result of the filtering condition.
 Live Demo
list_A = [33, 35, 36, 39, 40, 42]

res = []

for n in list_A:
   if n % 2 == 0:
      res.append(n)
print(res)
Running the above code gives us the following result:
[36, 40, 42]
When we have lists of unknown lengths, we can use a while loop and the len() function to achieve the same thing which was there in the above program.
 Live Demo
list_A = [33, 35, 36, 39, 40, 42]

res = []
n = 0

while (n < len(list_A)):
   if list_A[n] % 2 == 0:
      res.append(list_A[n])
   n += 1
print(res)
Running the above code gives us the following result:
[36, 40, 42]
We can also use a combination of lambda and filter function. The items picked by lambda function can be filtered out from the original list by applying the filter function.
 Live Demo
list_A = [33, 35, 36, 39, 40, 42]

res = []

x = lambda m: m % 2 == 0
res = list(filter(x, list_A))

print(res)
Running the above code gives us the following result:
[36, 40, 42]
Find all triplets in a list with given sum in Python

In a list of numbers we want to find out which three elements can join to give a certain sum. We call it a triplet. And in the list there can be many such triplets. For example, the sum 10 can be generated form numbers 1,6,3 as well as 1,5,4. In this article we will see how to find out all such triplets from a given list of numbers.
This is the traditional approach in which we will create temporary variables. These variables will hold the elements from the list and check if their sum is equating to the required value. Then it will keep accumulating such variables into the final result set.
 Live Demo
def SumTriplets(listA, sum):
   trpltcnt = 0
   res = []

   for i in range(0, len(listA) - 1):

      s = set()
      tmp = []

      # Adding first element
      tmp.append(listA[i])

      current_sum = sum - listA[i]

      for j in range(i + 1, len(listA)):

         if (current_sum - listA[j]) in s:
            trpltcnt += 1

            # Adding second element
            tmp.append(listA[j])

            # Adding third element
            tmp.append(current_sum - listA[j])

            # Appending tuple to the final list
            res.append(tuple(tmp))
            tmp.pop(2)
            tmp.pop(1)
         s.add(listA[j])

   return res


listA = [11,12,13,14,15,16,17,18,19,20]

print("Required triplets:\n",SumTriplets(listA, 40))
Running the above code gives us the following result −
Required triplets:
[(11, 15, 14), (11, 16, 13), (11, 17, 12), (12, 15, 13)]
 Live Demo
from itertools import combinations

listA = [11,12,13,14,15,16,17,18,19,20]

def fsum(val):
      return sum(val) == 40

res = list(filter(fsum,list(combinations(listA, 3))))

print("Required triplets:\n",res)
Running the above code gives us the following result −
Required triplets:
[(11, 12, 17), (11, 13, 16), (11, 14, 15), (12, 13, 15)]
QlikView - Circular Reference

Circular Reference occurs when we can traverse from one table to another using two or more different paths. This means you can join Table1 with Table2 directly using a column or you can also first join Table1 with Table3 and then table3 with Table2. This can lead to incorrect result in the output formed by a data model, which loads all these three tables. QlikView prevents the load of such data into its memory once it recognizes a circular reference.
Let us consider the following three CSV data files, which are used as input for further illustrations.
SalesCountries:
ProductID,ProductCategory,Country,SaleAmount
1,Outdoor Recreation,Italy,4579
2,Clothing,USA,4125
3,Costumes & Accessories,South Korea,6521
4,Athletics,Japan,4125
5,Personal Care,Brazil,5124
6,Arts & Entertainment,China,1245
7,Hardware,South America,456
8,Home & Garden,Peru,241
9,Food,India,1247
10,Home & Garden,Singapore,5462
11,Office Supplies,Hungary,577

ProductCountry:
ProductID, Country
3,Brazil
3,China
2,Korea
1,USA
2,Singapore
7,Sri Lanka
1,Italy

We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file.
After creating the above script, we load the data to QlikView's memory using the command Control+R. This is when we get the error prompt mentioning the presence of circular loop in the tables getting loaded.
To find the exact cause of the above warning we can look at the data model by using the menu command for table viewer - Control+T. The following screen comes up, which clearly shows the circular reference. Here the join between RegionCountry and SalesRegion can be directly achieved using the field Region. It can also be achieved by first going to the table ProductCountry, using the field Country and then mapping ProdcutID with Salesregion.
The above circular reference can be resolved by renaming some of the columns in the data sets so that QlikView does not form an association between the tables automatically using the column names. For this, we will rename country column in RegionCountry to SalesCountry. In the data set ProdcuCountry, we rename the Country column to ProductCountry.
The Rectified data model after renaming the column above can be seen using the command Control+T. Now we can see that the relationship between the tables does not form a loop.
Pressing Control+R to reload the data does not give us the warning anymore and we can use this data to create reports.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Binomial Coefficient in java

Binomial coefficient (c(n, r) or nCr) is calculated using the formula n!/r!*(n-r)!. Following is the Java program find out the binomial coefficient of given integers.
import java.util.Scanner;

public class BinomialCoefficient {
   public static long fact(int i) {
      if(i <= 1) {
         return 1;
      }
      return i * fact(i - 1);
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);  
      System.out.println("Enter n value: ");
     
      int n = sc.nextInt();
      System.out.println("Enter r value: ");
     
      int r = sc.nextInt();
      long ncr = fact(n)/(fact(r)*fact(n-r));
      System.out.println("c("+n+", "+r+") :"+ ncr);
   }
}
Enter n value:
8
Enter r value:
3
c(8, 3) :56
PyQt - QDock Widget

A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. This area is around the central widget.
A dock window can be moved inside the main window, or they can be undocked to be moved into a new area by the user. These properties are controlled by the following QDockWidget class methods −
setWidget()
Sets any QWidget in the dock window’s area
setFloating()
If set to true, the dock window can float
setAllowedAreas()
Sets the areas to which the window can be docked
setFeatures()
Sets the features of dock window
In the following example, top level window is a QMainWindow object. A QTextEdit object is its central widget.
self.setCentralWidget(QTextEdit())

A dockable window is first created.
self.items = QDockWidget("Dockable", self)

A QListWidget object is added as a dock window.
self.listWidget = QListWidget()
self.listWidget.addItem("item1")
self.listWidget.addItem("item2")
self.listWidget.addItem("item3")
self.items.setWidget(self.listWidget)

Dockable object is placed towards the right side of the central widget.
self.addDockWidget(Qt.RightDockWidgetArea, self.items)
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class dockdemo(QMainWindow):
   def __init__(self, parent = None):
      super(dockdemo, self).__init__(parent)
		
      layout = QHBoxLayout()
      bar = self.menuBar()
      file = bar.addMenu("File")
      file.addAction("New")
      file.addAction("save")
      file.addAction("quit")
		
      self.items = QDockWidget("Dockable", self)
      self.listWidget = QListWidget()
      self.listWidget.addItem("item1")
      self.listWidget.addItem("item2")
      self.listWidget.addItem("item3")
		
      self.items.setWidget(self.listWidget)
      self.items.setFloating(False)
      self.setCentralWidget(QTextEdit())
      self.addDockWidget(Qt.RightDockWidgetArea, self.items)
      self.setLayout(layout)
      self.setWindowTitle("Dock demo")
		
def main():
   app = QApplication(sys.argv)
   ex = dockdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page