code-rag-bench/online-tutorials huggingface dataset:
How to update all the entries except a single value in a particular column using MySQL?

To update all the entries while ignoring a single value, you need to use IF().
Let us first create a table −
mysql> create table DemoTable736 (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100),
   isMarried boolean
);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable736(CustomerName,isMarried) values('Chris',0);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Robert',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('David',0);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Mike',0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Bob',0);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable736;
This will produce the following output -
+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 0         |
| 2          | Robert       | 0         |
| 3          | David        | 0         |
| 4          | Mike         | 0         |
| 5          | Carol        | 1         |
| 6          | Bob          | 0         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)
Following is the query to update all the entries except a single value in a particular column using MySQL. Here, we are updating the “isMarried” column −
mysql> update DemoTable736 set isMarried=if(CustomerId=5,1,1);
Query OK, 5 rows affected (0.13 sec)
Rows matched: 6 Changed: 5 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable736;
This will produce the following output -
+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 1         |
| 2          | Robert       | 1         |
| 3          | David        | 1         |
| 4          | Mike         | 1         |
| 5          | Carol        | 1         |
| 6          | Bob          | 1         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)
Final variables in C#

Java has a final keyword, but C# does not have its implementation. Use the sealed or readonly keyword in C# for the same implementation.
The readonly would allow the variables to be assigned a value only once. A field marked "read-only", can only be set once during the construction of an object. It cannot be changed.
class Employee {
   readonly int age;

   Employee(int age) {
      this.age = age;
   }

   void ChangeAge() {
         //age = 27; // Compile error
   }
}
Above, we have set the age field as readonly, which once assigned cannot be changed.
How to Sort CSV by multiple columns in Python ? - GeeksforGeeks

21 Apr, 2021
In this article, we are going to discuss how to sort a CSV file by multiple columns. First, we will convert the CSV file into a data frame then we will sort the data frame by using the sort_values() method. 
Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Return Type: Returns a sorted Data Frame with same dimensions as of the function caller Data Frame.
After converting the CSV file into a data frame, we need to add two or more column names of the CSV file as by parameter in sort_values() method with axis assigned to 0 like below:
sort_values(‘column1’, ‘column2’...’columnn’, axis=0)
CSV file in use:
Below are various examples that depict how to sort a CSV file by multiple columns:
Example 1:
In the below program, we first convert the CSV file into a dataframe, then we sort the dataframe by a single column in ascending order.
Python3
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("diamonds.csv")  # sorting data frame by a columndata.sort_values("carat", axis=0, ascending=True,                 inplace=True, na_position='first')  # displaydata.head(10)
Output:
Example 2:
Here, after converting into a data frame, the CSV file is sorted by multiple columns, the depth column is sorted first in ascending order, then the table column is sorted in ascending order for every depth.
Python3
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("diamonds.csv")  # sorting data frame by multiple columnsdata.sort_values(["depth", "table"], axis=0,                 ascending=True, inplace=True)  # displaydata.head(10)
Output:
Example 3: 
In the below example, the CSV file is sorted in descending order by the depth and then in ascending order by the table for every depth. 
Python3
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("diamonds.csv")  # sorting data frame by multiple columnsdata.sort_values(["depth", "table"], axis=0,                 ascending=[False, True], inplace=True)  # displaydata.head(10)
Output:
Example 4:
Here is another example where the CSV file is sorted by multiple columns.
Python3
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("diamonds.csv")  # sorting data frame by multiple columnsdata.sort_values(["depth", "table", "carat"], axis=0,                 ascending=[False, True, False], inplace=True)  # displaydata.head(10)
Output:
Picked
python-csv
Python-pandas
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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Aptitude | GATE CS 1998 | Question 52 - GeeksforGeeks

06 Sep, 2018
Consider n processes sharing the CPU in a round-robin fashion. Assuming that each process switch takes s seconds, what must be the quantum size q such that the overhead resulting from process switching is minimized but, at the same time, each process is guaranteed to get its turn at the CPU at least every t seconds ?
 (A) a(B) b(C) c(D) dAnswer: (A)Explanation: Each process will get CPU for q seconds and each process wants CPU again after t seconds.Thus, there will be (n-1) processes once after current process gets CPU again. Each process takes s seconds for context switch.
