code-rag-bench/online-tutorials huggingface dataset:
Convert a Vector into Factor in R Programming - as.factor() Function - GeeksforGeeks

08 Nov, 2021
as.factor() function in R Programming Language is used to convert the passed object(usually Vector) into a Factor.
Syntax: as.factor(object)
Parameters: 
Object: Vector to be converted
R
# Creating a vectorx<-c("female", "male", "male", "female") # Using as.factor() Function# to convert vector into factoras.factor(x)
Output: 
[1] female male   male   female
Levels: female male
Here we are applying this function to the integer vector 
R
data <- c("11.1", "3.11", "32.2", "2.2") as.factor(data)
Output: 
[1] 11.1 3.11 32.2 2.2 
Levels: 11.1 2.2 3.11 32.2
kumar_satyam
R Factor-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Python - Get sum of tuples having same first value

Tuples are python collections or arrays which are ordered but unchangeable. If we get a number of tuples where the first element is the same, then we may have a scenario when we need to add the second elements of those tuples whose first elements are equal.
In this method we will first consider a list made up of tuples. Then convert them to dictionary so that we can associate the elements in the tuple as key value pair. Then we apply the for loop with summing the value for each key o the dictionary. Finally use the map function to get back the list which has the summed up values.
 Live Demo
List = [(3,19),(7, 31), (7, 50), (1, 25.5), (1, 12)]
# Converting it to a dictionary
tup = {i:0 for i, v in List}
for key, value in List:
   tup[key] = tup[key]+value
# using map
result = list(map(tuple, tup.items()))
print(result)
Running the above code gives us the following result:
[(3, 19), (7, 81), (1, 37.5)]
Here we take a similar approach as above but use the defaultdict method of collections module. Now instead of using the map function, we access the dictionary items and convert them to a list.
 Live Demo
from collections import defaultdict
# list of tuple
List = [(3,19),(7, 31), (7, 50), (1, 25.5), (1, 12)]
dict = defaultdict(int)
for key, value in List:
   dict[key] = dict[key]+value
# Printing output
print(list(dict.items()))
Running the above code gives us the following result
[(3, 19), (7, 81), (1, 37.5)]
MySQL error 1452 - Cannot add or update a child row: a foreign key constraint fails?

This error comes whenever we add a foreign key constraint between tables and insert records into the child table. Let us see an example.
Creating the child table.
mysql> create table ChildDemo
   -> (
   -> id int,
   -> FKPK int
   -> );
Query OK, 0 rows affected (0.86 sec)
Creating the second table.
mysql> create table ParentDemo
   -> (
   -> FKPK int,
   -> Name varchar(100)
   -> ,
   -> primary key(FKPK)
   -> );
Query OK, 0 rows affected (0.57 sec)
To add foreign key constraint.
mysql> alter table ChildDemo add constraint ConstChild foreign key(FKPK) references ParentDemo(FKPK);
Query OK, 0 rows affected (1.97 sec)
Records: 0  Duplicates: 0  Warnings: 0
After creating foreign key constraint, whenever we insert records into the first table or child table, we will get the above error.
mysql> insert into ChildDemo values(1,3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`business`.`childdemo`, CONSTRAINT `ConstChild` FOREIGN KEY (`FKPK`) REFERENCES `parentdemo` (`fkpk`))
The error comes when you are trying to add a row for which no matching row in in the other table.
As stated
“Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. It will reject any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.”
How to check if a string is a valid keyword in Python?

Like other languages, Python also has some reserved words. These words hold some special meaning. Sometimes it may be a command, or a parameter etc. We cannot use keywords as variable names.
In this section we will see how to check a string is valid keyword or not.
To check this things, we have to import the keyword module in Python.
import keyword

In the keyword module, there is a function iskeyword(). It can be used to check whether a string is valid keyword or not.
In the following example, we are providing a list of words, and check whether the words are keywords or not. We are just separating the keywords and non-keywords using this program.
 Live Demo
import keyword
str_list = ['for', 'TP', 'python', 'del', 'Mango', 'assert', 'yield','if','Lion', 'as','Snake', 'box', 'return', 'try', 'loop', 'eye', 'global', 'while', 'update', 'is']
keyword_list = []
non_keyword_list = []
for item in str_list:
   if keyword.iskeyword(item):
      keyword_list.append(item)
   else:
      non_keyword_list.append(item)
print("Keywords: " + str(keyword_list))
print("\nNon Keywords: " + str(non_keyword_list))
Keywords: ['for']

Non Keywords: ['TP']
Keywords: ['for']

Non Keywords: ['TP', 'python']
Keywords: ['for', 'del']

Non Keywords: ['TP', 'python', 'Mango']
Keywords: ['for', 'del', 'assert', 'yield', 'if']