(Qp1)(s)(Qp2)(s)(Qp3)(s)(Qp1) 
It can be seen that since P1 left and arrived again, there have been n context switches and (n-1) processes. Thus, equation will be:
q*(n-1) + n*s <= t
q*(n-1) <= t - n*s
q <= (t-n.s) / (n-1) 
So, option (A) is correct.Quiz of this Question
parthendo
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
4 Bit Binary Incrementer - GeeksforGeeks

29 Apr, 2021
What is 4 Bit Binary Incrementer ?It adds 1 binary value to the existing binary value stored in the register or in other words we can simply say that it increases the value stored in the register by 1.For any n-bit binary incrementer ,‘n’ refers to the storage capacity of the register which needs to be incremented by 1. So we require ‘n’ number of half adders . Thus, in case of 4 bit binary incrementer we require 4 half adders.
Working:
The half adders are connected one after the other , as it has 2 inputs and 2 outputs , so for the LSB ( least significant bit) half adder or the right most half adder is given 1 as direct input( first input) and A0 which is the first bit of the register (second input) , so we get the two output : sum (S0) and carry (C).
The carry(C) from previous half adder is propagated to the next half adder, so the carry output of the previous half adder becomes the input of the next higher order half adder.
So considering the case for 4 half adders the circuit gets in total 4 bits (A0, A1, A2, A3), 1 is added and we get an incremented output. 
Examples:
(Refer to the circuit diagram from right to left for better understanding)
 

1. Input: 1010 ----> After using 4 bit binary incrementer ----> Output: 1011


    1 0 1 0       (Comparing from the circuit 1 0 1 0 is A3, A2, A1, A0 respectively)
        + 1       (1 is added as seen in the diagram also, in the first half adder, 1 is taken as input)
   _________
    1 0 1 1       ( 1 0 1 1 , in the diagram are S3, S2, S1, S0 respectively)
   _________
2. Input: 0010  ---> After using 4 bit binary incrementer ----> Output: 0011

   0 0 1 0
       + 1
  _________
   0 0 1 1
  _________
3. Input: 0011  ---> After using 4 bit binary incrementer ----> Output: 0100

   0 0 1 1
       + 1
   ________
   0 1 0 0
  _________
Computer Organization and Architecture
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximum mode configuration of 8086 microprocessor (Max mode)
Minimum mode configuration of 8086 microprocessor (Min mode)
Microprocessor | 8254 programmable interval timer
Subroutine in 8085
8086 program to convert an 8 bit BCD number into hexadecimal number
Full Adder in Digital Logic
Program for Decimal to Binary Conversion
Introduction of K-Map (Karnaugh Map)
Program for Binary To Decimal Conversion
4-bit binary Adder-Subtractor
Python | Numpy.dsplit() method - GeeksforGeeks

17 Sep, 2019
With the help of Numpy.dsplit()() method, we can get the splitted dimensions of an array by using Numpy.dsplit()() method.
Syntax : Numpy.dsplit(numpy.array(), split_size)
Return : Return the array having splitted dimensions.
Example #1 :
In this example we can see that using Numpy.expand_dims() method, we are able to get the splitted dimensions using this method.
# import numpyimport numpy as np  # using Numpy.dsplit() methodgfg = np.array([[1, 2, 5],                [3, 4, 10],                [5, 6, 15],                [7, 8, 20]])  gfg = gfg.reshape(1, 2, 6)print(gfg)  gfg = np.dsplit(gfg, 2)print(gfg)
Output :
[[[ 1 2 5 3 4 10][ 5 6 15 7 8 20]]]
[array([[[ 1, 2, 5],[ 5, 6, 15]]]),array([[[ 3, 4, 10],[ 7, 8, 20]]])]
Example #2 :
# import numpyimport numpy as np  # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8], [5, 10]])gfg = gfg.reshape(1, 2, 3)print(gfg)  gfg = np.dsplit(gfg, 3)print(gfg)
Output :
[[[ 1 2 7][ 8 5 10]]]
[array([[[1],[8]]]), array([[[2],[5]]]), array([[[ 7],[10]]])]
Python numpy-arrayManipulation
Python-numpy
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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Arithmetic Operations on Images using OpenCV in Python

In this tutorial, we are going to learn about the arithmetic operations on Images using OpenCV. We can apply operations like addition, subtraction, Bitwise Operations, etc.., Let's see how we can perform operations on images.
We need the OpenCV module to perform operations on images. Install the OpenCV module using the following command in the terminal or command line.
pip install opencv-python==4.1.1.26
If you run the above command, you will get the following successful message.
Collecting opencv-python==4.1.1.26
Downloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0
6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w
hl (39.0MB)
Requirement already satisfied: numpy>=1.14.5 in c:\users\hafeezulkareem\anaconda3\l
ib\site-packages (from opencv-python==4.1.1.26) (1.16.2)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.1.1.26
We can add two images using the cv2.addWeighted(). It takes five arguments, two images, and the weight of the final image from both and the light value for the final image.
Now we are going to add those two images into one image.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_1.jpg')
image_two = cv2.imread('_2.jpg')
# adding two images
result_image = cv2.addWeighted(image_one, 0.5, image_two, 0.5, 0)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
   cv2.destroyAllWindows()
Final Image
We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_1.jpg')
image_two = cv2.imread('_2.jpg')
# substracting two images
result_image = cv2.subtract(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
   cv2.destroyAllWindows()
Final Image
If you have any doubts regarding the tutorial, mention them in the comment section.
Redis - Backup

Redis SAVE command is used to create a backup of the current Redis database.
Following is the basic syntax of redis SAVE command.
127.0.0.1:6379> SAVE 

Following example creates a backup of the current database.
127.0.0.1:6379> SAVE  
OK 

This command will create a dump.rdb file in your Redis directory.
To restore Redis data, move Redis backup file (dump.rdb) into your Redis directory and start the server. To get your Redis directory, use CONFIG command of Redis as shown below.
127.0.0.1:6379> CONFIG get dir  
1) "dir" 
2) "/user/tutorialspoint/redis-2.8.13/src" 

In the output of the above command /user/tutorialspoint/redis-2.8.13/src is the directory, where Redis server is installed.
To create Redis backup, an alternate command BGSAVE is also available. This command will start the backup process and run this in the background.
127.0.0.1:6379> BGSAVE  
Background saving started


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
What are the allowed characters in Python function names?

Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps in knowing one entity from another.
Rules for writing identifiers
Identifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_3 and print_to_screen, all are valid examples.
An identifier cannot start with a digit. 2variable is invalid, but variable2 is perfectly correct.
Keywords cannot be used as identifiers. The word ‘global’ is a keyword in python. So we get an invalid syntax error here
global = "syntex"
print global
File "identifiers1.py", line 3
    global = "syntex"
           ^
SyntaxError: invalid syntax
Explanation:
The above code when run shows error because keyword global is used
as a variable/identifier for assigning a string value.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
$local = 5
print $local
File "identifiers2.py", line 1
    $local = 5
    ^
SyntaxError: invalid syntax
Explanation:
The above code when run shows error because special character $ is used in the variable/identifier for assigning a integer value.
How to subtract elements of two arrays and store the result as a positive array in JavaScript?

Suppose, we have two arrays like these −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
We are required to write a JavaScript function that takes in two such arrays and returns an array of absolute difference between the corresponding elements of the array.
Therefore, for these arrays, the output should look like −
const output = [8,6,4,1,3,3];
We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array.
Following is the code −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
const absDifference = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));
      res[i] = el;
   };
   return res;
};
console.log(absDifference(arr1, arr2));
This will produce the following output in console −
[ 8, 6, 4, 1, 3, 3 ]
How to get typed text from a textbox by using Selenium Webdriver?