Non Keywords: ['TP', 'python', 'Mango', 'Lion']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try', 'global', 'while']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye', 'update']

The keyword module has another option to get all of the keywords as a list.
 Live Demo
import keyword
print("All Keywords:")
print(keyword.kwlist)
All Keywords:['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
MySQL select to convert numbers to millions and billions format?

You can use FORMAT() from MySQL to convert numbers to millions and billions format. Let us first create a table−
mysql> create table DemoTable
   (
   Value BIGINT
   );
Query OK, 0 rows affected (0.74 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(78000000000);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(10000000000);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(90000000000);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(450600000000);
Query OK, 1 row affected (0.41 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Value        |
+--------------+
| 78000000000  |
| 10000000000  |
| 90000000000  |
| 450600000000 |
+--------------+
4 rows in set (0.00 sec)
Following is the query to convert numbers to million and billions format−
mysql> select format(Value,0) as `FormatValue` from DemoTable;
This will produce the following output−
+-----------------+
| FormatValue     |
+-----------------+
| 78,000,000,000  |
| 10,000,000,000  |
| 90,000,000,000  |
| 450,600,000,000 |
+-----------------+
4 rows in set (0.00 sec)
Independent Vertex Set

Independent sets are represented in sets, in which
there should not be any edges adjacent to each other. There should not be any common vertex between any two edges.
there should not be any edges adjacent to each other. There should not be any common vertex between any two edges.
there should not be any vertices adjacent to each other. There should not be any common edge between any two vertices.
there should not be any vertices adjacent to each other. There should not be any common edge between any two vertices.
Let 'G' = (V, E) be a graph. A subset of 'V' is called an independent set of 'G' if no two vertices in 'S' are adjacent.
Consider the following subsets from the above graphs −
S1 = {e}
S2 = {e, f}
S3 = {a, g, c}
S4 = {e, d}
Clearly, S1 is not an independent vertex set, because for getting an independent vertex set, there should be at least two vertices in the form a graph. But here it is not that case. The subsets S2, S3, and S4 are the independent vertex sets because there is no vertex that is adjacent to anyone vertex from the subsets.
Let 'G' be a graph, then an independent vertex set of 'G' is said to be maximal if no other vertex of 'G' can be added to 'S'.
Consider the following subsets from the above graphs.
S1 = {e}
S2 = {e, f}
S3 = {a, g, c}
S4 = {e, d}
S2 and S3 are maximal independent vertex sets of 'G'. In S1 and S4, we can add other vertices; but in S2 and S3, we cannot add any other vertex
A maximal independent vertex set of 'G' with a maximum number of vertices is called the maximum independent vertex set.
Consider the following subsets from the above graph −
S1 = {e}
S2 = {e, f}
S3 = {a, g, c}
S4 = {e, d}
Only S3 is the maximum independent vertex set, as it covers the highest number of vertices. The number of vertices in a maximum independent vertex set of 'G' is called the independent vertex number of G (β2).
For the complete graph Kn,
Vertex covering number = α2 = n-1
Vertex independent number = β2 = 1
You have α2 + β2 = n
In a complete graph, each vertex is adjacent to its remaining (n − 1) vertices. Therefore, a maximum independent set of Kn contains only one vertex.
Therefore, β2=1
and α2=|v| − β2 = n-1
Note − For any graph 'G' = (V, E)
α2 + β2 = |v|
α2 + β2 = |v|
If 'S' is an independent vertex set of 'G', then (V – S) is a vertex cover of G.
If 'S' is an independent vertex set of 'G', then (V – S) is a vertex cover of G.
Python - Tagging Words

Tagging is an essential feature of text processing where we tag the words into grammatical categorization. We take help of tokenization and pos_tag function to create the tags for each word.
import nltk

text = nltk.word_tokenize("A Python is a serpent which eats eggs from the nest")
tagged_text=nltk.pos_tag(text)
print(tagged_text)
When we run the above program, we get the following output −
[('A', 'DT'), ('Python', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('serpent', 'NN'), 
('which', 'WDT'), ('eats', 'VBZ'), ('eggs', 'NNS'), ('from', 'IN'), 
('the', 'DT'), ('nest', 'JJS')]

 We can describe the meaning of each tag by using the following program which shows the in-built values.
import nltk

nltk.help.upenn_tagset('NN')
nltk.help.upenn_tagset('IN')
nltk.help.upenn_tagset('DT')
When we run the above program, we get the following output −
NN: noun, common, singular or mass
    common-carrier cabbage knuckle-duster Casino afghan shed thermostat
    investment slide humour falloff slick wind hyena override subhumanity
    machinist ...
IN: preposition or conjunction, subordinating
    astride among uppon whether out inside pro despite on by throughout
    below within for towards near behind atop around if like until below
    next into if beside ...
DT: determiner
    all an another any both del each either every half la many much nary
    neither no some such that the them these this those

 We can also tag a corpus data and see the tagged result for each word in that corpus.
import nltk

from nltk.tokenize import sent_tokenize
from nltk.corpus import gutenberg
sample = gutenberg.raw("blake-poems.txt")
tokenized = sent_tokenize(sample)
for i in tokenized[:2]:
            words = nltk.word_tokenize(i)
            tagged = nltk.pos_tag(words)
            print(tagged)

When we run the above program we get the following output −
[([', 'JJ'), (Poems', 'NNP'), (by', 'IN'), (William', 'NNP'), (Blake', 'NNP'), (1789', 'CD'), 
(]', 'NNP'), (SONGS', 'NNP'), (OF', 'NNP'), (INNOCENCE', 'NNP'), (AND', 'NNP'), (OF', 'NNP'), 
(EXPERIENCE', 'NNP'), (and', 'CC'), (THE', 'NNP'), (BOOK', 'NNP'), (of', 'IN'), 
(THEL', 'NNP'), (SONGS', 'NNP'), (OF', 'NNP'), (INNOCENCE', 'NNP'), (INTRODUCTION', 'NNP'), 
(Piping', 'VBG'), (down', 'RP'), (the', 'DT'), (valleys', 'NN'), (wild', 'JJ'), 
(,', ','), (Piping', 'NNP'), (songs', 'NNS'), (of', 'IN'), (pleasant', 'JJ'), (glee', 'NN'),
 (,', ','), (On', 'IN'), (a', 'DT'), (cloud', 'NN'), (I', 'PRP'), (saw', 'VBD'), 
 (a', 'DT'), (child', 'NN'), (,', ','), (And', 'CC'), (he', 'PRP'), (laughing', 'VBG'), 
 (said', 'VBD'), (to', 'TO'), (me', 'PRP'), (:', ':'), (``', '``'), (Pipe', 'VB'),
 (a', 'DT'), (song', 'NN'), (about', 'IN'), (a', 'DT'), (Lamb', 'NN'), (!', '.'), (u"''", "''")]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2005 | Question 90 - GeeksforGeeks

28 Jun, 2021
Let E1 and E2 be two entities in an E/R diagram with simple single-valued attributes. R1 and R2 are two relationships between E1 and E2, where R1 is one-to-many and R2 is many-to-many. R1 and R2 do not have any attributes of their own. What is the minimum number of tables required to represent this situation in the relational model?(A) 2(B) 3(C) 4(D) 5Answer: (B)Explanation: The answer is B, i.e minimum 3 tables.
Strong entities E1 and E2 are represented as separate tables.
In addition to that many-to-many relationships(R2) must be converted as separate table by having primary keys of E1 and E2 as foreign keys.
One-to-many relaionship (R1) must be transferred to ‘many’ side table(i.e. E2) by having primary key of one side(E1) as foreign key( this way we need not to make a separate table for R1).
Let relation schema be E1(a1,a2) and E2( b1,b2).
Relation E1( a1 is the key)
a1 a2
-------
1 3
2 4
3 4
Relation E2( b1 is the key, a1 is the foreign key, hence R1(one-many) relationship set satisfy here )
b1 b2 a1
-----------
7 4 2
8 7 2
9 7 3
Relation R2 ( {a1, b1} combined is the key here , representing many-many relationship R2 )
a1 b1
--------
1 7
1 8
2 9
3 9
Hence we will have minimum of 3 tables.Quiz of this Question
ManasChhabra2
GATE-CS-2005
GATE-GATE-CS-2005
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
Program to sort array by increasing frequency of elements in Python

Suppose we have an array with some elements where elements may appear multiple times. We have to sort the array such that elements are sorted according to their increase of frequency. So which element appears less number of time will come first and so on.
So, if the input is like nums = [1,5,3,1,3,1,2,5], then the output will be [2, 5, 5, 3, 3, 1, 1, 1]
To solve this, we will follow these steps −
mp := a new map
mp := a new map
for each distinct element i from nums, dox:= number of i present in numsif x is present in mp, theninsert i at the end of mp[x]otherwise mp[x] := a list with only one element i
for each distinct element i from nums, do
x:= number of i present in nums
x:= number of i present in nums
if x is present in mp, theninsert i at the end of mp[x]
if x is present in mp, then
insert i at the end of mp[x]
insert i at the end of mp[x]
otherwise mp[x] := a list with only one element i
otherwise mp[x] := a list with only one element i
ans:= a new list
ans:= a new list
for each i in sort the mp based on key, dofor each j in sort the list mp[i] in reverse order, doinsert j, i number of times into ans
for each i in sort the mp based on key, do
for each j in sort the list mp[i] in reverse order, doinsert j, i number of times into ans
for each j in sort the list mp[i] in reverse order, do
insert j, i number of times into ans
insert j, i number of times into ans
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
def solve(nums):
   mp = {}
   for i in set(nums):
      x=nums.count(i)
      try:
         mp[x].append(i)
      except:
         mp[x]=[i]
   ans=[]

   for i in sorted(mp):
      for j in sorted(mp[i], reverse=True):
         ans.extend([j]*i)
   return ans

nums = [1,5,3,1,3,1,2,5]
print(solve(nums))
[1,5,3,1,3,1,2,5]
[2, 5, 5, 3, 3, 1, 1, 1]
Single-Row and Multi-Row Partitions in Cassandra - GeeksforGeeks

15 Feb, 2021
In Cassandra, CQL(Cassandra Query Language) has two partitions as follows –
Single-Row Partitions
Multi-Row Partitions
Single-Row Partitions :In Cassandra, the primary key represents a unique data partition and the clustering columns part are also helpful for data arrangement and are used to handle the data arrangement part. In Single-Row partitions, there is only a partitioning key on single column.
Example –Let us take the Employee table having fields like Emp_id, Emp_name, Emp_email, where Emp_id is the primary key. 
CREATE table Employee(
Emp_id UUID, 
Emp_name TEXT, 
Emp_email TEXT,
primary key(Emp_id)
);
You can check the partitioning logical reference model for the above example as follows –
K - Primary key
C - Clustering column
S - Static column
In Cassandra, the Primary key is the combination of the Partitioning key and Clustering column if any. 
Primary Key = Partition Key + [Clustering Columns]
Multi-Row Partitions :In Multi-Row partitions, partitioning key is applied on more than one single column and clustering column for arrangement or partitioning data modelling.
Example –Let us take the Event table having fields like Event_venue, Event_year, Event_artifact, Events_title, Events_country, where Event_venue, Event_year are the primary keys and Event_artifact is the clustering column key. 
CREATE table Events(
Event_venue TEXT, 
Event_year INT,
Event_artifact TEXT,
Events_title TEXT,
Events_country TEXT STATIC,
primary key((Event_venue, Event_year), Event_artifact)
);
You can check partitioning logical reference model for above example as follows –
K - Primary key
C - Clustering column
S - Static column
NoSQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL indexes
SQL Query to Compare Two Dates
How to clear Tkinter Canvas?

Tkinter provides a way to add a canvas in a window and when we create a canvas, it wraps up some storage inside the memory. While creating a canvas in tkinter, it will effectively eat some memory which needs to be cleared or deleted.
In order to clear a canvas, we can use the delete() method. By specifying “all”, we can delete and clear all the canvas that are present in a tkinter frame.
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("650x250")

#Creating a canvas
myCanvas =Canvas(win, bg="white", height=200, width=200)
cordinates= 10, 10, 200, 200
arc = myCanvas.create_arc(cordinates, start=0, extent=320, fill="red")
myCanvas.pack()

#Clearing the canvas
myCanvas.delete('all')

win.mainloop()

The above code will clear the canvas,
First, mark the following line as a comment and execute the code.
myCanvas.delete('all')
It will produce the following window: 
Now, uncomment the line and execute again to clear the canvas.
How to convert Python dictionary keys/values to lowercase?

You can convert Python dictionary keys/values to lowercase by simply iterating over them and creating a new dict from the keys and values. For example,
def lower_dict(d):
   new_dict = dict((k.lower(), v.lower()) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))
This will give the output
{'foo': 'hello', 'bar': 'world'}
If you want just the keys to be lower cased, you can call lower on just that. For example,
def lower_dict(d):
   new_dict = dict((k.lower(), v) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))
This will give the output
{'foo': 'Hello', 'bar': 'World'}
Pretty print JSON using javax.json API in Java?


The javax.json package provides an Object Model API to process JSON. The Object Model API is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures can be represented as object models using JsonObject and JsonArray interfaces. We can use the JsonGenerator interface to write the JSON data to an output in a streaming way. The JsonGenerator.PRETTY_PRINTING is a configuration property to generate JSON prettily.
We can implement a pretty print JSON in the below example.
import java.io.*;
import java.util.*;
import javax.json.*;
import javax.json.stream.*;
public class JSONPrettyPrintTest {
   public static void main(String args[]) {
      String jsonString = "{\"name\":\"Raja Ramesh\",\"age\":\"35\",\"salary\":\"40000\"}";
      StringWriter sw = new StringWriter();
      try {
         JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
         JsonObject jsonObj = jsonReader.readObject();
         Map<String, Object> map = new HashMap<>();
         map.put(JsonGenerator.PRETTY_PRINTING, true);
         JsonWriterFactory writerFactory = Json.createWriterFactory(map);
         JsonWriter jsonWriter = writerFactory.createWriter(sw);
         jsonWriter.writeObject(jsonObj);
         jsonWriter.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
      String prettyPrint = sw.toString();
      System.out.println(prettyPrint); // pretty print JSON
   }
}
{
   "name": "Raja Ramesh",
 "age": "35",
  "salary": "40000"
}
Koa.js - Static Files

Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default doesn't allow you to serve static files.
We need a middleware to serve this purpose. Go ahead and install koa-serve −
$ npm install --save koa-static

Now we need to use this middleware. Before that create a directory called public. We will store all our static files here. This allows us to keep our server code secure as nothing above this public folder would be accessible to the clients. After you've created a public directory, create a file named hello.txt in it with any content you like. Now add the following to your app.js.
var serve = require('koa-static');
var koa = require('koa');
var app = koa();

app.use(serve('./public'));

app.listen(3000);
Note − Koa looks up the files relative to the static directory, so the name of the static directory is not part of the URL. The root route is now set to your public dir, so all static files you load will be considering public as the root. To test that this is working fine, run your app and visit https://localhost:3000/hello.txt
You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file.
We can also set multiple static assets directories using −
var serve = require('koa-static');
var koa = require('koa');
var app = koa();

app.use(serve('./public'));
app.use(serve('./images'));

app.listen(3000);
Now when we request a file, Koa will search these directories and send us the matching file.
 Print
 Add Notes
 Bookmark this page
C++ IOS Library - Flags

It is used to get/set format flags. The format flags of a stream affect the way data is interpreted in certain input functions and how these are written by certain output functions. See ios_base::fmtflags for the possible values of this function's argument and the interpretation of its return value.
The second form of this function sets the value for all the format flags of the stream, overwriting the existing values and clearing any flag not explicitly set in the argument. To access individual flags, see members setf and unsetf.
Following is the declaration for ios_base::flags function.
get (1)	fmtflags flags() const;
set (2)	fmtflags flags (fmtflags fmtfl);
The first form (1) returns the format flags currently selected in the stream.
The second form (2) sets new format flags for the stream, returning its former value.
fmtfl − Format flags to be used by the stream. ios_base::fmtflags is a bitmask type.
The format flags selected in the stream before the call.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
Concurrent access to the same stream object may cause data races.
In below example explains about ios_base::flags function.
#include <iostream>     

int main () {
   std::cout.flags ( std::ios::right | std::ios::hex | std::ios::showbase );
   std::cout.width (10);
   std::cout << 100 << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
  0x64

 Print
 Add Notes
 Bookmark this page
Python - Plotting Pie charts in excel sheet using XlsxWriter module

A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice, is proportional to the quantity it represents.
# import xlsxwriter module
import xlsxwriter
# Workbook() takes one, non-optional, argument which is the filename #that we want to create.
workbook = xlsxwriter.Workbook('chart_pie.xlsx')
# The workbook object is then used to add new worksheet via the #add_worksheet() method.
worksheet = workbook.add_worksheet()
# Create a new Format object to formats cells in worksheets using #add_format() method .  
# here we create bold format object .
bold = workbook.add_format({'bold': 1})  
# create a data list .
headings = ['Category', 'Values']
data = [
   ['Apple', 'Cherry', 'Pecan'],
   [60, 30, 10],
]  
# Write a row of data starting from 'A1' with bold format.
worksheet.write_row('A1', headings, bold)  
# Write a column of data starting from A2, B2, C2 respectively.
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])  
# Create a chart object that can be added to a worksheet using #add_chart() method.  
# here we create a pie chart object .
chart1 = workbook.add_chart({'type': 'pie'})  
# Add a data series to a chart using add_series method.
# Configure the first series.
#[sheetname, first_row, first_col, last_row, last_col].
chart1.add_series({
   'name':       'Pie sales data',
   'categories': ['Sheet1', 1, 0, 3, 0],
   'values':     ['Sheet1', 1, 1, 3, 1],
})
# Add a chart title
chart1.set_title({'name': 'Popular Pie Types'})
# Set an Excel chart style. Colors with white outline and shadow.
chart1.set_style(10)
# Insert the chart into the worksheet(with an offset).
# the top-left corner of a chart is anchored to cell C2.
worksheet.insert_chart('C2', chart1, {'x_offset': 25, 'y_offset': 10})
# Finally, close the Excel file via the close() method.  
workbook.close()
Dart Programming - do while Loop

The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. However, the condition is evaluated for the subsequent iterations. In other words, the code block will be executed at least once in a do...while loop.
The following illustration shows the flowchart of the do...while loop −
Following is the syntax for the do-while loop. 
do {  
   Statement(s) to be executed;  
} while (expression); 

Note − Don’t miss the semicolon used at the end of the do...while loop.
void main() { 
   var n = 10; 
   do { 
      print(n); 
      n--; 
   }
   while(n>=0); 
}  
The example prints numbers from 0 to 10 in the reverse order. The following output is displayed on successful execution of the above code.
10 
9 
8 
7 
6 
5 
4 
3 
2 
1 
0


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to create a Cumulative Sum Column in MySQL?

To create a cumulative sum column in MySQL, you need to create a variable and set to value to 0. Cumulative sum increments the next value step by step with current value.
Firstly, you need to create a variable with the help of SET. The syntax is as follows −
set @anyVariableName:= 0;
The syntax to create a cumulative sum column in MySQL is as follows −
select yourColumnName1,yourColumnName2,........N,(@anyVariableName := @anyVariableName + yourColumnName2) as anyVariableName
from yourTableName order by yourColumnName1;
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table CumulativeSumDemo
   −> (
   −> BookId int,
   −> BookPrice int
   −> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table with the help of select statement. The query to insert record is as follows −
mysql> insert into CumulativeSumDemo values(101,400);
Query OK, 1 row affected (0.15 sec)

mysql> insert into CumulativeSumDemo values(102,500);
Query OK, 1 row affected (0.16 sec)

mysql> insert into CumulativeSumDemo values(103,600);
Query OK, 1 row affected (0.16 sec)

mysql> insert into CumulativeSumDemo values(104,1000);
Query OK, 1 row affected (0.18 sec)
Display all records which I have inserted with the help of insert command. The query is as follows −
mysql> select *from CumulativeSumDemo;
The following is the output −
+--------+-----------+
| BookId | BookPrice |
+--------+-----------+
|    101 |       400 |
|    102 |       500 |
|    103 |       600 |
|    104 |      1000 |
+--------+-----------+
4 rows in set (0.00 sec)
To add cumulative sum column, first you need to create a variable. The query is as follows −
mysql> set @CumulativeSum := 0;
Query OK, 0 rows affected (0.00 sec)
Implement the above syntax discussed in the beginning to add a cumulative sum column. The query is as follows −
mysql> select BookId,BookPrice,(@CumulativeSum := @CumulativeSum + BookPrice) as CumSum
   −> from CumulativeSumDemo order by BookId;
The following is the output. Here the cumulative sum column is also visible −
+--------+-----------+--------+
| BookId | BookPrice | CumSum |
+--------+-----------+--------+
|    101 |       400 |    400 |
|    102 |       500 |    900 |
|    103 |       600 |   1500 |
|    104 |      1000 |   2500 |
+--------+-----------+--------+
4 rows in set (0.00 sec)
Download image with Selenium Python

We can download images with Selenium webdriver in Python. First of
all, we shall identify the image that we want to download with the help of the
locators like id, class, xpath, and so on.
We shall use the open method for opening the file in write and binary mode (is represented by wb). Then capture the screenshot of the element that we desire to capture with the screenshot_as_png method.
Finally, the captured image must be written to the opened file with the write
method. Let us make an attempt to download the image of an element having
the below html −
with open('Logo.png', 'wb') as file:
file.write(driver.find_element_by_xpath('//*[@alt="I"]').screenshot_as_png)
from selenium import webdriver
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm");
#open file in write and binary mode
with open('Logo.png', 'wb') as file:
#identify image to be captured
   l = driver.find_element_by_xpath('//*[@alt="Tutorialspoint"]')
#write file
   file.write(l.screenshot_as_png)
#close browser
driver.quit()
File Logo.png gets created in the project folder.
On opening the file −
Find the tuples containing the given element from a list of tuples in Python

A list can have tuples as its elements. In this article we will learn how to identify those tuples which contain a specific search element which is a string.
We can design a follow with in condition. After in we can mention the condition or a combination of conditions.
 Live Demo
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng for and if
res = [item for item in listA
   if item[0] == test_elem and item[1] >= 2]
# printing res
print("The tuples satisfying the conditions:\n ",res)
Running the above code gives us the following result −
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
We use the filter function along with Lambda function. In the filter condition we use the the in operator to check for the presence of the element in the tuple.
 Live Demo
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng lambda and in
res = list(filter(lambda x:test_elem in x, listA))
# printing res
print("The tuples satisfying the conditions:\n ",res)
Running the above code gives us the following result −
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
Loop through a hash table using Javascript

Now let us create a forEach function that'll allow us to loop over all key-value pairs and call a callback on those values. For this, we just need to loop over each chain in the container and call the callback on the key and value pairs.
forEach(callback) {
   // For each chain
   this.container.forEach(elem => {
      // For each element in each chain call callback on KV pair
      elem.forEach(({ key, value }) => callback(key, value));
   });
}
You can test this using.
let ht = new HashTable();
ht.put(10, 94); ht.put(20, 72);
ht.put(30, 1); ht.put(21, 6);
ht.put(15, 21);
ht.put(32, 34);

let sum = 0;

// Add all the values together
ht.forEach((k, v) => sum += v)

console.log(sum);
This will give the output.
228
Batch Script - EXPAND

This batch command extracts files from compressed .cab cabinet files.
EXPAND [cabinetfilename]

@echo off 
EXPAND excel.cab
The above command will extract the contents of the file excel.cab in the current location.
 Print
 Add Notes
 Bookmark this page
PHP variable Variables

In PHP, it is possible to set variable name dynamically. Such a variable uses value of an existing variable as name. A variable variable is defined with two $ signs as prefix
 Live Demo
<?php
$var1="xyz"; //normal variable
$$var1="abcd";//variable variable
echo $var1 . "\n";
echo $$var1 . "\n";
echo "{$$var1} $xyz";
?>
This script produces following output
xyz
abcd
abcd abcd
Note that value of $$var1 is same as $xyz, xyz being value of $var1.
Numeric value of normal variable cannot be used as variable variable
 Live Demo
<?php
$var1=100; //normal variable
$$var1=200;//variable variable
echo $var1 . "\n";
echo $$var1 . "\n";
echo $100;
?>
When this script is executed, following result is displayed
PHP Parse error: syntax error, unexpected '100' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' line 6
It is also possible to define a variable variable in terms of an array subscript. In following example, a variable variable is defines using 0th element of a normal array
 Live Demo
<?php
$var1=array("aa","bb"); //normal variable
${$var1[0]}=10;//variable variable with array element
echo $var1[0] . "\n";
echo $aa . "\n";
echo ${$var1[0]} . "\n";
?>
This will produce following result −
aa
10
10
Class properties are also accessible using variable property names. This feature is useful when a propery name is made up of an array.
<?php
var $u = "Architecture";
var $ugCourses = array("CSE","MECH","CIVIL");
$obj = new branches();
$courses = "ugCourses";
echo $obj->{$courses[0]} . "\n";
echo $obj->{$courses}[0] . "\n";
?>
This will produce following result −
Architecture
CSE
What is the use of $Lastexitcode and $? Variable in PowerShell?

$LastExitCode in Powershell is the number that represents the exit code/error level of the last script or application executed and $? (Dollar hook) also represents the success or the failure of the last command. In general, both represent the same but the output method is different. The first command output is in the Number format (0 and 1) and the latter command is for Boolean (True or False) output.
For example,
PS C:\WINDOWS\system32> $LASTEXITCODE
0
PS C:\WINDOWS\system32> $?
True
As you see the output, 0 represents the success status of the $LastExitCode command and $True for the $?.
Now if the command doesn’t run successfully then what output you will get for both the commands. Check the below example.
PS C:\WINDOWS\system32> ping anyhost.test
Ping request could not find host anyhost.test. Please check the name and try
again.
PS C:\WINDOWS\system32> $LASTEXITCODE
1
PS C:\WINDOWS\system32> $?
True
And you terminate the output of any command in the middle of execution, $lastexitcode will be different but $? command output will be true as the command exists and it can resolve the domain.
PS C:\WINDOWS\system32> ping google.com

Pinging google.com [172.217.166.174] with 32 bytes of data:
Reply from 172.217.166.174: bytes=32 time=30ms TTL=55

Ping statistics for 172.217.166.174:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 30ms, Maximum = 30ms, Average = 30ms
Control-C
PS C:\WINDOWS\system32> $LASTEXITCODE
-1073741510
PS C:\WINDOWS\system32> $?
True
C# | Math.Pow() Method - GeeksforGeeks

31 Jan, 2019
In C#, Math.Pow() is a Math class method. This method is used to calculate a number raise to the power of some other number.
Syntax:
public static double Pow(double base, double power)

Parameters:
double base: It is a double-precision floating-point number which is to be raised to a power and type of this parameter is System.Double.
double power: It is a double-precision floating-point number which specifies a power or exponent and type of this parameter is System.Double.
Return Type: The function returns the number base raised to the power. The type of this method is System.Double
Examples:
Input  : base = 8, power =2 
Output : 64

Input  : base = 2.5, power =3
Output : 15.625

Program: To demonstrate the Math.Pow()
// C# program to illustrate the // Math.Pow() functionusing System;class GFG {      // Main Method    static public void Main()    {          // Find power using Math.Pow        // 6 is base and 2 is power or        // index or exponent of a number        double pow_ab = Math.Pow(6, 2);          // Print the result        Console.WriteLine(pow_ab);          // 3.5 is base and 3 is power or        // index or exponent of a number        double pow_tt = Math.Pow(3.5, 3);          // Print the result        Console.WriteLine(pow_tt);          // 202 is base and 4 is power or        // index or exponent of a number        double pow_t = Math.Pow(202, 4);          // Print the result        Console.WriteLine(pow_t);    }}
Output:
36
42.875
1664966416

Reference: https://msdn.microsoft.com/en-us/library/system.math.pow(v=vs.110).aspx
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
Dart Programming - Functions

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
A function definition specifies what and how a specific task would be done.
A function must be called so as to execute it.
Functions may also return value along with control, back to the caller.
Parameters are a mechanism to pass values to functions.
Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function.
We have three types of optional parameters in Dart −
To specify optional positional parameters, use square [] brackets.
Unlike positional parameters, the parameter's name must be specified while the value is being passed. Curly brace {} can be used to specify optional named parameters.
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.
Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
void main() { 
   print(factorial(6));
}  
factorial(number) { 
   if (number <= 0) {         
      // termination case 
      return 1; 
   } else { 
      return (number * factorial(number - 1));    
      // function invokes itself 
   } 
}   
It should produce the following output −
720

Lambda functions are a concise mechanism to represent functions. These functions are also called as Arrow functions.
[return_type]function_name(parameters)=>expression;

void main() { 
   printMsg(); 
   print(test()); 
}  
printMsg()=>
print("hello"); 

int test()=>123;                       
// returning function
It should produce the following output −
hello 123 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2017 (Set 1) | Question 45 - GeeksforGeeks

17 Aug, 2021
Let A be m×n real valued square symmetric matrix of rank 2 with expression given below.Consider the following statements

(i)  One eigenvalue must be in [-5, 5].
(ii) The eigenvalue with the largest magnitude 
     must be strictly greater than 5.

Which of the above statements about engenvalues of A is/are necessarily CORRECT?(A) Both (i) and (ii)(B) (i) only(C) (ii) only(D) Neither (i) nor (ii)Answer: (B)Explanation: As a rank of A matrix = 2, hence
=> n-2 eigen values are zero. Let be the eigen values.Given that ————(1)
We know that Trace of (AA)T = Trace of A2 (since A is symmetric) =  ————(2)
From (1) and (2) :
Hence, atleast one of the given eigen values lies in [-5,5](only 1 is correct).
This solution is contributed by Sumouli Chaudhary.Quiz of this Question
as5853535
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 53
Lodash | _.find() Method

21 May, 2022
The _.find() method accessing each value of the collection and returns the first element that passes a truth test for the predicate or undefined if no value passes the test. The function returns as soon as it finds the match. So it actually searches for elements according to the predicate.Syntax:  
_.find(collection, predicate, fromIndex)
Parameters: This method accept three parameters as mentioned above and described below:  
collection: This parameter holds the array or object collection that need to inspect.
predicate: This parameter holds the function invoked each iteration.
fromIndex: This parameter holds the index from which you want to start searching (optional). If you don’t pass this parameter then it start searching from the beginning.
Return Value: It returns the matched element or undefined if nothing match.Example 1: Tn this example, we will try to find the first number whose square is more than 100.  
javascript
const _ = require('lodash'); let x = [2, 5, 7, 10, 13, 15]; let result = _.find(x, function(n) {    if (n * n > 100) {        return true;    }}); console.log(result);
Here, const _ = require(‘lodash’) is used to import the lodash library into the file.Output:  
13
Example 2: In this example, we will find the first number in the list which is greater than 10 but start searching from index 2.  
javascript
const _ = require('lodash'); let x = [-1, 29, 7, 10, 13, 15]; let result = _.find(x, function(n) {    if (n > 10) {        return true;    }}, 2); console.log(result);
Output:  
13
Example 3: In this example, we will search for the first student (object) in the list who has more score than 90.  
javascript
const _ = require('lodash'); let x = [    {'name': 'Akhil', marks:'78'},    {'name': 'Akhil', marks:'98'},    {'name': 'Akhil', marks:'97'}]; let result = _.find(x, function(obj) {    if (obj.marks > 90) {        return true;    }}); console.log(result);
Output:  
{ name: 'Akhil', marks: '98' }
Example 4: When none element return true on predicate.  
javascript
const _ = require('lodash'); let x = [1, 2, 7, 10, 13, 15]; let result = _.find(x, function(n) {    if (n < 0) {        return true;    }}); console.log(result);
Output:  
undefined
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.Reference: https://lodash.com/docs/4.17.15#find 
anikakapoor
michaelxfrench
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.