We can get the typed text from a textbox with Selenium webdriver. Firstly, we have to enter text in the text box (after being identified with any locators) with the help of the sendKeys method.
Then apply the method getAttribute to obtain the text entered in that field and pass the parameter value to that method. Let us make an attempt to obtain the value entered in the Google search box −
WebElement m = driver.findElement(By.name("q"));
String st = m.getAttribute("value");
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class GetTextTyped{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement t =driver.findElement(By.name("q"));
      t.sendKeys("Tutorialspoint");
      // obtain value with getAttribute
      System.out.println("Value is: " + t.getAttribute("value"));
      driver.quit();
   }
}
String Formatting in Python using % - GeeksforGeeks

19 Nov, 2020
In Python a string of required formatting can be achieved by different methods.Some of them are ;1) Using %2) Using {}3) Using Template Strings
In this article the formatting using % is discussed.
The formatting using % is similar to that of ‘printf’ in C programming language.%d – integer%f – float%s – string%x – hexadecimal%o – octal
The below example describes the use of formatting using % in Python
# Python program to demonstrate the use of formatting using %   # Initialize variable as a string variable = '15'string = "Variable as string = %s" %(variable) print (string )  # Printing as raw data # Thanks to Himanshu Pant for this print ("Variable as raw data = %r" %(variable))  # Convert the variable to integer # And perform check other formatting options   variable = int(variable) # Without this the below statement                         # will give error. string = "Variable as integer = %d" %(variable) print (string) print ("Variable as float = %f" %(variable))   # printing as any string or char after a mark # here i use mayank as a string print ("Variable as printing with special char = %cmayank" %(variable))   print ("Variable as hexadecimal = %x" %(variable))print ("Variable as octal = %o" %(variable)) 
Output :
Variable as string = 15
Variable as raw data = '15'
Variable as integer = 15
Variable as float = 15.000000
Variable as printing with special char = mayank
Variable as hexadecimal = f
Variable as octal = 17

This article is contributed by Nikhil Kumar Singh (nickzuck_007)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
*args and **kwargs in Python
Check if the String has only unicode digits or space in Java

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements.
The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.
Declaration - The java.lang.Character.isDigit() method is declared as follows −
public static boolean isDigit(int codePoint)
The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.
Declaration − The java.lang.String.charAt() method is declared as follows −
public char charAt(int index)
Let us see a program to check whether a String has only unicode digits or space in Java.
 Live Demo
public class Example {
   boolean check(String s) {
    if (s == null) // checks if the String is null {
      return false;
    }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is not a digit and not a space
            if ((Character.isDigit(s.charAt(i)) == false) && (s.charAt(i) != ' ')) {
            return false; // if it is not any of them then it returns false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "0090"; // has only digits so it will return true
      String s1 = "y o y"; // has spaces but also has letters so it will return false
      System.out.println("String "+s+" has only unicode digits or spaces: "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits or spaces: "+e.check(s1));
   }
}
String 0090 has only unicode digits or spaces: true
String y o y has only unicode digits or spaces: false
Kivy – Material design Icon button

24 Feb, 2021
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on an android device even we can use it on Raspberry pi also.  It is an open-source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. Its graphic engine is built over OpenGL ES 2 and has fast graphics pipeline. 
In this article, we will develop a GUI window using kivy framework of python, and we will add material design icon buttons of different sizes on this window.
Approach:
Import required modules.
Create an App class.
Add Buttons.
Return layout.
Run an instance of the class.
Implementation:                  
Python3
# importing mdapp from kivymd frameworkfrom kivymd.app import MDApp  # importing builder from kivyfrom kivy.lang import Builder  # this is the main class which# will render the whole applicationclass uiApp(MDApp):      # method which will render our application    def build(self):        return Builder.load_string("""  MDBoxLayout:    spacing:300    MDIconButton:              # name of mdicon        icon:"language-python"                                  pos_hint: {"center_x": .5, "center_y": .5}        user_font_size: "64sp"                  # bgcolor of iconbutton        md_bg_color:[1,1,0,1]                                     MDIconButton:                  # custom image as mdicon        icon:"gfg.png"                                          pos_hint: {"center_x": .5, "center_y": .5}        user_font_size: "16sp"              MDIconButton:                  icon:"language-python"        pos_hint: {"center_x": .5, "center_y": .5}                                     """)  # running the applicationuiApp().run()
Output:
Python-kivy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Lodash _.clamp() Method

09 Sep, 2020
The _.clamp() method is used to clamp number within the inclusive range within the lower and upper bounds.
Syntax:
_.clamp(number, lower, upper)

Parameters: This method accepts three parameters as mentioned above and described below:
number: This parameter holds the number to clamp.
lower: This parameter holds the lower bound.
upper: This parameter holds the upper bound.
Return Value: This method returns the clamped number.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Use of _.clamp method console.log(_.clamp(2, 3, 5)); console.log(_.clamp(2, -2, -5)); 
Output:
3
-2

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Use of _.clamp method console.log(_.clamp(15, -13, 13)); console.log(_.clamp(-15, -13, 13)); 
Output:
13
-13

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to convert Dict of list to CSV

28 Nov, 2021
Given a dictionary of list d, the task is to write a Python program to write a dictionary into a CSV file.
The idea to solve this problem is to zip the dictionary and then write it into a CSV file. Python provides an in-built module called ‘csv’ for working with CSV files. csv.writer class is used to write into CSV file. csv.writer class provide two methods for writing into csv file.
writerow(): writerow() method is used to write single row.
writerows(): writerows() method is used to write multiple rows.
Python3
# Program to write a dictionary of list to csvimport csv  # dictionary of listd = {"key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i']}  # writing to csv filewith open("test.csv", "w") as outfile:        # creating a csv writer object    writerfile = csv.writer(outfile)          # writing dictionary keys as headings of csv    writerfile.writerow(d.keys())          # writing list of dictionary    writerfile.writerows(zip(*d.values()))
Output:
Python’s zip() function takes iterable as input and returns an iterator object. This iterator generates a series of tuples with each tuple having elements from each of the iterable. 
Here lists in the dictionary are provided as input to the zip() and it will return a series of tuples with each tuple having elements from all lists these tuples will be treated as rows for CSV file.
Example:
Python3
# Program to write a dictionary of list to csvimport csv  # dictionary of listd = {"key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i']}  # writing to csv filewith open("test.csv", "w") as outfile:        # creating a csv writer object    writerfile = csv.writer(outfile)          # writing dictionary keys as headings of csv    writerfile.writerow(d.keys())          # writing list of dictionary    writerfile.writerows(zip(*d.values()))
Output:
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Select into and temporary tables in MS SQL Server

23 Sep, 2020
1. Select into :Suppose a table has some particular rows that has to be transferred to another table of the same database. It can be done using select into statement as follows –
select list into destination from source (where condition) 
Example :There are two tables named student and marks. The marks of the students has to be transferred from marks to student table. This has to be done as :
Select *
from student;
Select *
from marks;
Select mks into student 
from marks;
The marks will be added into the student table. The ‘where’ clause can be used for condition. It is optional.
2. Temporary tables :The user at times wants to create a separate table from the given table values. It has to be done using the temporary tables concept. Temporary tables can be created in two ways: using create table syntax or select into syntax.
Select into :A new table has to created from the student table using select into statement as follows :
Select *
from student;
Select name, rollno into temp_table #details 
from student;
Create table :A new table can be created using create table statement :
Create table #details( name varchar2(30), rollno int);
A new table is created. The values can be copied from the other table as follows :
Insert into #details select name, rollno from student;
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
OS Path module in Python

29 Nov, 2020
This module contains some useful functions on pathnames. The path parameters are either strings or bytes . These functions here are used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned. As there are different versions of operating system so there are several versions of this module in the standard library.Following are some functions of OS Path module.1. os.path.basename(path) : It is used to return the basename of the file . This function basically return the file name from the path given.  
Python3
# basename functionimport osout = os.path.basename("/baz/foo")print(out)
Output:  
'foo'
2. os.path.dirname(path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name.  
Python3
# dirname functionimport osout = os.path.dirname("/baz/foo")print(out)
Output:  
'/baz'
3. os.path.isabs(path) : It specifies whether the path is absolute or not. In Unix system absolute path means path begins with the slash(‘/’) and in Windows that it begins with a (back)slash after chopping off a potential drive letter.  
Python
# isabs functionimport osout = os.path.isabs("/baz/foo")print(out)
Output:  
True
4. os.path.isdir(path) : This function specifies whether the path is existing directory or not.  
Python
# isdir functionimport osout = os.path.isdir("C:\\Users")print(out)
Output:  
True
5. os.path.isfile(path) : This function specifies whether the path is existing file or not.  
Python
# isfile functionimport osout = os.path.isfile("C:\\Users\foo.csv")print(out)
Output:  
True
6. os.path.normcase(path) : This function normalizes the case of the pathname specified. In Unix and Mac OS X system it returns the pathname as it is . But in Windows it converts the path to lowercase and forward slashes to backslashes.  
Python
# normcase function in windowsimport osout = os.path.normcase("/BAz")print(out)
Output:  
'\\baz'
7. os.path.normpath(path) : This function normalizes the path names by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. On Windows, it converts forward slashes to backward slashes .  
Python
# normpath function in Uniximport osout = os.path.normpath("foo/./bar")print(out)
Output:  
'foo/bar'
There are many more functions , you can refer that in python.References : Python Documentation 
Yashadatt
rajavpandian
Python-Library
python-modules
python-os-module
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
How to check a key exists in an array in PHP ?

01 Jun, 2020
We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP.
Examples:
Input : arr = ["Geek1", "Geek2", "1", "2","3"] 
        key = "2"
Output : Found the Key

Input : arr = ["Geek1", "Geek2", "1", "2","3"] 
        key = 9
Output : Key not Found


The problem can be solved using PHP inbuilt function for checking key exists in a given array. The in-built function used for the given problem are:
Method 1: Using array_key_exists() Method: The array_key_exists() function checks whether a specific key or index is present inside an array or not.
Syntax:
boolean array_key_exists( $index, $array )

Example:
PHP
<?php// PHP program to check if a key // exists in an array or not  $array = array(      'names' => array("Geek1", "Geek2", "Geek3"),     'rank' => array('1', '2', '3'));   // Use of array_key_exists() functionif(array_key_exists("rank", $array)) {    echo "Found the Key"; } else{     echo "Key not Found"; }   ?>
Found the Key
Method 2: Using isset() Method: The isset() function checks whether a specific key or index is present inside an array or not.
Syntax:
bool isset( mixed $var, mixed $... )

PHP
<?php// PHP program to check if a key // exists in an array or not  $array = array(      'names' => array("Geek1", "Geek2", "Geek3"),     'rank' => array('1', '2', '3'));   // Use of array_key_exists() functionif(isset($array["rank"])){    echo "Found the Key"; } else{     echo "Key not Found"; }   ?>
Found the Key 
PHP-array
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.extract() in Python

09 Mar, 2022
The numpy.extract() function returns elements of input_array if they satisfy some specified condition. 
Syntax: numpy.extract(condition, array)
Parameters :  
array     : Input array. User apply conditions on input_array elements
condition : [array_like]Condition on the basis of which user extract elements. 
      Applying condition on input_array, if we print condition, it will return an array
      filled with either True or False. Array elements are extracted from the Indices having 
      True value.
Returns : 
Array elements that satisfy the condition.
Python
# Python Program illustrating# numpy.compress method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) a = geek.mod(array, 4) !=0# This will show element status of satisfying conditionprint("\nArray Condition a : \n", a) # This will return elements that satisfy condition "a" conditionprint("\nElements that satisfy condition a  : \n", geek.extract(a, array))   b = array - 4 == 1# This will show element status of satisfying conditionprint("\nArray Condition b : \n", b) # This will return elements that satisfy condition "b" conditionprint("\nElements that satisfy condition b  : \n", geek.extract(b, array))
Output : 
Original array : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Array Condition a : 
 [[False  True]
 [ True  True]
 [False  True]
 [ True  True]
 [False  True]]

Elements that satisfy condition a  : 
 [1 2 3 5 6 7 9]

Array Condition b : 
 [[False False]
 [False False]
 [False  True]
 [False False]
 [False False]]

Elements that satisfy condition b  : 
 [5]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.extract.html#numpy.extract Note : Also, these codes won’t run on online IDE’s. So please, run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Code_r
nidhi_biet
simmytarika5
vinayedula
Python numpy-Sorting Searching
Python-numpy
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
numpy.reshape() in Python

06 Jul, 2022
The numpy.reshape() function shapes an array without changing the data of the array.
Syntax:
numpy.reshape(array, shape, order = 'C')
Parameters : 
array : [array_like]Input array
shape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then shaping
        it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)
order  : [C-contiguous, F-contiguous, A-contiguous; optional]         
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
         ‘A’ means to read / write the elements in Fortran-like index order if,
         array is Fortran contiguous in memory, C-like order otherwise
Return Type: 
Array which is reshaped without changing the data.
Example
Python
# Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print("Original array : \n", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print("\narray reshaped with 2 rows and 4 columns : \n",      array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print("\narray reshaped with 4 rows and 2 columns : \n",      array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print("\nOriginal array reshaped to 3D : \n",      array4)
Output : 
Original array : 
 [0 1 2 3 4 5 6 7]

array reshaped with 2 rows and 4 columns : 
 [[0 1 2 3]
 [4 5 6 7]]

array reshaped with 4 rows and 2 columns : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]]

Original array reshaped to 3D : 
 [[[0 1]
  [2 3]]
 [[4 5]
  [6 7]]]
  
 
 [[0 1 2 3]
 [4 5 6 7]]
References : 
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html
Note: These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AditiGoyal1
saurabh1990aror
jeetasitsarkar
sooda367
knspavankumar
subhajitghosh1997
vinayedula
vasanth2754
simmytarika5
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are non negative real numbers?

30 Nov, 2021
Algebra is a branch of mathematics that is concerned with the analysis of symbols which represent unknown quantities and constants which represent known quantities. The expressions of algebra are made up of terms and each term may consist of variables (an unknown value), coefficient, constants along with mathematical operations attached to them. 
The below-written article is a study of real numbers. The article briefly describes non-negative real numbers along with some sample questions for doubt clearance.
Real numbers are the set of numbers that consists of both rational and irrational numbers. They can either count to be positive or negative. Generally, real numbers are denoted by the alphabetical symbol ‘R’. Some examples of real numbers are -1/2, -5, -11, -0.5, etc. The set of real numbers, whole numbers, rational numbers, and as well as irrational numbers can be expressed in the form of p/q.
Answer:
The set of positive real numbers which are greater than 0 (zero) are the non-negative real numbers.
The statement can be written as,
R ≥ 0
Which means the real numbers are either positive or zero. The set will include numbers like {0,1, 2, 3, 4, 5,...}.
Question 1: Which numbers are not included in the set of real numbers?
Answer:
The imaginary numbers and the irrational numbers which can not be expressed in the form of p/q are not included in the set of real numbers.
Question 2: Is zero included in non-negative real numbers?
Answer:
Yes, all the positive numbers along with zero are included in non-negative real numbers.
Question 3: What are imaginary numbers?
Answer:
The complex numbers which are represented by letters and do not have a constant value are imaginary numbers. They are basically unreal numbers with no constant numerical value.
Picked
Maths MAQ
School Learning
School Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove certain characters from a string in C++?

In this section, we will see how to remove some characters from a string in C++. In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.
Input: A number string “ABAABACCABA”
Output: “BBCCB”
Step 1:Take a string
Step 2: Remove each occurrence of a specific character using remove() function
Step 3: Print the result.
Step 4: End
 Live Demo
#include<iostream>
#include<algorithm>

using namespace std;
main() {
   string my_str = "ABAABACCABA";

   cout << "Initial string: " << my_str << endl;

   my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string
   cout << "Final string: " << my_str;
}
Initial string: ABAABACCABA
Final string: BBCCB
C++ Memory Library - dynamic_pointer_cast

It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*.
Following is the declaration for std::dynamic_pointer_cast.
template <class T, class U>
  shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;
template <class T, class U>
  shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;
sp − Its a shared pointer.
It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*.
noexcep − It doesn't throw any exceptions.
In below example explains about std::dynamic_pointer_cast.
#include <iostream>
#include <memory>

struct A {
   static const char* static_type;
   const char* dynamic_type;
   A() { dynamic_type = static_type; }
};
struct B: A {
   static const char* static_type;
   B() { dynamic_type = static_type; }
};

const char* A::static_type = "sample text A";
const char* B::static_type = "sample text B";

int main () {
   std::shared_ptr<A> foo;
   std::shared_ptr<B> bar;

   bar = std::make_shared<B>();

   foo = std::dynamic_pointer_cast<A>(bar);

   std::cout << "foo's static type: " << foo->static_type << '\n';
   std::cout << "foo's dynamic type: " << foo->dynamic_type << '\n';
   std::cout << "bar's static type: " << bar->static_type << '\n';
   std::cout << "bar's dynamic type: " << bar->dynamic_type << '\n';

   return 0;
}
Let us compile and run the above program, this will produce the following result −
foo's static type: sample text A
foo's dynamic type: sample text B
bar's static type: sample text B
bar's dynamic type: sample text B

 Print
 Add Notes
 Bookmark this page
fmt.Fprintf() Function in Golang With Examples - GeeksforGeeks

26 Feb, 2021
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprintf() function in Go language formats according to a format specifier and writes to w. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. 
Syntax:  
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
Parameters: This function accepts three parameters which are illustrated below-  
w io.Writer: This is the specified standard input or output.
format string: This is containing some strings including verbs.
a ...interface{}: This is the specified constant variables used in the code.
Return Value: It returns the number of bytes written and any write error encountered.Example 1: 
C
// Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport (    "fmt"    "os") // Calling mainfunc main() {     // Declaring some const variables    const name, dept = "GeeksforGeeks", "CS"     // Calling Fprintf() function which returns    // "n" as the number of bytes written and    // "err" as any error ancountered    n, err := fmt.Fprintf(os.Stdout, "%s is a %s portal.\n",                                                name, dept)     // Printing the number of bytes written    fmt.Print(n, " bytes written.\n")     // Printing if any error encountered    fmt.Print(err) }
Output:  
GeeksforGeeks is a CS portal.
30 bytes written.
<nil>
Example 2: 
C
// Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport (    "fmt"    "os") // Calling mainfunc main() {     // Declaring some const variables    const num1, num2, num3 = 5, 10, 15     // Calling Fprintf() function which returns    // "n" as the number of bytes written and    // "err" as any error encountered    n, err := fmt.Fprintf(os.Stdout, "%d + %d = %d.\n",                                      num1, num2, num3)     // Printing the number of bytes written    fmt.Print(n, " bytes written.\n")     // Printing if any error encountered    fmt.Print(err) }
Output:  
5 + 10 = 15.
13 bytes written.
<nil>
 
arorakashish0911
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Defer Keyword in Golang
How to iterate over an Array using for loop in Golang?
Loops in Go Language
Rune in Golang
Class and Object in Golang
Math.Truncate() Method in C#

The Math.Truncate() method in C# is used to compute an integral part of a number, which is Double or Decimal.
public static decimal Truncate(decimal val1)
public static double Truncate(double val2)
Above, there are two syntaxes. The value val1 is the decimal number to truncate, whereas val2 is the double number to truncate.
Let us now see an example to implement Math.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 25.46467m;
      Decimal val2 = 45.9989m;
      Decimal val3 = 678.325m;
      Console.WriteLine(Math.Truncate(val1));
      Console.WriteLine(Math.Truncate(val2));
      Console.WriteLine(Math.Truncate(val3));
   }
}
This will produce the following output −
25
45
678
Let us see another example to implement Math.Truncate() method −
using System;
public class Demo {
   public static void Main(){
      Double val1 = 95.86467;
      Double val2 = 25.11;
      Double val3 = 878.325;
      Console.WriteLine(Math.Truncate(val1));
      Console.WriteLine(Math.Truncate(val2));
      Console.WriteLine(Math.Truncate(val3));
   }
}
This will produce the following output −
95
25
878