title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python – Add custom values key in List of dictionaries
01 Aug, 2020 Given a list of dictionaries, custom list and Key, add the key to each dictionary with list values in order. Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 2, “is” : 16, “best” : 10}], K = “Geeks”, append_list = [6, 7, 4]Output : [{“Gfg” : 6, “is” : 9, “best” : 10, “Geeks” : 6}, {“Gfg” : 8, “is” : 11, “best” : 19, “Geeks” : 7}, {“Gfg” : 2, “is” : 16, “best” : 10, “Geeks” : 4}]Explanation : “Geeks” key added in each dictionary. Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}], K = “CS”, append_list = [6]Output : [{“Gfg” : 6, “is” : 9, “best” : 10, “CS” : 6}]Explanation : “CS” key added in each dictionary with 6 as value. Method #1 : Using loop + enumerate() This is one of the ways in which this task can be performed. In this, we iterate through the dictionary using enumerate() to get indices, and keep assigning to each dictionary key with its index value. Python3 # Python3 code to demonstrate working of # Add custom values key in List of dictionaries# Using loop # initializing liststest_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 2, "is" : 16, "best" : 10}, {"Gfg" : 12, "is" : 1, "best" : 8}, {"Gfg" : 22, "is" : 6, "best" : 8}] # printing original listprint("The original list : " + str(test_list)) # initializing Key K = "CS" # initializing list append_list = [6, 7, 4, 3, 9] # using enumerate() to iterate for index and valuesfor idx, ele in enumerate(test_list): ele[K] = append_list[idx] # printing result print("The dictionary list after addition : " + str(test_list)) The original list : [{'Gfg': 6, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 2, 'is': 16, 'best': 10}, {'Gfg': 12, 'is': 1, 'best': 8}, {'Gfg': 22, 'is': 6, 'best': 8}] The dictionary list after addition : [{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3}, {'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}] Method #2 : Using zip() + loop This is yet another way in which this task can be performed. In this, we perform mapping of list values with each dictionary using zip(). Python3 # Python3 code to demonstrate working of # Add custom values key in List of dictionaries# Using zip() + loop # initializing liststest_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 2, "is" : 16, "best" : 10}, {"Gfg" : 12, "is" : 1, "best" : 8}, {"Gfg" : 22, "is" : 6, "best" : 8}] # printing original listprint("The original list : " + str(test_list)) # initializing Key K = "CS" # initializing list append_list = [6, 7, 4, 3, 9] # zip() used to bind index wise # list and dictionaryfor dic, lis in zip(test_list, append_list): dic[K] = lis # printing result print("The dictionary list after addition : " + str(test_list)) The original list : [{'Gfg': 6, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 2, 'is': 16, 'best': 10}, {'Gfg': 12, 'is': 1, 'best': 8}, {'Gfg': 22, 'is': 6, 'best': 8}] The dictionary list after addition : [{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3}, {'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}] Python dictionary-programs Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 137, "s": 28, "text": "Given a list of dictionaries, custom list and Key, add the key to each dictionary with list values in order." }, { "code": null, "e": 515, "s": 137, "text"...
How to use Filtering in DataGrid Component in ReactJS ?
23 Apr, 2021 Filtering in DataGrid Component helps to view particular or related records in the data grid. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use Filtering in DataGrid Component. Approach: With the help of filterModel prop, we can do the filtering in DataGrid Component. In the below example, we have passed columnField as name and operatorValue as contains and value as Geek, therefore it will show all rows which have name field that contains Geek value in it. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/data-grid Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react';import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 170 }, { field: 'name', headerName: 'NAME', width: 170 }, { field: 'age', headerName: 'AGE', width: 170 },]; const rows = [ { id: 1, name: 'Gourav', age: 12 }, { id: 2, name: 'Geek', age: 43 }, { id: 3, name: 'Pranav', age: 41 },]; export default function App() { return ( <div style={{ height: 500, width: '80%' }}> <h4> How to use Filtering in DataGrid Component in ReactJS? </h4> <DataGrid rows={rows} columns={columns} pageSize={2} filterModel={{ items: [ { columnField: 'name', operatorValue: 'contains', value: 'Geek' }, ], }} /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://material-ui.com/components/data-grid/filtering/ Material-UI React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 305, "s": 28, "text": "Filtering in DataGrid Component helps to view particular or related records in the data grid. DataGrid Component helps in displaying the information in a grid-like format of r...
Context Manager Using @contextmanager Decorator
11 Aug, 2021 Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. Syntax: @decorator def function(args): statements(s) Example: Python3 # Python program to demonstrate# decorators def msg_decorator(func): # Inner function def msg_wrapper(msg): print("A decorated line:", func(msg)) return msg_wrapper # Using the decorator@msg_decoratordef print_name(name): return name print_name("Pooventhiran") A decorated line: Pooventhiran In this example, whenever print_name() is called, first, msg_decorator is called with print_name as the argument. Inside msg_decorator, msg_wrapper is returned which simply calls whichever function passed to msg_decorator with the arguments passed to it. Though this example is simple, these are so powerful in actual usecases like checking for boundary/special conditions, pre-processing, etc.Note: For more information refer to Decorators in Python. Context Managers are Python’s resource managers. In most cases, we use files as resources (a simple resource). We often don’t care about closing the files at the end of execution. This is a bad coding practice and also this causes issues when too many files are opened, or when the program is terminated with failure as the resource is not properly released. Context managers are the rescue for this issue by automatically managing resources. In Python, the with keyword is used. Example: Python3 # Python program to demonstrate# Context Manager with open('testfile.txt') as in_file: print(''.join(in_file.readlines())) In the example shown above, the file used is managed by ContextManager itself as it closes the file even if the program fails. This context manager feature can also be built into our programs. The user need to ensure that the class has the methods: __enter__() and __exit__(). Let’s look at a template with these special methods. Python3 # Python program creating a# context manager class ContextManager(): def __init__(self): print('init method called') def __enter__(self): print('enter method called') return self def __exit__(self, exc_type, exc_value, exc_traceback): print('exit method called') # Driver codewith ContextManager() as manager: print('with statement block') Output: init method called enter method called with statement block exit method called In the above code, __enter__ will be executed when control enters with and __exit__, when control leaves with clause. We can simply make any function as a context manager with the help of contextlib.contextmanager decorator without having to write a separate class or __enter__ and __exit__ functions. We have to use contextlib.contextmanager to decorate a generator function which yields exactly once. Everything before yield is considered to be __enter__ section and everything after, to be __exit__ section. The generator function should yield the resource. Example: Let’s rewrite the above example with this decorator Python3 # Python program for creating a# context manager using @contextmanager# decorator from contextlib import contextmanager @contextmanagerdef ContextManager(): # Before yield as the enter method print("Enter method called") yield # After yield as the exit method print("Exit method called") with ContextManager() as manager: print('with statement block') Output: Enter method called with statement block Exit method called clintra Python Decorators Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Aug, 2021" }, { "code": null, "e": 289, "s": 28, "text": "Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in...
Perl - Variables
Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or strings in these variables. We have learnt that Perl has the following three basic data types − Scalars Arrays Hashes Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will precede by sign @ and it will store ordered lists of scalars. Finaly, the Hash variable will precede by sign % and will be used to store sets of key/value pairs. Perl maintains every variable type in a separate namespace. So you can, without fear of conflict, use the same name for a scalar variable, an array, or a hash. This means that $foo and @foo are two different variables. Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Keep a note that this is mandatory to declare a variable before we use it if we use use strict statement in our program. The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example − $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salary variables, respectively. Shortly we will see how we can assign values to arrays and hashes. A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single thing. Here is a simple example of using scalar variables − #!/usr/bin/perl $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point print "Age = $age\n"; print "Name = $name\n"; print "Salary = $salary\n"; This will produce the following result − Age = 25 Name = John Paul Salary = 1445.5 An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets. Here is a simple example of using array variables − #!/usr/bin/perl @ages = (25, 30, 40); @names = ("John Paul", "Lisa", "Kumar"); print "\$ages[0] = $ages[0]\n"; print "\$ages[1] = $ages[1]\n"; print "\$ages[2] = $ages[2]\n"; print "\$names[0] = $names[0]\n"; print "\$names[1] = $names[1]\n"; print "\$names[2] = $names[2]\n"; Here we used escape sign (\) before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − $ages[0] = 25 $ages[1] = 30 $ages[2] = 40 $names[0] = John Paul $names[1] = Lisa $names[2] = Kumar A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name followed by the "key" associated with the value in curly brackets. Here is a simple example of using hash variables − #!/usr/bin/perl %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); print "\$data{'John Paul'} = $data{'John Paul'}\n"; print "\$data{'Lisa'} = $data{'Lisa'}\n"; print "\$data{'Kumar'} = $data{'Kumar'}\n"; This will produce the following result − $data{'John Paul'} = 45 $data{'Lisa'} = 30 $data{'Kumar'} = 40 Perl treats same variable differently based on Context, i.e., situation where a variable is being used. Let's check the following example − #!/usr/bin/perl @names = ('John Paul', 'Lisa', 'Kumar'); @copy = @names; $size = @names; print "Given names are : @copy\n"; print "Number of names are : $size\n"; This will produce the following result − Given names are : John Paul Lisa Kumar Number of names are : 3 Here @names is an array, which has been used in two different contexts. First we copied it into anyother array, i.e., list, so it returned all the elements assuming that context is list context. Next we used the same array and tried to store this array in a scalar, so in this case it returned just the number of elements in this array assuming that context is scalar context. Following table lists down the various contexts − Scalar Assignment to a scalar variable evaluates the right-hand side in a scalar context. List Assignment to an array or a hash evaluates the right-hand side in a list context. Boolean Boolean context is simply any place where an expression is being evaluated to see whether it's true or false. Void This context not only doesn't care what the return value is, it doesn't even want a return value. Interpolative This context only happens inside quotes, or things that work like quotes.
[ { "code": null, "e": 2492, "s": 2354, "text": "Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory." }, { "code": null, "e": 2742, "s": 2492, "text": "Based on the data type of a variable, the in...
Python – Binding and Listening with Sockets
01 Jun, 2022 Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. Note: For more information, refer Socket Programming in Python A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. Example Python3 import socketimport sys # specify Host and PortHOST = ''PORT = 5789 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # With the help of bind() function # binding host and port soc.bind((HOST, PORT)) except socket.error as message: # if any error occurs then with the # help of sys.exit() exit from the program print('Bind failed. Error Code : ' + str(message[0]) + ' Message ' + message[1]) sys.exit() # print if Socket binding operation completed print('Socket binding operation completed') # With the help of listening () function# starts listeningsoc.listen(9) conn, address = soc.accept()# print the address of connectionprint('Connected with ' + address[0] + ':' + str(address[1])) First of all we import socket which is necessary. Then we made a socket object and reserved a port on our pc. After that we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer. After that we put the server into listen mode. 9 here means that 9 connections are kept waiting if the server is busy and if a 10th socket tries to connect then the connection is refused. Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal: # start the server $ python server.py Keep the above terminal open now open another terminal and type: $ telnet localhost 12345 Output: anikakapoor sweetyty Python-socket Python 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 Python | os.path.join() method 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 Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2022" }, { "code": null, "e": 391, "s": 28, "text": "Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket rea...
Using Matplotlib with Jupyter Notebook
04 Jul, 2022 The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Note: For more information, refer to How To Use Jupyter Notebook – An Ultimate Guide Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.To get started you just need to make the necessary imports, prepare some data, and you can start plotting with the help of the plot() function.When you’re done, remember to show your plot using the show() function. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python.It consists of several plots like: Line Bar Scatter Histogram And many more Install Matplotlib with pip Matplotlib can also be installed using the Python package manager, pip. To install Matplotlib with pip, open a terminal window and type: pip install matplotlib Install Matplotlib with the Anaconda Prompt Matplotlib can be installed using with the Anaconda Prompt. If the Anaconda Prompt is available on your machine, it can usually be seen in the Windows Start Menu. To install Matplotlib, open the Anaconda Prompt and type: conda install matplotlib After the installation is completed. Let’s start using Matplotlib with Jupyter Notebook. We will be plotting various graphs in the Jupyter Notebook using Matplotlib. Python3 # importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.plot(x, y) # function to show the plotplt.show() Output: Bar Plot Python3 # importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.bar(x, y) # function to show the plotplt.show() Output: Histogram Python3 # importing matplotlib modulefrom matplotlib import pyplot as plt # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot histogramplt.hist(y) # Function to show the plotplt.show() Output : Python3 # importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot scatterplt.scatter(x, y) # function to show the plotplt.show() Output : We can add title to the graph by using the following command matplotlib.pyplot.title("My title") We can label the x-axis and y-axis by using the following functions matplotlib.pyplot.xlabel("Time (Hr)") matplotlib.pyplot.ylabel("Position (Km)") Example : Python3 # importing matplotlib modulefrom matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.scatter(x, y) # Adding Titleplt.title("GeeksFoeGeeks") # Labeling the axesplt.xlabel("Time (hr)")plt.ylabel("Position (Km)") # function to show the plotplt.show() Output: We can also write a program in the same cell for printing Multiple Graphs together. We can print these graphs vertically one below another by repeating the show() function in the program or we can use a function called subplot() in order to print them horizontally as well. Python3 from matplotlib import pyplot as plt x = [1, 2, 3, 4, 5]y = [1, 4, 9, 16, 25]plt.scatter(x, y) # function to show the plotplt.show() plt.plot(x, y) # function to show the plotplt.show() Output vinayedula Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 934, "s": 28, "text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses...
Difference between JavaScript and JSP
16 Jun, 2022 JavaScript is a lightweight and object-oriented scripting language used to create dynamic HTML pages with interactive effects within a webpage. It is an interpreted scripting language and its code is run in a web browser. It is also called a browser’s language and can be used for client-side developments as well as server-side developments. It was developed by Brendan Eich at Netscape and was first released in 1995. Features of JavaScript: Some important features of JavaScript are : It is a lightweight scripting language. It is platform-independent, it can run anytime on any platform or any browser. It can handle date and time easily as it has in-built functions for date and time. It allows dynamic typing, define types of the variable on the basis of stored value. It provides support for Object-Oriented programming. It reduces the load on the server by providing greater control to the browser itself. Example: javascript <script type="text/javascript"> document.write("Hello Geeks, Greetings from GeeksforGeeks")</script> JSP stands for Java Server Pages, are a dynamic web technology based on servlet container and Java EE specification which is used to generate dynamic web content in webpages. It was launched in the year 1999. It serves as a server-side technology based on various content formats such as XML or HTML or any other type of document contents. Features of JSP: Some important features of JSP are : It is an expression language for the server-side. It is easy to code as it allows tag-based programming. It is platform-independent, it can run anytime on any platform or any browser. It allows the building of dynamic web pages which helps to interact with the users in a real-time environment. It primarily connects with the server which provides an easy connection to the database. Example: html <html> <head><title>Hello!</title></head> <body> Hello Geeks!<br/> <% out.println("Welcome to Geeksforgeeks"); %> </body></html> Difference between JavaScript and JSP: siddharthredhu01 priyansh70890 Java-JSP JavaScript-Misc Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2022" }, { "code": null, "e": 543, "s": 53, "text": "JavaScript is a lightweight and object-oriented scripting language used to create dynamic HTML pages with interactive effects within a webpage. It is an interpreted scripting...
Closest greater or same value on left side for every element in array
21 Feb, 2022 Given an array of integers, find the closest (not considering the distance, but value) greater or the same value on the left of every element. If an element has no greater or same value on the left side, print -1. Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : -1, 10, -1, 10, -1, 20 The first element has nothing on the left side, so the answer for first is -1. Second, element 5 has 10 on the left, so the answer is 10. Third element 11 has nothing greater or the same, so the answer is -1. Fourth element 6 has 10 as value wise closes, so the answer is 10 Similarly, we get values for the fifth and sixth elements. A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse toward the left of it and find the closest (value-wise) greater element. The time complexity of this solution is O(n*n) C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // function for ceiling in left side for every element in an// arrayvoid printPrevGreater(int arr[], int n){ cout << "-1" << " "; // for first element for (int i = 1; i < n; i++) { int diff = INT_MAX; for (int j = 0; j < i; j++) // traverse left side to i-th element { if (arr[j] >= arr[i]) diff = min(diff, arr[j] - arr[i]); } if (diff == INT_MAX) cout << "-1" << " "; // if not found at left side else cout << arr[i] + diff << " "; }} // Driver codeint main(){ int arr[] = { 10, 5, 11, 10, 20, 12 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevGreater(arr, n); return 0;} // This code is contributed by// @itsrahulhere_ import java.util.*;class GFG { // function for ceiling in left side for every element in an // array static void printPrevGreater(int arr[], int n) { System.out.print("-1" + " "); // for first element for (int i = 1; i < n; i++) { int diff = Integer.MAX_VALUE; for (int j = 0; j < i; j++) // traverse left side to i-th element { if (arr[j] >= arr[i]) diff = Math.min(diff, arr[j] - arr[i]); } if (diff == Integer.MAX_VALUE) System.out.print("-1" + " "); // if not found at left side else System.out.print(arr[i] + diff + " "); } } // Driver code public static void main(String[] args) { int arr[] = { 10, 5, 11, 10, 20, 12 }; int n = arr.length; printPrevGreater(arr, n); }} // This code is contributed by Rajput-Ji import sys # function for ceiling in left side for every element in an# arraydef printPrevGreater(arr,n): print("-1",end = ' ') # for first element for i in range(1,n): diff = sys.maxsize for j in range(i): # traverse left side to i-th element if (arr[j] >= arr[i]): diff = min(diff, arr[j] - arr[i]) if diff == sys.maxsize : print("-1",end = " ") # if not found at left side else : print(arr[i] + diff ,end = ' ') # Driver codearr = [ 10, 5, 11, 10, 20, 12 ]n = len(arr)printPrevGreater(arr, n) # This code is contributed by shinjanpatra using System; public class GFG { // function for ceiling in left side for every element in an // array static void printPrevGreater(int []arr, int n) { Console.Write("-1" + " "); // for first element for (int i = 1; i < n; i++) { int diff = int.MaxValue; for (int j = 0; j < i; j++) // traverse left side to i-th element { if (arr[j] >= arr[i]) diff = Math.Min(diff, arr[j] - arr[i]); } if (diff == int.MaxValue) Console.Write("-1" + " "); // if not found at left side else Console.Write(arr[i] + diff + " "); } } // Driver code public static void Main(String[] args) { int []arr = { 10, 5, 11, 10, 20, 12 }; int n = arr.Length; printPrevGreater(arr, n); }} // This code is contributed by Rajput-Ji <script> // function for ceiling in left side for every element in an // array function printPrevGreater(arr , n) { document.write("-1" + " "); // for first element for (i = 1; i < n; i++) { var diff = Number.MAX_VALUE; for (j = 0; j < i; j++) // traverse left side to i-th element { if (arr[j] >= arr[i]) diff = Math.min(diff, arr[j] - arr[i]); } if (diff == Number.MAX_VALUE) document.write("-1" + " "); // if not found at left side else document.write(arr[i] + diff + " "); } } // Driver code var arr = [ 10, 5, 11, 10, 20, 12 ]; var n = arr.length; printPrevGreater(arr, n); // This code is contributed by Rajput-Ji</script> Output: -1 10 -1 10 -1 20 Time Complexity: O(n * n)Auxiliary Space: O(1) An efficient solution is to use Self-Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time.We use lower_bound() in C++ to find the closest greater element. This function works in Log n time for a set. C++ Java Python3 C# Javascript // C++ implementation of efficient algorithm to find// greater or same element on left side#include <iostream>#include <set>using namespace std; // Prints greater elements on left side of every elementvoid printPrevGreater(int arr[], int n){ set<int> s; for (int i = 0; i < n; i++) { // First search in set auto it = s.lower_bound(arr[i]); if (it == s.end()) // If no greater found cout << "-1" << " "; else cout << *it << " "; // Then insert s.insert(arr[i]); }} /* Driver program to test insertion sort */int main(){ int arr[] = { 10, 5, 11, 10, 20, 12 }; int n = sizeof(arr) / sizeof(arr[0]); printPrevGreater(arr, n); return 0;} // Java implementation of efficient algorithm// to find greater or same element on left sideimport java.util.TreeSet; class GFG { // Prints greater elements on left side // of every element static void printPrevGreater(int[] arr, int n) { TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) { Integer c = ts.ceiling(arr[i]); if (c == null) // If no greater found System.out.print(-1 + " "); else System.out.print(c + " "); // Then insert ts.add(arr[i]); } } // Driver Code public static void main(String[] args) { int[] arr = { 10, 5, 11, 10, 20, 12 }; int n = arr.length; printPrevGreater(arr, n); }} // This code is contributed by// sanjeev2552 # Python3 implementation of efficient algorithm# to find greater or same element on left side # Prints greater elements# on left side of every elementdef printPrevGreater(arr, n): s = set() for i in range(0, n): # First search in set it = [x for x in s if x >= arr[i]] if len(it) == 0: # If no greater found print("-1", end = " ") else: print(min(it), end = " ") # Then insert s.add(arr[i]) # Driver Codeif __name__ == "__main__": arr = [10, 5, 11, 10, 20, 12] n = len(arr) printPrevGreater(arr, n) # This code is contributed by Rituraj Jain // C# implementation of efficient algorithm// to find greater or same element on left sideusing System;using System.Collections.Generic; class GFG { // To get the minimum value static int minimum(SortedSet<int> ss) { int min = int.MaxValue; foreach(int i in ss) if (i < min) min = i; return min; } // Prints greater elements on left side // of every element static void printPrevGreater(int[] arr, int n) { SortedSet<int> s = new SortedSet<int>(); for (int i = 0; i < n; i++) { SortedSet<int> ss = new SortedSet<int>(); // First search in set foreach(int x in s) if (x >= arr[i]) ss.Add(x); if (ss.Count == 0) // If no greater found Console.Write(-1 + " "); else Console.Write(minimum(ss) + " "); // Then insert s.Add(arr[i]); } } // Driver Code public static void Main(String[] args) { int[] arr = { 10, 5, 11, 10, 20, 12 }; int n = arr.Length; printPrevGreater(arr, n); }} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of efficient algorithm to find// greater or same element on left side // To get the minimum valuefunction minimum(ss){ var min = 1000000000; ss.forEach(i => { if (i < min) min = i; }); return min;}// Prints greater elements on left side of every elementfunction printPrevGreater(arr, n){ var s = new Set(); for (var i = 0; i < n; i++) { var ss = new Set(); // First search in set s.forEach(x => { if(x >= arr[i]) ss.add(x); }); if (ss.size == 0) // If no greater found document.write(-1 + " "); else document.write(minimum(ss) + " "); // Then insert s.add(arr[i]); }} /* Driver program to test insertion sort */var arr = [10, 5, 11, 10, 20, 12];var n = arr.length;printPrevGreater(arr, n); </script> -1 10 -1 10 -1 20 Time Complexity: O(n Log n) Auxiliary Space: O(n) rituraj_jain sanjeev2552 princiraj1992 importantly manpreetsingh78923 itsrahulhere_ Rajput-Ji shinjanpatra cpp-set Self-Balancing-BST Arrays Binary Search Tree Arrays Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Feb, 2022" }, { "code": null, "e": 266, "s": 52, "text": "Given an array of integers, find the closest (not considering the distance, but value) greater or the same value on the left of every element. If an element has no greater or...
Data Science | Solving Linear Equations
01 Jun, 2022 You can go through Introduction to Data Science : Skills Required article to have some basic understanding of what Data Science is.Linear Algebra is a very fundamental part of Data Science. When one talks about Data Science, data representation becomes an important aspect of Data Science. Data is represented usually in a matrix form. The second important thing in the perspective of Data Science is if this data contains several variables of interest, then one is interested to know how many of these are very important. And if there are relationships between these variables, then how can one uncover these relationships. Linear algebraic tools allow us to understand these data. So, a Data Science enthusiast needs to have a good understanding of this concept before going to understand complex machine learning algorithms.Matrices and Linear Algebra There are many ways to represent the data, matrices provide you with a convenient way to organize these data. Matrices can be used to represent samples with multiple attributes in a compact form Matrices can also be used to represent linear equations in a compact and simple fashion Linear algebra provides tools to understand and manipulate matrices to derive useful knowledge from data Identification of Linear Relationships Among Attributes We identify the linear relationship between attributes using the concept of null space and nullity. Before proceeding further, go through Null Space and Nullity of a Matrix.Preliminaries Generalized linear equations are represented as below: [Tex]A (m * n); x (n * 1); b (m * 1)[/Tex]m and n are the number of equations and variables respectivelyb is the general RHS commonly used In general there are three cases one need to understand: We will consider these three cases independently.Full row rank and full column rank For a matrix A (m x n) Note: In general whatever be the size of the matrix it is established that row rank is always equal to the column rank. It means for any size of the matrix if we have certain number of independent rows, we will have those many numbers of independent column. In general case if we have a matrix m x n and m is smaller than n then the maximum rank of the matrix can only be m. So, maximum rank is always the less of the two numbers m and n. Case 1: m = n Example 1.1: Consider the given matrix equation: (1) |A| is not equal to zerorank(A) = 2 = no. of columnsThis implies that A is full rankTherefore, the solution for the given example is (1) Program to find rank and inverse of a matrix and solve the matrix equation in Python: Python3 # First, import# matrix_rank from numpy.linalgfrom numpy.linalg import matrix_rank, inv, solve # A 2 x 2 matrixA = [[1, 3], [2, 4]]b = [7, 10] # Rank of matrix Aprint("Rank of the matrix is:", matrix_rank(A)) # Inverse of matrix Aprint("\nInverse of A:\n", inv(A)) # Matrix equation solutionprint("Solution of linear equations:", solve(A, b)) Output: Rank of the matrix is: 2 Inverse of A: [[-2. 1.5] [ 1. -0.5]] Solution of linear equation: [ 1. 2.] You can refer Numpy | Linear Algebra article for various operations on matrix and to solve linear equations in Python. Example 1.2: Consider the given matrix equation: (2) |A| is not equal to zerorank(A) = 1nullity = 1Checking consistencyRow (2) = 2 Row (1)The equations are consistent with only one linearly independent equationThe solution set for (, ) is infinite because we have onlyone linearly independent equation and two variables (2) Explanation: In the above example we have only one linearly independent equation i.e. . So, if we take , then we have ; if we take , then we have . In the similar fashion we can have many solutions to this equation. We can take any value of ( we have infinite choices for ) and correspondingly for each value of we will get one . Hence, we can say that this equation has infinite solutions.Example 1.3: Consider the given matrix equation: (3) |A| is not equal to zerorank(A) = 1nullity = 1Checking consistency2 Row (1) = Therefore, the equations are inconsistentWe cannot find the solution to () (3) Case 2: m > n In this case, the number of variables or the attributes is less than the number of equations. Here, not all the equations can be satisfied. So, it is sometimes termed as the case of no solution. But, we can try to identify an appropriate solution by viewing this case from optimization perspective. An optimization perspective - Rather than finding a solution to , we can find an such that () is minimized- Here, is a vector- There will be as many error terms as the number of equations- Denote = e (m x 1); there are m errors , i = 1:m- We can minimize all the errors collectively by minimizing - This is the same as minimizing So, the optimization problem becomes = = Here, we can notice that the optimization problem is a function of x. When we solve this optimization problem, it will give us the solution for x. We can obtain the solution to this optimization problem by differentiating with respect to x and setting the differential to zero. – Now, differentiating f(x) and setting the differential to zero results in – Assuming that all the columns are linearly independent Note: While this solution x might not satisfy all the equation but it will ensure that the errors in the equations are collectively minimized.Example 2.1: Consider the given matrix equation: (4) m = 3, n = 2Using the optimization concept[Tex]\begin{bmatrix} x_1\\ x_2\\ \end{bmatrix} = &&(\begin{bmatrix} 1&2&3\\ 0&0&1\\ \end{bmatrix} % \begin{bmatrix} 1&0\\ 2&0\\ 3&1\\ \end{bmatrix})&&^{-1} \begin{bmatrix} 1&2&3\\ 0&0&1\\ \end{bmatrix} % \begin{bmatrix} 1\\ -0.5\\ 5\\ \end{bmatrix}[/Tex][Tex]\begin{bmatrix} x_1\\ x_2\\ \end{bmatrix} = \begin{bmatrix} 0\\ 5\\ \end{bmatrix}[/Tex]Therefore, the solution for the given linear equation is Substituting in the equation shows (4) Example 2.2: Consider the given matrix equation: (5) m = 3, n = 2Using the optimization concept[Tex]\begin{bmatrix} x_1\\ x_2\\ \end{bmatrix} = &&(\begin{bmatrix} 1&2&3\\ 0&0&1\\ \end{bmatrix} % \begin{bmatrix} 1&0\\ 2&0\\ 3&1\\ \end{bmatrix})&&^{-1} \begin{bmatrix} 1&2&3\\ 0&0&1\\ \end{bmatrix} % \begin{bmatrix} 1\\ 2\\ 5\\ \end{bmatrix}[/Tex][Tex]\begin{bmatrix} x_1\\ x_2\\ \end{bmatrix} = \begin{bmatrix} 1\\ 2\\ \end{bmatrix}[/Tex]Therefore, the solution for the given linear equation is Substituting in the equation shows (5) So, the important point to notice in the case 2 is that if we have more equations than variables then we can always use the least square solution which is . There is one thing to keep in mind is that exists if the columns of A are linearly independent.Case 3: m < n This case deals with more number of attributes or variables than equations Here, we can obtain multiple solutions for the attributes This is an infinite solution case We will see how we can choose one solution from the set of infinite possible solution In this case also we have an optimization perspective.Know what is Lagrange function here. – Given below is the optimization problemmin() such that, – We can define a Lagrangian function – Differentiate the Lagrangian with respect to x, and set it to zero, then we will get, Pre – multiplying by A From above we can obtain assuming that all the rows are linearly independent Example 3.1: Consider the given matrix equation: (6) m = 2, n = 3Using the optimization concept,[Tex]x = \begin{bmatrix} 1&0\\ 2&0\\ 3&1\\ \end{bmatrix} % (\begin{bmatrix} 1&2&3\\ 0&0&1\\ \end{bmatrix} % \begin{bmatrix} 1&0\\ 2&0\\ 3&1\\ \end{bmatrix})^{-1} % \begin{bmatrix} 2\\ 1\\ \end{bmatrix}[/Tex][Tex]x = \begin{bmatrix} 1&0\\ 2&0\\ 3&1\\ \end{bmatrix} % \begin{bmatrix} -0.2\\ 1.6\\ \end{bmatrix}[/Tex]The solution for given sample is () = (-0.2, -0.4, 1)You can easily verify that (6) Generalization The above-described cases cover all the possible scenarios that one may encounter while solving linear equations. The concept we use to generalize the solutions for all the above cases is called Moore – Penrose Pseudoinverse of a matrix. Singular Value Decomposition can be used to calculate the psuedoinverse or the generalized inverse (). sumitgumber28 kumargaurav97520 data-science Machine Learning Mathematical Python Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Jun, 2022" }, { "code": null, "e": 1020, "s": 53, "text": "You can go through Introduction to Data Science : Skills Required article to have some basic understanding of what Data Science is.Linear Algebra is a very fundamental part ...
Flood Fill Algorithm
01 Nov, 2021 Given a 2D screen arr[][] where each arr[i][j] is an integer representing the color of that pixel, also given the location of a pixel (X, Y) and a color C, the task is to replace the color of the given pixel and all the adjacent same-colored pixels with the given color.Example: Input: arr[][] = { {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}} X = 4, Y = 4, C = 3 Output: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 3 3 3 3 0 1 0 1 1 1 3 3 0 1 0 1 1 1 3 3 3 3 0 1 1 1 1 1 3 1 1 1 1 1 1 1 3 3 1 Explanation: The values in the given 2D screen indicate colors of the pixels. X and Y are coordinates of the brush, C is the color that should replace the previous color on screen[X][Y] and all surrounding pixels with the same color. Hence all the 2 are replaced with 3. BFS Approach: The idea is to use BFS traversal to replace the color with the new color. Create an empty queue lets say Q. Push the starting location of the pixel as given in the input and apply replacement color to it. Iterate until Q is not empty and pop the front node (pixel position). Check the pixels adjacent to the current pixel and push into the queue if valid (had not been colored with replacement color and have the same color as the old color). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if// the given pixel is validbool isValid(int screen[][8], int m, int n, int x, int y, int prevC, int newC){ if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC || screen[x][y]== newC) return false; return true;} // FloodFill functionvoid floodFill(int screen[][8], int m, int n, int x, int y, int prevC, int newC){ vector<pair<int,int>> queue; // Append the position of starting // pixel of the component pair<int,int> p(x,y); queue.push_back(p); // Color the pixel with the new color screen[x][y] = newC; // While the queue is not empty i.e. the // whole component having prevC color // is not colored with newC color while(queue.size() > 0) { // Dequeue the front node pair<int,int> currPixel = queue[queue.size() - 1]; queue.pop_back(); int posX = currPixel.first; int posY = currPixel.second; // Check if the adjacent // pixels are valid if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) { // Color with newC // if valid and enqueue screen[posX + 1][posY] = newC; p.first = posX + 1; p.second = posY; queue.push_back(p); } if(isValid(screen, m, n, posX-1, posY, prevC, newC)) { screen[posX-1][posY]= newC; p.first = posX-1; p.second = posY; queue.push_back(p); } if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) { screen[posX][posY + 1]= newC; p.first = posX; p.second = posY + 1; queue.push_back(p); } if(isValid(screen, m, n, posX, posY-1, prevC, newC)) { screen[posX][posY-1]= newC; p.first = posX; p.second = posY-1; queue.push_back(p); } }} int main(){ int screen[][8] ={ {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}}; // Row of the display int m = 8; // Column of the display int n = 8; // Co-ordinate provided by the user int x = 4; int y = 4; // Current color at that co-ordinate int prevC = screen[x][y]; // New color that has to be filled int newC = 3; floodFill(screen, m, n, x, y, prevC, newC); // Printing the updated screen for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { cout << screen[i][j] << " "; } cout << endl; } return 0;} // This code is contributed by suresh07. // Java implementation of the approachimport java.util.*;import java.awt.Point;public class Main{ // Function that returns true if // the given pixel is valid static boolean isValid(int[][] screen, int m, int n, int x, int y, int prevC, int newC) { if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC || screen[x][y]== newC) return false; return true; } // FloodFill function static void floodFill(int[][] screen, int m, int n, int x, int y, int prevC, int newC) { Vector<Point> queue = new Vector<Point>(); // Append the position of starting // pixel of the component queue.add(new Point(x, y)); // Color the pixel with the new color screen[x][y] = newC; // While the queue is not empty i.e. the // whole component having prevC color // is not colored with newC color while(queue.size() > 0) { // Dequeue the front node Point currPixel = queue.get(queue.size() - 1); queue.remove(queue.size() - 1); int posX = currPixel.x; int posY = currPixel.y; // Check if the adjacent // pixels are valid if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) { // Color with newC // if valid and enqueue screen[posX + 1][posY] = newC; queue.add(new Point(posX + 1, posY)); } if(isValid(screen, m, n, posX-1, posY, prevC, newC)) { screen[posX-1][posY]= newC; queue.add(new Point(posX-1, posY)); } if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) { screen[posX][posY + 1]= newC; queue.add(new Point(posX, posY + 1)); } if(isValid(screen, m, n, posX, posY-1, prevC, newC)) { screen[posX][posY-1]= newC; queue.add(new Point(posX, posY-1)); } } } public static void main(String[] args) { int[][] screen ={ {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}}; // Row of the display int m = screen.length; // Column of the display int n = screen.length; // Co-ordinate provided by the user int x = 4; int y = 4; // Current color at that co-ordinate int prevC = screen[x][y]; // New color that has to be filled int newC = 3; floodFill(screen, m, n, x, y, prevC, newC); // Printing the updated screen for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { System.out.print(screen[i][j] + " "); } System.out.println(); } }} // This code is contributed by mukesh07. # Python3 implementation of the approach # Function that returns true if# the given pixel is validdef isValid(screen, m, n, x, y, prevC, newC): if x<0 or x>= m\ or y<0 or y>= n or\ screen[x][y]!= prevC\ or screen[x][y]== newC: return False return True # FloodFill functiondef floodFill(screen, m, n, x, y, prevC, newC): queue = [] # Append the position of starting # pixel of the component queue.append([x, y]) # Color the pixel with the new color screen[x][y] = newC # While the queue is not empty i.e. the # whole component having prevC color # is not colored with newC color while queue: # Dequeue the front node currPixel = queue.pop() posX = currPixel[0] posY = currPixel[1] # Check if the adjacent # pixels are valid if isValid(screen, m, n, posX + 1, posY, prevC, newC): # Color with newC # if valid and enqueue screen[posX + 1][posY] = newC queue.append([posX + 1, posY]) if isValid(screen, m, n, posX-1, posY, prevC, newC): screen[posX-1][posY]= newC queue.append([posX-1, posY]) if isValid(screen, m, n, posX, posY + 1, prevC, newC): screen[posX][posY + 1]= newC queue.append([posX, posY + 1]) if isValid(screen, m, n, posX, posY-1, prevC, newC): screen[posX][posY-1]= newC queue.append([posX, posY-1]) # Driver codescreen =[[1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 0, 0],[1, 0, 0, 1, 1, 0, 1, 1],[1, 2, 2, 2, 2, 0, 1, 0],[1, 1, 1, 2, 2, 0, 1, 0],[1, 1, 1, 2, 2, 2, 2, 0],[1, 1, 1, 1, 1, 2, 1, 1],[1, 1, 1, 1, 1, 2, 2, 1], ] # Row of the displaym = len(screen) # Column of the displayn = len(screen[0]) # Co-ordinate provided by the userx = 4y = 4 # Current color at that co-ordinateprevC = screen[x][y] # New color that has to be fillednewC = 3 floodFill(screen, m, n, x, y, prevC, newC) # Printing the updated screenfor i in range(m): for j in range(n): print(screen[i][j], end =' ') print() // C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function that returns true if // the given pixel is valid static bool isValid(int[,] screen, int m, int n, int x, int y, int prevC, int newC) { if(x < 0 || x >= m || y < 0 || y >= n || screen[x, y] != prevC || screen[x,y]== newC) return false; return true; } // FloodFill function static void floodFill(int[,] screen, int m, int n, int x, int y, int prevC, int newC) { List<Tuple<int,int>> queue = new List<Tuple<int,int>>(); // Append the position of starting // pixel of the component queue.Add(new Tuple<int,int>(x, y)); // Color the pixel with the new color screen[x,y] = newC; // While the queue is not empty i.e. the // whole component having prevC color // is not colored with newC color while(queue.Count > 0) { // Dequeue the front node Tuple<int,int> currPixel = queue[queue.Count - 1]; queue.RemoveAt(queue.Count - 1); int posX = currPixel.Item1; int posY = currPixel.Item2; // Check if the adjacent // pixels are valid if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) { // Color with newC // if valid and enqueue screen[posX + 1,posY] = newC; queue.Add(new Tuple<int,int>(posX + 1, posY)); } if(isValid(screen, m, n, posX-1, posY, prevC, newC)) { screen[posX-1,posY]= newC; queue.Add(new Tuple<int,int>(posX-1, posY)); } if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) { screen[posX,posY + 1]= newC; queue.Add(new Tuple<int,int>(posX, posY + 1)); } if(isValid(screen, m, n, posX, posY-1, prevC, newC)) { screen[posX,posY-1]= newC; queue.Add(new Tuple<int,int>(posX, posY-1)); } } } static void Main() { int[,] screen ={ {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}}; // Row of the display int m = screen.GetLength(0); // Column of the display int n = screen.GetLength(1); // Co-ordinate provided by the user int x = 4; int y = 4; // Current color at that co-ordinate int prevC = screen[x,y]; // New color that has to be filled int newC = 3; floodFill(screen, m, n, x, y, prevC, newC); // Printing the updated screen for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { Console.Write(screen[i,j] + " "); } Console.WriteLine(); } }} // This code is contributed by divyeshrabadiya07. <script> // Javascript implementation of the approach // Function that returns true if // the given pixel is valid function isValid(screen, m, n, x, y, prevC, newC) { if(x<0 || x>= m || y<0 || y>= n || screen[x][y]!= prevC || screen[x][y]== newC) return false; return true; } // FloodFill function function floodFill(screen, m, n, x, y, prevC, newC) { let queue = []; // Append the position of starting // pixel of the component queue.push([x, y]); // Color the pixel with the new color screen[x][y] = newC; // While the queue is not empty i.e. the // whole component having prevC color // is not colored with newC color while(queue.length > 0) { // Dequeue the front node currPixel = queue[queue.length - 1]; queue.pop(); let posX = currPixel[0]; let posY = currPixel[1]; // Check if the adjacent // pixels are valid if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) { // Color with newC // if valid and enqueue screen[posX + 1][posY] = newC; queue.push([posX + 1, posY]); } if(isValid(screen, m, n, posX-1, posY, prevC, newC)) { screen[posX-1][posY]= newC; queue.push([posX-1, posY]); } if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) { screen[posX][posY + 1]= newC; queue.push([posX, posY + 1]); } if(isValid(screen, m, n, posX, posY-1, prevC, newC)) { screen[posX][posY-1]= newC; queue.push([posX, posY-1]); } } } let screen =[ [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 1, 1], [1, 2, 2, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 2, 2, 0], [1, 1, 1, 1, 1, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1]]; // Row of the display let m = screen.length; // Column of the display let n = screen[0].length; // Co-ordinate provided by the user let x = 4; let y = 4; // Current color at that co-ordinate let prevC = screen[x][y]; // New color that has to be filled let newC = 3; floodFill(screen, m, n, x, y, prevC, newC); // Printing the updated screen for(let i = 0; i < m; i++) { for(let j = 0; j < n; j++) { document.write(screen[i][j] + " "); } document.write("</br>"); } // This code is contributed by divyesh072019.</script> 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 3 3 3 3 0 1 0 1 1 1 3 3 0 1 0 1 1 1 3 3 3 3 0 1 1 1 1 1 3 1 1 1 1 1 1 1 3 3 1 DFS Approach: Similarly DFS approach can be used to implement the Flood Fill algorithm as well. sweetyty divyesh072019 divyeshrabadiya07 mukesh07 suresh07 BFS Google Algorithms Graph Matrix Recursion Google Recursion Matrix Graph BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples Find if there is a path between two vertices in an undirected graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations Topological Sorting Find if there is a path between two vertices in a directed graph
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Nov, 2021" }, { "code": null, "e": 335, "s": 54, "text": "Given a 2D screen arr[][] where each arr[i][j] is an integer representing the color of that pixel, also given the location of a pixel (X, Y) and a color C, the task is to rep...
Material Design Date Picker in Android
23 Oct, 2020 Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Date Picker. There are a lot of date pickers available for Android which are Open Source. But the Material design date pickers offer more functionality to the user and easy to implement for developers. Have a look at the following images on what type of material design date pickers are going to be discussed in this discussion. Note that we are going to implement this project using the Java language. In this article, we are going to implement two types of material design date pickers as one can see in the below images. Material Design Normal Date Picker Material Design Date Range Picker Before going to implement the material design date picker, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding material design components dependency Now add the following dependency to the app-level gradle file. implementation ‘com.google.android.material:material:1.3.0-alpha02’ After invoking the dependency click on the “Sync Now” button. Make sure you are connected to the network so that Android Studio downloads all the required files. Refer to the following image if unable to locate the app-level gradle file and invoke the dependency. Step 3: Change the base application theme as Material Theme as following Go to app > src > main > res > values > styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file. As we are using material design components this step is mandatory. XML <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Customize your theme here --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> Refer to the following if unable to locate styles.xml and change the base theme of the application. Step 4: Working with the activity_main.xml file Invoke the following code for the application interface or can design it according to one’s needs. And this is going to remain the same for the entire discussion. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--make sure to give the appropriate IDs to textView and the button to handle them in MainActivity.java--> <!--simple text view to show the selected date by the user--> <TextView android:id="@+id/show_selected_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="128dp" android:text="Selected Date is : " android:textSize="18sp" /> <!--button to open the material design date picker dialog--> <Button android:id="@+id/pick_date_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="Select Date" android:textSize="18sp" app:icon="@drawable/ic_baseline_add_to_photos_24" /> </LinearLayout> The icon has been added to the Select Date button above in the code. However, that is optional. Refer Theming Material Design buttons in android with examples on how to add the icon to a button or how to change the theme of the button. Output UI: Step 5: Now invoke the following code to implement the first type of the material design date picker Go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.datepicker.MaterialDatePicker;import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; public class MainActivity extends AppCompatActivity { private Button mPickDateButton; private TextView mShowSelectedDateText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // now register the text view and the button with // their appropriate IDs mPickDateButton = findViewById(R.id.pick_date_button); mShowSelectedDateText = findViewById(R.id.show_selected_date); // now create instance of the material date picker // builder make sure to add the "datePicker" which // is normal material date picker which is the first // type of the date picker in material design date // picker MaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker(); // now define the properties of the // materialDateBuilder that is title text as SELECT A DATE materialDateBuilder.setTitleText("SELECT A DATE"); // now create the instance of the material date // picker final MaterialDatePicker materialDatePicker = materialDateBuilder.build(); // handle select date button which opens the // material design date picker mPickDateButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // getSupportFragmentManager() to // interact with the fragments // associated with the material design // date picker tag is to get any error // in logcat materialDatePicker.show(getSupportFragmentManager(), "MATERIAL_DATE_PICKER"); } }); // now handle the positive button click from the // material design date picker materialDatePicker.addOnPositiveButtonClickListener( new MaterialPickerOnPositiveButtonClickListener() { @SuppressLint("SetTextI18n") @Override public void onPositiveButtonClick(Object selection) { // if the user clicks on the positive // button that is ok button update the // selected date mShowSelectedDateText.setText("Selected Date is : " + materialDatePicker.getHeaderText()); // in the above statement, getHeaderText // is the selected date preview from the // dialog } }); }} Step 6: Now invoke the following code to implement the second type of the material design date picker In material design date picker there is one more type of the date picker is available, that is called as date range picker. The following code is the implementation of the date range picker. Go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import androidx.core.util.Pair;import com.google.android.material.datepicker.MaterialDatePicker;import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; public class MainActivity extends AppCompatActivity { private Button mPickDateButton; private TextView mShowSelectedDateText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // now register the text view and the button with // their appropriate IDs mPickDateButton = findViewById(R.id.pick_date_button); mShowSelectedDateText = findViewById(R.id.show_selected_date); // now create instance of the material date picker // builder make sure to add the "dateRangePicker" // which is material date range picker which is the // second type of the date picker in material design // date picker we need to pass the pair of Long // Long, because the start date and end date is // store as "Long" type value MaterialDatePicker.Builder<Pair<Long, Long>> materialDateBuilder = MaterialDatePicker.Builder.dateRangePicker(); // now define the properties of the // materialDateBuilder materialDateBuilder.setTitleText("SELECT A DATE"); // now create the instance of the material date // picker final MaterialDatePicker materialDatePicker = materialDateBuilder.build(); // handle select date button which opens the // material design date picker mPickDateButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // getSupportFragmentManager() to // interact with the fragments // associated with the material design // date picker tag is to get any error // in logcat materialDatePicker.show(getSupportFragmentManager(), "MATERIAL_DATE_PICKER"); } }); // now handle the positive button click from the // material design date picker materialDatePicker.addOnPositiveButtonClickListener( new MaterialPickerOnPositiveButtonClickListener() { @SuppressLint("SetTextI18n") @Override public void onPositiveButtonClick(Object selection) { // if the user clicks on the positive // button that is ok button update the // selected date mShowSelectedDateText.setText("Selected Date is : " + materialDatePicker.getHeaderText()); // in the above statement, getHeaderText // will return selected date preview from the // dialog } }); }} To implement more functionalities of Material Design Date Paicke please refer to More Functionalities of Material Design Date Picker in Android article. android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Oct, 2020" }, { "code": null, "e": 1130, "s": 28, "text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineer...
Wand oil_paint() function – Python
08 Jul, 2021 The oil_paint() function is an inbuilt function in the Python Wand ImageMagick library which is used to simulate an oil painting by replace each pixel with most frequent surrounding color. Syntax: oil_paint(radius, sigma) Parameters: This function accepts three parameters as mentioned above and defined below: radius: This parameter is used to store the radius of the simulation. sigma: This parameter is used to store the sigma of the simulation. Return Value: This function returns the Wand ImageMagick object. Original Image: Example 1: Python3 # Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as oil_paint: # Invoke oil_paint function with radius 6 and sigma 4 oil_paint.oil_paint(6, 4) # Save the image oil_paint.save(filename ='oil_paint1.jpg') Output: Example 2: Python3 # Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke oil_paint function with radius 9 and sigma 7 pic.oil_paint(9, 7) # Save the image pic.save(filename ='oil_paint2.jpg') Output: sweetyty Image-Processing Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2021" }, { "code": null, "e": 218, "s": 28, "text": "The oil_paint() function is an inbuilt function in the Python Wand ImageMagick library which is used to simulate an oil painting by replace each pixel with most frequent surro...
Python – Interconvert Horizontal and Vertical String
02 Sep, 2020 Given a String, convert to vertical if horizontal and vice-versa. Input : test_str = ‘geeksforgeeks’Output : geeksExplanation : Horizontal String converted to Vertical. Input : test_str = geeksOutput : ‘geeks’Explanation : Vertical String converted to Horizontal. Method #1 : [Horizontal to Vertical] using loop + “\n” In this, we add newline character to after each character so that each element gets rendered at next line. Python3 # Python3 code to demonstrate working of # Interconvert Horizontal and Vertical String# using [Horizontal to Vertical] using loop + "\n" # initializing stringtest_str = 'geeksforgeeks' # printing original Stringprint("The original string is : " + str(test_str)) # using loop to add "\n" after each character res = ''for ele in test_str: res += ele + "\n" # printing result print("The converted string : " + str(res)) The original string is : geeksforgeeks The converted string : g e e k s f o r g e e k s Method #2 : [Vertical to Horizontal] using replace() + “\n” In this, we perform the task of conversion by removing “\n” by replacement by empty string. Python3 # Python3 code to demonstrate working of # Interconvert Horizontal and Vertical String# using [Vertical to Horizontal] using replace() + "\n" # initializing stringtest_str = 'g\ne\ne\nk\ns\nf\no\nr\ng\ne\ne\nk\ns\n' # printing original Stringprint("The original string is : " + str(test_str)) # using replace() + "\n" to solve this problemres = test_str.replace("\n", "") # printing result print("The converted string : " + str(res)) The original string is : g e e k s f o r g e e k s The converted string : geeksforgeeks Python string-programs Python Python Programs 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Split string into list of characters Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2020" }, { "code": null, "e": 118, "s": 52, "text": "Given a String, convert to vertical if horizontal and vice-versa." }, { "code": null, "e": 221, "s": 118, "text": "Input : test_str = ‘geeksforgeeks’Outpu...
Loading Data From Amazon S3 To Amazon Redshift | by Shafiqa Iqbal | Towards Data Science
In this tutorial, you walk through the process of loading data into your Amazon Redshift database tables from data files in an Amazon S3 bucket from beginning to end. In this tutorial, you’ll do the following: Connect to Amazon Redshift using SQL Workbench/J. Launch an Amazon Redshift cluster and create a database table and schema. Use COPY commands to load the table from the data files on Amazon S3. Step 1: Sign in to your AWS account and go to Amazon Redshift Console. Step 2: On the navigation menu, choose CLUSTERS, then choose Create cluster. The Create cluster page appears. Step 3: Choose dc2.large for the node type in the Compute-optimized section. Then choose 1 for the Nodes. Step 4: In the Cluster details section, specify values for Cluster identifier, Database port, Master user name, and Master user password. Step 5: Go to IAM roles and create a new role with AmazonS3ReadOnlyAccess policy. Step 6: Choose create cluster. Step 7: In order to be able to connect to your redshift cluster, make it publically accessible. Go to Network and Security, edit publically accessible tab, Allow instances and devices outside the VPC connect to your database through the cluster endpoint and attach an Elastic IP. Step 8: Open the security group attached to your cluster (in Network and security) and allow access to your Public IP in inbound rules. Step 1: Go to https://www.sql-workbench.eu/downloads.html and download generic package for all systems. Step 2: Open exe file in windows and jar file in linux/mac. Step 3: Once SQL Workbench/J is opened, Choose File, and then choose Connect window. Step 4: Choose Create a new connection profile. Choose Manage Drivers. The Manage Drivers dialog opens. In the Name box, type a name for the driver. Step 5: Add your jar file by importing it from computer. Step 6: Enter your JDBC URL copied from Redshift Console’s Connection details. Step 7: Enter your username and password and select Auto-commit checkbox to True. Step 8: Test your connection. It will connect to your AWS Redshift cluster. Here are the final configurations. Step 1: Download allusers_pipe.txt file from here. Create a bucket on AWS S3 and upload the file there. Step 2: Create your schema in Redshift by executing the following script in SQL Workbench/j. create schema schema-name authorization db-username; Step 3: Create your table in Redshift by executing the following script in SQL Workbench/j. create table schema-name.users(userid integer not null distkey sortkey,username char(8),firstname varchar(30),lastname varchar(30),city varchar(30),state char(2),email varchar(100),phone char(14),likesports boolean,liketheatre boolean,likeconcerts boolean,likejazz boolean,likeclassical boolean,likeopera boolean,likerock boolean,likevegas boolean,likebroadway boolean,likemusicals boolean); Step 4: Run the following COPY command. The COPY command includes a placeholder for the Amazon Resource Name (ARN) for the IAM role, your bucket name, and an AWS Region, as shown in the following example. copy users from 's3://<myBucket>/allusers_pipe.txt'iam_role 'aws_iam_role=<iam-role-arn>'delimiter '|' region '<aws-region>'; you can create multiple tables with this structure and populate them accordingly. Step 5: Now try the example query, you should see the following result. select * from users; In this tutorial, we loaded S3 files in Amazon Redshift using Copy Commands. We connected SQL Workbench/J, created Redshift cluster, created schema and tables. For upcoming stories, you should follow my profile Shafiqa Iqbal. That’s it, guys! Have fun, keep learning & always coding!
[ { "code": null, "e": 339, "s": 172, "text": "In this tutorial, you walk through the process of loading data into your Amazon Redshift database tables from data files in an Amazon S3 bucket from beginning to end." }, { "code": null, "e": 382, "s": 339, "text": "In this tutorial, y...
Tryit Editor v3.7
Tryit: The traditional way - no use of variables
[]
Kubernetes - Autoscaling
Autoscaling is one of the key features in Kubernetes cluster. It is a feature in which the cluster is capable of increasing the number of nodes as the demand for service response increases and decrease the number of nodes as the requirement decreases. This feature of auto scaling is currently supported in Google Cloud Engine (GCE) and Google Container Engine (GKE) and will start with AWS pretty soon. In order to set up scalable infrastructure in GCE, we need to first have an active GCE project with features of Google cloud monitoring, google cloud logging, and stackdriver enabled. First, we will set up the cluster with few nodes running in it. Once done, we need to set up the following environment variable. export NUM_NODES = 2 export KUBE_AUTOSCALER_MIN_NODES = 2 export KUBE_AUTOSCALER_MAX_NODES = 5 export KUBE_ENABLE_CLUSTER_AUTOSCALER = true Once done, we will start the cluster by running kube-up.sh. This will create a cluster together with cluster auto-scalar add on. ./cluster/kube-up.sh On creation of the cluster, we can check our cluster using the following kubectl command. $ kubectl get nodes NAME STATUS AGE kubernetes-master Ready,SchedulingDisabled 10m kubernetes-minion-group-de5q Ready 10m kubernetes-minion-group-yhdx Ready 8m Now, we can deploy an application on the cluster and then enable the horizontal pod autoscaler. This can be done using the following command. $ kubectl autoscale deployment <Application Name> --cpu-percent = 50 --min = 1 -- max = 10 The above command shows that we will maintain at least one and maximum 10 replica of the POD as the load on the application increases. We can check the status of autoscaler by running the $kubclt get hpa command. We will increase the load on the pods using the following command. $ kubectl run -i --tty load-generator --image = busybox /bin/sh $ while true; do wget -q -O- http://php-apache.default.svc.cluster.local; done We can check the hpa by running $ kubectl get hpa command. $ kubectl get hpa NAME REFERENCE TARGET CURRENT php-apache Deployment/php-apache/scale 50% 310% MINPODS MAXPODS AGE 1 20 2m $ kubectl get deployment php-apache NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE php-apache 7 7 7 3 4m We can check the number of pods running using the following command. jsz@jsz-desk2:~/k8s-src$ kubectl get pods php-apache-2046965998-3ewo6 0/1 Pending 0 1m php-apache-2046965998-8m03k 1/1 Running 0 1m php-apache-2046965998-ddpgp 1/1 Running 0 5m php-apache-2046965998-lrik6 1/1 Running 0 1m php-apache-2046965998-nj465 0/1 Pending 0 1m php-apache-2046965998-tmwg1 1/1 Running 0 1m php-apache-2046965998-xkbw1 0/1 Pending 0 1m And finally, we can get the node status. $ kubectl get nodes NAME STATUS AGE kubernetes-master Ready,SchedulingDisabled 9m kubernetes-minion-group-6z5i Ready 43s kubernetes-minion-group-de5q Ready 9m kubernetes-minion-group-yhdx Ready 9m 41 Lectures 5 hours AR Shankar 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Nigel Poulton 25 Lectures 1.5 hours Pranjal Srivastava 18 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2599, "s": 2195, "text": "Autoscaling is one of the key features in Kubernetes cluster. It is a feature in which the cluster is capable of increasing the number of nodes as the demand for service response increases and decrease the number of nodes as the requirement decreases. T...
A Complete Beginners Guide to Matrix Multiplication for Data Science with Python Numpy | by GreekDataGuy | Towards Data Science
Linear algebra is the basis of machine learning from logistic regressions to deep neural networks. If you’ve been doing data science for a while but don’t understand the math behind it, matrix multiplication is the best place to start. It’s approachable, practical, and familiarizes you with the mathematical objects of machine learning: scalars, vectors and matrices. Oh yeah, and Numpy makes it a walk in the park. By the end of this article, you’ll have a practical understanding of matrix multiplication. Here we’ll contrast matrices with scalars. A matrix is a 2D array, where each element in the array has 2 indices. For example, [[1, 2], [3, 4]] is a matrix, and the index of 1 is (0,0). We can prove this using Python and Numpy. import numpy as npA = [[1, 2], [3, 4]]np.array(A)[0,0]=> 1 When talking about the shape of matrices, we say “rows x columns”. We would say the 1st matrix below has a shape of 2x2, and the 2nd has a shape of 3x2. [[1, 2], [3, 4]][[10, 20], [11, 21], [12, 22]] In contrast, a scalar is just a number, like the number 5. The simple form of matrix multiplication is called scalar multiplication, multiplying a scalar by a matrix. Scalar multiplication is generally easy. Each value in the input matrix is multiplied by the scalar, and the output has the same shape as the input matrix. Let’s do the above example but with Python’s Numpy. a = 7B = [[1,2], [3,4]]np.dot(a,B)=> array([[ 7, 14],=> [21, 28]]) One more scalar multiplication example. This time a scalar multiplying a 3x1 matrix. And in Numpy. a = 4 B = [[1],[2],[3]]np.dot(a,B)=> array([[ 4],=> [ 8],=> [12]]) Order doesn’t matter with scalar multiplication. “scalar x matrix” and “matrix x scalar” give the same result. But not so when multiplying 2 matrices. Now to the fun part. Multiply a 2D matrix by a 2D matrix. There are a few things to keep in mind. Order matters now. AB != BAMatrices can be multiplied if the number of columns in the 1st equals the number of rows in the 2ndMultiplication is the dot product of rows and columns. Rows of the 1st matrix with columns of the 2nd Order matters now. AB != BA Matrices can be multiplied if the number of columns in the 1st equals the number of rows in the 2nd Multiplication is the dot product of rows and columns. Rows of the 1st matrix with columns of the 2nd In the above image, 19 in the (0,0) index of the outputted matrix is the dot product of the 1st row of the 1st matrix and the 1st column of the 2nd matrix. Let’s replicate the result in Python. A = [[1,2], [3,4]]B = [[5,6], [7,8]]np.dot(A,B)=> array([[19, 22],=> [43, 50]]) And let’s hammer home the point about order. Try np.dot(A,B) and then try np.dot(B,A). np.dot(A,B)=> array([[19, 22],=> [43, 50]])np.dot(B,A)=> array([[23, 34],=> [31, 46]]) Now notice how the output is different! You’ll find the same result calculating it on paper (as unintuitive as it is if you’re not familiar with matrices). Now we’ll multiply a 2x3 matrix with a 3x2 matrix. And in Python with Numpy. A = [[1,2,3], [4,5,6]]B = [[10,11], [20,21], [30,31]]np.dot(A,B)=> array([[140, 146],=> [320, 335]]) Last example. Multiply a 1x5 with a 5x1 matrix. Notice how all the calculation we do here are simply to return a single cell in the output matrix. And once again, in Python. A = [[1,2,3,4,5]]B = [[10], [20], [30], [40], [50]]np.dot(A,B)=> array([[550]]) That covers 3 unique cases of matrix multiplication and should give you a general sense of how it works. I’ve shown all the calculations in each step of the diagrams so it’s easy for you to follow along. Matrix multiplication (and linear algebra) is the basis for deep learning and machine learning. While you don’t need it to plug and play with Sklearn, having a mental picture of how it works will help you understand it’s models. And with that understanding comes an increased efficiency in tuning and tweaking those models for better performance.
[ { "code": null, "e": 270, "s": 171, "text": "Linear algebra is the basis of machine learning from logistic regressions to deep neural networks." }, { "code": null, "e": 540, "s": 270, "text": "If you’ve been doing data science for a while but don’t understand the math behind it, ...
Working With Command Line
In this chapter, we will learn how to make use of the command line to run test cases. To begin with, let us open the command prompt and go to the folder where your test cases are saved. We have created test cases and saved in the folder robotframework in C Drive. Test cases created so far are available in the folder C:\robotframework. If you have saved your project as a file, the command is − robot -T nameoftestcase.robot If you have saved your project as a directory, the command is − robot -T projectname testsuite We will run one of the test created from the folder as shown below − The output, log and report paths are displayed at the end as shown above. The following screenshot shows the execution details − We can use command line to execute robot test cases. The details of the test case pass or fail are displayed in the command line along with log and report URLs. 17 Lectures 1 hours Musab Zayadneh 11 Lectures 31 mins Musab Zayadneh 20 Lectures 1.5 hours Maksym Rudnyi 25 Lectures 3 hours Kamal Kishor Girdher 16 Lectures 3.5 hours Onur 10 Lectures 34 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2255, "s": 2169, "text": "In this chapter, we will learn how to make use of the command line to run test cases." }, { "code": null, "e": 2433, "s": 2255, "text": "To begin with, let us open the command prompt and go to the folder where your test cases are sav...
Python - Sum of Cubes in List - GeeksforGeeks
29 Dec, 2019 Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of cubes of list in just one line. Let’s discuss certain ways in which this can be performed. Method #1 : Using reduce() + lambdaThe power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2. # Python code to demonstrate # Cube Summation in List# using reduce() + lambda # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print ("The original list is : " + str(test_list)) # using reduce() + lambda# Cube Summation in Listres = reduce(lambda i, j: i + j * j*j, [test_list[:1][0]**3]+test_list[1:]) # printing resultprint ("The sum of cubes of list is : " + str(res)) The original list is : [3, 5, 7, 9, 11] The sum of cubes of list is : 2555 Method #2 : Using map() + sum()The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the cube number. # Python3 code to demonstrate # Cube Summation in List# using sum() + map() # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print ("The original list is : " + str(test_list)) # using sum() + map()# Cube Summation in Listres = sum(map(lambda i : i * i * i, test_list)) # printing resultprint ("The sum of cubes of list is : " + str(res)) The original list is : [3, 5, 7, 9, 11] The sum of cubes of list is : 2555 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25058, "s": 25030, "text": "\n29 Dec, 2019" }, { "code": null, "e": 25402, "s": 25058, "text": "Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize th...
C++ Program to Implement Circular Queue
A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first. A circular queue is a type of queue in which the last position is connected to the first position to make a circle. A program to implement circular queue in C++ is given as follows − #include <iostream> using namespace std; int cqueue[5]; int front = -1, rear = -1, n=5; void insertCQ(int val) { if ((front == 0 && rear == n-1) || (front == rear+1)) { cout<<"Queue Overflow \n"; return; } if (front == -1) { front = 0; rear = 0; } else { if (rear == n - 1) rear = 0; else rear = rear + 1; } cqueue[rear] = val ; } void deleteCQ() { if (front == -1) { cout<<"Queue Underflow\n"; return ; } cout<<"Element deleted from queue is : "<<cqueue[front]<<endl; if (front == rear) { front = -1; rear = -1; } else { if (front == n - 1) front = 0; else front = front + 1; } } void displayCQ() { int f = front, r = rear; if (front == -1) { cout<<"Queue is empty"<<endl; return; } cout<<"Queue elements are :\n"; if (f <= r) { while (f <= r){ cout<<cqueue[f]<<" "; f++; } } else { while (f <= n - 1) { cout<<cqueue[f]<<" "; f++; } f = 0; while (f <= r) { cout<<cqueue[f]<<" "; f++; } } cout<<endl; } int main() { int ch, val; cout<<"1)Insert\n"; cout<<"2)Delete\n"; cout<<"3)Display\n"; cout<<"4)Exit\n"; do { cout<<"Enter choice : "<<endl; cin>>ch; switch(ch) { case 1: cout<<"Input for insertion: "<<endl; cin>>val; insertCQ(val); break; case 2: deleteCQ(); break; case 3: displayCQ(); break; case 4: cout<<"Exit\n"; break; default: cout<<"Incorrect!\n"; } } while(ch != 4); return 0; } The output of the above program is as follows − 1)Insert 2)Delete 3)Display 4)Exit Enter choice : 1 Input for insertion: Enter choice : 1 Input for insertion: Enter choice : 1 Input for insertion: Enter choice : 1 Input for insertion: Enter choice : 1 Input for insertion: Enter choice : 2 Element deleted from queue is : 5 Enter choice : 2 Element deleted from queue is : 3 Enter choice : 2 Element deleted from queue is : 2 Enter choice : 1 Input for insertion: 6 Enter choice : 3 Queue elements are : 7 9 6 Enter choice : 4 Exit
[ { "code": null, "e": 1238, "s": 1062, "text": "A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first." }, { "code": null, "e": 1354, "s": 1238, "text": "A circ...
Python File read() Method
Python file method read() reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes. Following is the syntax for read() method − fileObject.read( size ); size − This is the number of bytes to be read from the file. size − This is the number of bytes to be read from the file. This method returns the bytes read in string. The following example shows the usage of read() method. This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.read(10) print "Read Line: %s" % (line) # Close opend file fo.close() When we run above program, it produces following result − Name of the file: foo.txt Read Line: Python is 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
[ { "code": null, "e": 2396, "s": 2244, "text": "Python file method read() reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes." }, { "code": null, "e": 2440, "s": 2396, "text": "Following is the syntax for re...
How to use the ConvertFrom-StringData command in PowerShell?
The ConvertFrom-String command converts the String to the Hashtable format as shown below. PS C:\> "This is string" | ConvertFrom-String P1 P2 P3 -- -- -- This is string In the above example, We haven’t specified any header so that the output is separated the delimiter by space P1, P2 and continuous. By default, this command separates the string with a ‘=’ delimiter as shown below. $stringhash = @" Name = Spooler Starttype = Manual Status = Stopped "@ $stringhash | ConvertFrom-StringData Name Value ---- ----- Status Stopped Starttype Manual Name Spooler Another method we can use is by separating string Keys and values with a delimiter parameter. This parameter is only available in the PowerShell core 7.1 version. $stringhash = @" Name | Spooler Starttype | Manual Status | Stopped "@ ConvertFrom-StringData -StringData $stringhash -Delimiter '|' We can also use the below method. PS C:\> $stringhash = "Name = Spooler `n StartType = Manual `n Status = Stopped" PS C:\> ConvertFrom-StringData -StringData $stringhash Name Value ---- ----- Status Stopped Name Spooler StartType Manual
[ { "code": null, "e": 1153, "s": 1062, "text": "The ConvertFrom-String command converts the String to the Hashtable format as shown below." }, { "code": null, "e": 1199, "s": 1153, "text": "PS C:\\> \"This is string\" | ConvertFrom-String" }, { "code": null, "e": 1232,...
ArrayList clone() method in Java with Examples - GeeksforGeeks
18 Dec, 2018 The Java.util.ArrayList.clone() method is used to create a shallow copy of the mentioned array list. It just creates a copy of the list. Syntax: ArrayList.clone() Parameters: This method does not take any parameters. Return Value: This function returns a copy of the instance of Linked list. Below program illustrate the Java.util.ArrayList.clone() method: Example 1: // Java code to illustrate clone() method import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<String> list = new ArrayList<String>(); // Use add() method // to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the list System.out.println("First ArrayList: " + list); // Creating another linked list and copying ArrayList sec_list = new ArrayList(); sec_list = (ArrayList)list.clone(); // Displaying the other linked list System.out.println("Second ArrayList is: " + sec_list); }} First ArrayList: [Geeks, for, Geeks, 10, 20] Second ArrayList is: [Geeks, for, Geeks, 10, 20] Example 2: // Java code to illustrate clone() method import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Use add() method // to add elements in the list list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); // Displaying the list System.out.println("First ArrayList: " + list); // Creating another linked list and copying ArrayList sec_list = new ArrayList(); sec_list = (ArrayList)list.clone(); // Displaying the other linked list System.out.println("Second ArrayList is: " + sec_list); }} First ArrayList: [10, 20, 30, 40, 50] Second ArrayList is: [10, 20, 30, 40, 50] Java - util package Java-ArrayList Java-Collections Java-Functions Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Multithreading in Java LinkedList in Java Overriding in Java Stack Class in Java
[ { "code": null, "e": 24658, "s": 24630, "text": "\n18 Dec, 2018" }, { "code": null, "e": 24795, "s": 24658, "text": "The Java.util.ArrayList.clone() method is used to create a shallow copy of the mentioned array list. It just creates a copy of the list." }, { "code": null...
Bulma Background Color - GeeksforGeeks
01 Dec, 2021 Bulma is a free and open-source CSS framework based on Flexbox. It is component-rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design. Background class accepts lots of value in Bulma which all the properties are covered in class form. By using this class we can color any background. In CSS, we do that by using the CSS Color property. Syntax: <tag class="has-background-*"> Text </tag> Background Color classes We can use any of these colors listed below at the place of * in the above syntax: has-background-white: This class used to set the background color white. has-background-black: This class used to set the background color black. has-background-light: This class used to set the background color cream. has-background-dark: This class used to set the background color dark brown. has-background-primary: This class is used to set the background color light cyan. has-background-link: This class used to set the background color blue. has-background-info: This class used to set the background color light blue. has-background-success: This class used to set the background color green. has-background-warning: This class used to set the background color yellow. has-background-danger: This class used to set the background color red. Note: You can set any element to one of the 10 colors or 9 shades of grey. You can use each color in its light and dark versions. Simply append *-light or *-dark. Below example illustrate the text color in Bulma: Example: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css"></head> <body> <h1 class="is-size-2"> GeeksforGeeks </h1> <b>Bulma Background Color Class</b> <br> <div> <p class="has-text-white has-background-black"> A Computer Science Portal for Geeks </p> <p class="has-text-black has-background-white"> A Computer Science Portal for Geeks </p> <p class="has-text-light has-background-dark"> A Computer Science Portal for Geeks </p> <p class="has-text-dark has-background-light"> A Computer Science Portal for Geeks </p> <p class="has-text-primary has-background-link"> A Computer Science Portal for Geeks </p> <p class="has-text-link has-background-primary"> A Computer Science Portal for Geeks </p> <p class="has-text-info has-background-success"> A Computer Science Portal for Geeks </p> <p class="has-text-success has-background-info"> A Computer Science Portal for Geeks </p> <p class="has-text-warning has-background-danger"> A Computer Science Portal for Geeks </p> <p class="has-text-danger has-background-warning"> A Computer Science Portal for Geeks </p> </div></body> </html> Output: Reference: https://bulma.io/documentation/helpers/color-helpers/#background-color Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25400, "s": 25372, "text": "\n01 Dec, 2021" }, { "code": null, "e": 25796, "s": 25400, "text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component-rich, compatible, and well documented. It is highly responsive in nature. It uses c...
How to use Tooltip component in ReactJS? - GeeksforGeeks
05 Mar, 2021 Tooltips display informative text when users hover over, focus on, or tap an element. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Tooltip Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import IconButton from "@material-ui/core/IconButton";import Tooltip from "@material-ui/core/Tooltip";import PersonIcon from "@material-ui/icons/Person";import DeleteIcon from "@material-ui/icons/Delete"; export default function App() { return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Tooltip Component in ReactJS?</h4> <Tooltip title="Delete"> <IconButton> <DeleteIcon /> </IconButton> </Tooltip> <Tooltip title="Person"> <IconButton> <PersonIcon /> </IconButton> </Tooltip> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/tooltips/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments React-Router Hooks How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? ReactJS useNavigate() Hook Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24826, "s": 24798, "text": "\n05 Mar, 2021" }, { "code": null, "e": 25079, "s": 24826, "text": "Tooltips display informative text when users hover over, focus on, or tap an element. Material UI for React has this component available for us, and it is very eas...
How to use length () in Android sqlite?
Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc. This example demonstrate about How to use length () in Android sqlite Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter Name" android:layout_height="wrap_content" /> <EditText android:id="@+id/salary" android:layout_width="match_parent" android:inputType="numberDecimal" android:hint="Enter Salary" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"><Button android:id="@+id/save" android:text="Save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/refresh" android:text="Refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/udate" android:text="Update" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/Delete" android:text="DeleteALL" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button to get the listview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button save, refresh; EditText name, salary; ArrayAdapter arrayAdapter; private ListView listView; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); final DatabaseHelper helper = new DatabaseHelper(this); final ArrayList array_list = helper.getAllCotacts(); name = findViewById(R.id.name); salary = findViewById(R.id.salary); listView = findViewById(R.id.listView); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (helper.delete()) { Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show(); } } }); findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.update(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Updated", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { array_list.clear(); array_list.addAll(helper.getAllCotacts()); arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.insert(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); } } Step 4 − Add the following code to src/ DatabaseHelper.java package com.example.andy.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "salaryDatabase9"; public static final String CONTACTS_TABLE_NAME = "SalaryDetails"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 2); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL( "create table " + CONTACTS_TABLE_NAME + "(id INTEGER PRIMARY KEY, name text,salary float,datetime default current_timestamp)" ); } catch (SQLiteException e) { try { throw new IOException(e); } catch (IOException e1) { e1.printStackTrace(); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME); onCreate(db); } public boolean insert(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", s); contentValues.put("salary", s1); db.replace(CONTACTS_TABLE_NAME, null, contentValues); return true; } public ArrayList getAllCotacts() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<String> array_list = new ArrayList<String>(); Cursor res = db.rawQuery("select LENGTH(name) as fullname from " + CONTACTS_TABLE_NAME, null); res.moveToFirst(); while (res.isAfterLast() == false) { if ((res != null) && (res.getCount() > 0)) array_list.add(res.getString(res.getColumnIndex("fullname"))); res.moveToNext(); } return array_list; } public boolean update(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("UPDATE " + CONTACTS_TABLE_NAME + " SET name = " + "'" + s + "', " + "salary = " + "'" + s1 + "'"); return true; } public boolean delete() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE from " + CONTACTS_TABLE_NAME); return true; } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, we have stored name as sairamkrishna , using sqlite command we are finding the name length using length() so it is returning length of string as 13. Click here to download the project code
[ { "code": null, "e": 1457, "s": 1062, "text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the re...
Collection vs Collections in Java with Example - GeeksforGeeks
02 Sep, 2020 Collection: Collection is a interface present in java.util.package. It is used to represent a group of individual objects as a single unit. It is similar to the container in the C++ language. The collection is considered as the root interface of the collection framework. It provides several classes and interfaces to represent a group of individual objects as a single unit. The List, Set, and Queue are the main sub-interfaces of the collection interface. The map interface is also part of the java collection framework, but it doesn’t inherit the collection of the interface. The add(), remove(), clear(), size(), and contains() are the important methods of the Collection interface. Declaration: public interface Collection<E> extends Iterable<E> Type Parameters: E - the type of elements returned by this iterator Collections: Collections is a utility class present in java.util.package. It defines several utility methods like sorting and searching which is used to operate on collection. It has all static methods. These methods provide much-needed convenience to developers, allowing them to effectively work with Collection Framework. For example, It has a method sort() to sort the collection elements according to default sorting order, and it has a method min(), and max() to find the minimum and maximum value respectively in the collection elements. Declaration: public class Collections extends Object Collection vs Collections: Java // Java program to demonstrate the difference // between Collection and Collections import java.io.*;import java.util.*; class GFG { public static void main (String[] args) { // Creating an object of List<String> List<String> arrlist = new ArrayList<String>(); // Adding elements to arrlist arrlist.add("geeks"); arrlist.add("for"); arrlist.add("geeks"); // Printing the elements of arrlist // before operations System.out.println("Elements of arrlist before the operations:"); System.out.println(arrlist); System.out.println("Elements of arrlist after the operations:"); // Adding all the specified elements // to the specified collection Collections.addAll(arrlist, "web", "site"); // Printing the arrlist after // performing addAll() method System.out.println(arrlist); // Sorting all the elements of the // specified collection according to // default sorting order Collections.sort(arrlist); // Printing the arrlist after // performing sort() method System.out.println(arrlist); }} Elements of arrlist before the operations: [geeks, for, geeks] Elements of arrlist after the operations: [geeks, for, geeks, web, site] [for, geeks, geeks, site, web] Java-Collections Difference Between Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference Between == and .equals() Method in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 27876, "s": 27848, "text": "\n02 Sep, 2020" }, { "code": null, "e": 28253, "s": 27876, "text": "Collection: Collection is a interface present in java.util.package. It is used to represent a group of individual objects as a single unit. It is similar to the co...
\begin - Tex Command
\begin - is used in begin/end environment. { \begin } \begin command is used in begin/end environment. \begin{gather}a\\a+b\\a+b+c\end{gather} aa+ba+b+c \begin{gather}a\\a+b\\a+b+c\end{gather} aa+ba+b+c \begin{gather}a\\a+b\\a+b+c\end{gather} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8029, "s": 7986, "text": "\\begin - is used in begin/end environment." }, { "code": null, "e": 8040, "s": 8029, "text": "{ \\begin }" }, { "code": null, "e": 8089, "s": 8040, "text": "\\begin command is used in begin/end environment." },...
How to add months to a date in JavaScript?
To add months to a JavaScript Date, use the setMonth() method. JavaScript date setMonth() method sets the months for a specified date according to local time. You can try to run the following code to add 2 months. <html> <head> <title>JavaScript setMonth Method</title> </head> <body> <script> var dt = new Date("August 20, 2017 11:30:25"); dt.setMonth( dt.getMonth() + 2 ); document.write( dt ); </script> </body> </html>
[ { "code": null, "e": 1221, "s": 1062, "text": "To add months to a JavaScript Date, use the setMonth() method. JavaScript date setMonth() method sets the months for a specified date according to local time." }, { "code": null, "e": 1276, "s": 1221, "text": "You can try to run the ...
What are the Rules of Regular Expressions in Compiler Design?
The language accepted by finite automata can be simply defined by simple expressions known as Regular Expressions. It is an effective approach to describe any language. A regular expression can also be represented as a sequence of patterns that represent a string. Regular expressions are used to connect character sequence in strings. The string searching algorithm used this pattern to discover the operations on a string. There are various rules for regular expressions which are as follows − ε is a Regular expression. ε is a Regular expression. Union of two Regular Expressions R1 and R2. Union of two Regular Expressions R1 and R2. i.e., R1 + R2 or R1|R2 is also a regular expression. Concatenation of two Regular Expressions R1 and R2. Concatenation of two Regular Expressions R1 and R2. i.e., R1 R2 is also a Regular Expression. Closure of Regular Expression R, i.e., R* is also a Regular Expression. Closure of Regular Expression R, i.e., R* is also a Regular Expression. If R is a Regular Expression, then (R) is also a Regular Expression. If R is a Regular Expression, then (R) is also a Regular Expression. R1|R2=R2|R1 or R1+ R2=R2+ R1 (Commutative) R1| (R2|R3)=(R1| R2)|R3 (Associative) Or R1+ (R2+ R3)=(R1+ R2)+R3 R1 (R2|R3)=(R1R2)R3 (Associative) R1| (R2|R3)=R1R2| R1R3 (Distributive) Or R1 (R2+ R3)=R1R2+R1R3 ε R=R ε=R (Concatenation) Example1 − Write Regular Expressions for the following language over ∑ ={a,b} String of length zero or one. Answer: ε | a | b or (ε+a+b) Strings of length two. Answer: aa | ab | bb or (aa+ab+ba +bb) Strings of Even Length Answer: (aa| ab| ba | bb)* or (aa+ab+ba +bb)* Set of all strings of a’s and b’s having at least two occurrences of aa. Answer − (a+b)*aa(a+b)aa(a+b)* Example2 − Find Regular Expressions for following language. L={ε,1,11,111,....} {∴ 10=ε,11=1,12=11,13=111.....} Answer: 1* L={ε,11,1111,111111,.....} Answer: (11) ∗ L = Set of all strings of 0’s and 1’s = {ε,0,1,01,11,00,000,101,......} L = Set of all strings of 0’s and 1’s = {ε,0,1,01,11,00,000,101,......} Answer: (0+1) ∗ or (0|1) ∗ L = Set of all strings of 0’s and 1’s ending with 11. L = Set of all strings of 0’s and 1’s ending with 11. Answer: (0+1) ∗ 11 L = Set of all strings of 0’s and 1’s beginning with 0 and ending with 1. L = Set of all strings of 0’s and 1’s beginning with 0 and ending with 1. Answer: 0(0+1) ∗ 1 Example3 − Write Regular Expression in which the second letter from the right end of the string is 1 where ∑ ={0,1}. Answer: (0+1) ∗ 1(0+1) Example4 − Write Regular Expressions for the following language over ∑ ={a,b} L=Set of strings having at least one occurrence of the double letter L=Set of strings having at least one occurrence of the double letter Answer: (a+b)*(aa+bb)(a+b)* L = Set of strings having double letter at Beginning and Ending of string. L = Set of strings having double letter at Beginning and Ending of string. Answer: (aa+bb)(a+b)*(aa+bb) L = Set of strings having double letter at Beginning or on Ending of string. L = Set of strings having double letter at Beginning or on Ending of string. Answer: (aa+bb)(a+b)*+ (a+b)*(aa+bb)+(aa+bb)(a+b)*(aa+bb)
[ { "code": null, "e": 1487, "s": 1062, "text": "The language accepted by finite automata can be simply defined by simple expressions known as Regular Expressions. It is an effective approach to describe any language. A regular expression can also be represented as a sequence of patterns that represen...
MultiClass Classification Using K-Nearest Neighbours | by Vatsal Sheth | Towards Data Science
INTRODUCTION: Classification is a classic machine learning application. Classification basically categorises your output in two classes i.e. your output can be one of two things. For example, a bank wants to know whether a customer will be able pay his/her monthly investments or not? We can use machine learning algorithms to determine the output of this problem, which will be either Yes or No(Two classes). But what if you want to classify something that has more than 2 categories and isn’t as simple as a yes/no problem? This is where multi-class classification comes in. MultiClass classification can be defined as the classifying instances into one of three or more classes. In this article we are going to do multi-class classification using K Nearest Neighbours. KNN is a super simple algorithm, which assumes that similar things are in close proximity of each other. So if a datapoint is near to another datapoint, it assumes that they both belong to similar classes. To know more deeply about KNN algorithms, I would suggest you go check out this article: towardsdatascience.com Now, that we are through all the basics, let’s get to some implementation. We are going to use multiple python libraries like pandas(To read our dataset), Sklearn(To train our dataset and implement our model) and libraries like Seaborn and Matplotlib(To visualise our data). If you don’t already have this libraries install you can install them using pip or Anaconda on your pc/laptop. Or another way that I would personally suggest, use google colab to perform the experiment online with all the libraries pre-installed. The dataset that we are going to be using is called the IRIS flower dataset and it basically has 4 features for it’s 150 data points and is categorised into 3 different species i.e. 50 flowers of each species.The dataset can be downloaded from the following link: www.kaggle.com Now as we get started with our code, the first step to do is to import all the libraries in our code. from sklearn import preprocessingfrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pd Once you’ve imported the libraries the next step is to read the data.We will use the pandas library for this function. While reading, we will also check if there are any null values as well as the number of different species in the data. (Should be 3 as our dataset has 3 species). We will also assign all the three species categories a particular number, 0,1 and 2. df = pd.read_csv(‘IRIS.csv’)df.head() df[‘species’].unique() Output: array([‘Iris-setosa’, ‘Iris-versicolor’, ‘Iris-virginica’], dtype=object) df.isnull().values.any() Output: False df[‘species’] = df[‘species’].map({‘Iris-setosa’ :0, ‘Iris-versicolor’ :1, ‘Iris-virginica’ :2}).astype(int) #mapping numbersdf.head() Once, that we are now done with importing libraries and our CSV file, the next step we do is exploratory data analysis(EDA). EDA is necessary for any problem as it helps us visualise the data and infer some conclusions initially just by looking at the data and not performing any algorithms. We perform correlations between all the features using the library seaborn as well as plot a scatterplot of all the datasets using the same library. plt.close();sns.set_style(“whitegrid”);sns.pairplot(df, hue=”species”, height=3);plt.show() Output: sns.set_style(“whitegrid”);sns.FacetGrid(df, hue=’species’, size=5) \.map(plt.scatter, “sepal_length”, “sepal_width”) \.add_legend();plt.show() Output: Inferences from EDA: While Setosa can be easily identified, Virnica and Versicolor have some overlap .Length and Width are the most important features to identify various flower types. While Setosa can be easily identified, Virnica and Versicolor have some overlap . Length and Width are the most important features to identify various flower types. After the EDA and before training our model on the dataset, the one last thing left to do is normalisation. Normalisation is basically bringing all the values of different features on a same scale. As different features has different scale, normalising helps us and the model to optimise it’s parameters more efficiently. We normalise all our input from scale: 0 to 1. Here, X is our inputs(hence dropping the classified species) and Y is our output(3 classes). x_data = df.drop([‘species’],axis=1)y_data = df[‘species’]MinMaxScaler = preprocessing.MinMaxScaler()X_data_minmax = MinMaxScaler.fit_transform(x_data)data = pd.DataFrame(X_data_minmax,columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])df.head() Finally, we have reached to the point of training the dataset. We use the built-in KNN algorithm from sci-kit learn. We split the our input and output data into training and testing data, as to train the model on training data and testing model’s accuracy on the testing model. We choose a 80%–20% split for our training and testing data. X_train, X_test, y_train, y_test = train_test_split(data, y_data,test_size=0.2, random_state = 1)knn_clf=KNeighborsClassifier()knn_clf.fit(X_train,y_train)ypred=knn_clf.predict(X_test) #These are the predicted output values Output: KNeighborsClassifier(algorithm=’auto’, leaf_size=30, metric=’minkowski’, metric_params=None, n_jobs=None, n_neighbors=5, p=2, weights=’uniform’) Here, we see that the classifier chose 5 as the optimum number of nearest neighbours to classify the data best. Now that we have built the model, our final step is to visualise the results. We calculate the confusion matrix, the precision recall parameters and the overall accuracy of the model. from sklearn.metrics import classification_report, confusion_matrix, accuracy_scoreresult = confusion_matrix(y_test, ypred)print(“Confusion Matrix:”)print(result)result1 = classification_report(y_test, ypred)print(“Classification Report:”,)print (result1)result2 = accuracy_score(y_test,ypred)print(“Accuracy:”,result2) Output: Summary/Conclusion: We successfully implemented a KNN algorithm for the IRIS datset. We found out the most impactful deatures through out EDA and normalised our dataset for improved accuracy. We got an accuracy of 96.67% with our algorithm as well as we got the confusion matrix and the classification report. From the classification report and the confusion matrix we can see that it misidentifies versicolor as virginica. That is how one can do multi-class classification using KNN algorithm. Hope you learned something new and meaningful today.
[ { "code": null, "e": 185, "s": 171, "text": "INTRODUCTION:" }, { "code": null, "e": 697, "s": 185, "text": "Classification is a classic machine learning application. Classification basically categorises your output in two classes i.e. your output can be one of two things. For exa...
ASP.NET MVC - Data Annotations
DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations. DataAnnotation attributes override default Code-First conventions. System.ComponentModel.DataAnnotations includes the following attributes that impacts the nullability or size of the column. Key Timestamp ConcurrencyCheck Required MinLength MaxLength StringLength System.ComponentModel.DataAnnotations.Schema namespace includes the following attributes that impacts the schema of the database. Table Column Index ForeignKey NotMapped InverseProperty Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that Code First depends on is how it implies which property is the key in each of the Code First classes. The convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “StudentId”. The property will map to a primary key column in the database. The Student, Course and Enrollment classes follow this convention. Now let’s suppose Student class used the name StdntID instead of ID. When Code First does not find a property that matches this convention it will throw an exception because of Entity Framework’s requirement that you must have a key property. You can use the key annotation to specify which property is to be used as the EntityKey. Let’s take a look at the Student class which contains StdntID. It doesn’t follow the default Code First convention so to handle this, Key attribute is added, which will make it a primary key. public class Student{ [Key] public int StdntID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } When you run the application and look into the database in SQL Server Explorer, you will see that the primary key is now StdntID in Students table. Entity Framework also supports composite keys. Composite keys are primary keys that consist of more than one property. For example, you have a DrivingLicense class whose primary key is a combination of LicenseNumber and IssuingCountry. public class DrivingLicense{ [Key, Column(Order = 1)] public int LicenseNumber { get; set; } [Key, Column(Order = 2)] public string IssuingCountry { get; set; } public DateTime Issued { get; set; } public DateTime Expires { get; set; } } When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order. Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it will also ensure that the database field generated by Code First is non-nullable. It's more common to use rowversion or timestamp fields for concurrency checking. But rather than using the ConcurrencyCheck annotation, you can use the more specific TimeStamp annotation as long as the type of the property is byte array. You can only have one timestamp property in a given class. Let’s take a look at a simple example by adding the TimeStamp property to the Course class. public class Course{ public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } [Timestamp] public byte[] TStamp { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } As you can see in the above example, Timestamp attribute is applied to Byte[] property of the Course class. So, Code First will create a timestamp column TStamp in the Courses table. The ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database, when a user edits or deletes an entity. If you've been working with the EF Designer, this aligns with setting a property's ConcurrencyMode to Fixed. Let’s take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class. public class Course{ public int CourseID { get; set; } [ConcurrencyCheck] public string Title { get; set; } public int Credits { get; set; } [Timestamp, DataType("timestamp")] public byte[] TimeStamp { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } In the above Course class, ConcurrencyCheck attribute is applied to the existing Title property. Code First will include Title column in update command to check for optimistic concurrency as shown in the following code. exec sp_executesql N'UPDATE [dbo].[Courses] SET [Title] = @0 WHERE (([CourseID] = @1) AND ([Title] = @2)) ',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max) ',@0 = N'Maths',@1 = 1,@2 = N'Calculus' go The Required annotation tells EF that a particular property is required. Let’s have a look at the following Student class in which Required id is added to the FirstMidName property. Required attribute will force EF to ensure that the property has data in it. public class Student{ [Key] public int StdntID { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. So, Code First will create a NOT NULL FirstMidName and LastName column in the Students table as shown in the following screenshot. The MaxLength attribute allows you to specify additional property validations. It can be applied to a string or array type property of a domain class. EF Code First will set the size of a column as specified in MaxLength attribute. Let’s take a look at the following Course class in which MaxLength(24) attribute is applied to Title property. public class Course{ public int CourseID { get; set; } [ConcurrencyCheck] [MaxLength(24)] public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } When you run the above application, Code-First will create a nvarchar(24) column Title in the Coursed table as shown in the following screenshot. Now when the user sets the Title which contains more than 24 characters, EF will throw EntityValidationError. The MinLength attribute allows you to specify additional property validations, just as you did with MaxLength. MinLength attribute can also be used with MaxLength attribute as shown in the following code. public class Course{ public int CourseID { get; set; } [ConcurrencyCheck] [MaxLength(24) , MinLength(5)] public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } EF will throw EntityValidationError, if you set a value of Title property less than the specified length in MinLength attribute or greater than the specified length in MaxLength attribute. StringLength also allows you to specify additional property validations like MaxLength. The difference being StringLength attribute can only be applied to a string type property of Domain classes. public class Course{ public int CourseID { get; set; } [StringLength (24)] public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } Entity Framework also validates the value of a property for StringLength attribute. Now, if the user sets the Title, which contains more than 24 characters, then EF will throw EntityValidationError. Default Code First convention creates a table name same as the class name. If you are letting Code First create the database, you can also change the name of the tables it is creating. You can use Code First with an existing database. But it's not always the case that the names of the classes match the names of the tables in your database. Table attribute overrides this default convention. EF Code First will create a table with a specified name in Table attribute for a given domain class. Let’s take a look at an example in which the class is named Student, and by convention, Code First presumes this will map to a table named Students. If that's not the case you can specify the name of the table with the Table attribute as shown in the following code. [Table("StudentsInfo")] public class Student{ [Key] public int StdntID { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can now see that the Table attribute specifies the table as StudentsInfo. When the table is generated, you will see the table name StudentsInfo as shown in the following screenshot. You cannot only specify the table name but you can also specify a schema for the table using the Table attribute using the following code. [Table("StudentsInfo", Schema = "Admin")] public class Student{ [Key] public int StdntID { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } In the above example, the table is specified with admin schema. Now Code First will create StudentsInfo table in Admin schema as shown in the following screenshot. It is also the same as Table attribute, but Table attribute overrides the table behavior while Column attribute overrides the column behavior. Default Code First convention creates a column name same as the property name. If you are letting Code First create the database, and you also want to change the name of the columns in your tables. Column attribute overrides this default convention. EF Code First will create a column with a specified name in the Column attribute for a given property. Let’s take a look at the following example again in which the property is named FirstMidName, and by convention, Code First presumes this will map to a column named FirstMidName. If that's not the case, you can specify the name of the column with the Column attribute as shown in the following code. public class Student{ public int ID { get; set; } public string LastName { get; set; } [Column("FirstName")] public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can now see that the Column attribute specifies the column as FirstName. When the table is generated, you will see the column name FirstName as shown in the following screenshot. The Index attribute was introduced in Entity Framework 6.1. Note − If you are using an earlier version, the information in this section does not apply. You can create an index on one or more columns using the IndexAttribute. Adding the attribute to one or more properties will cause EF to create the corresponding index in the database when it creates the database. Indexes make the retrieval of data faster and efficient, in most cases. However, overloading a table or view with indexes could unpleasantly affect the performance of other operations such as inserts or updates. Indexing is the new feature in Entity Framework where you can improve the performance of your Code First application by reducing the time required to query data from the database. You can add indexes to your database using the Index attribute, and override the default Unique and Clustered settings to get the index best suited to your scenario. By default, the index will be named IX_<property name> Let’s take a look at the following code in which Index attribute is added in Course class for Credits. public class Cours{ public int CourseID { get; set; } public string Title { get; set; } [Index] public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can see that the Index attribute is applied to the Credits property. Now when the table is generated, you will see IX_Credits in Indexes. By default, indexes are non-unique, but you can use the IsUnique named parameter to specify that an index should be unique. The following example introduces a unique index as shown in the following code. public class Course{ public int CourseID { get; set; } [Index(IsUnique = true)] public string Title { get; set; } [Index] public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } Code First convention will take care of the most common relationships in your model, but there are some cases where it needs help. For example, by changing the name of the key property in the Student class created a problem with its relationship to Enrollment class. public class Enrollment{ public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } public class Student{ [Key] public int StdntID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } While generating the database, Code First sees the StudentID property in the Enrollment class and recognizes it, by the convention that it matches a class name plus “ID”, as a foreign key to the Student class. But there is no StudentID property in the Student class, rather it is StdntID property in Student class. The solution for this is to create a navigation property in the Enrollment and use the ForeignKey DataAnnotation to help Code First understand how to build the relationship between the two classes as shown in the following code. public class Enrollment{ public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } [ForeignKey("StudentID")] public virtual Student Student { get; set; } } You can see now that the ForeignKey attribute is applied to navigation property. By default conventions of Code First, every property that is of a supported data type and which includes getters and setters are represented in the database. But this isn’t always the case in applications. NotMapped attribute overrides this default convention. For example, you might have a property in the Student class such as FatherName, but it does not need to be stored. You can apply NotMapped attribute to a FatherName property, which you do not want to create a column in a database. Following is the code. public class Student{ [Key] public int StdntID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } [NotMapped] public int FatherName { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can see that NotMapped attribute is applied to the FatherName property. Now when the table is generated, you will see that FatherName column will not be created in a database, but it is present in Student class. Code First will not create a column for a property which does not have either getters or setters. The InverseProperty is used when you have multiple relationships between classes. In the Enrollment class, you may want to keep track of who enrolled a Current Course and who enrolled a Previous Course. Let’s add two navigation properties for the Enrollment class. public class Enrollment{ public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course CurrCourse { get; set; } public virtual Course PrevCourse { get; set; } public virtual Student Student { get; set; } } Similarly, you’ll also need to add in the Course class referenced by these properties. The Course class has navigation properties back to the Enrollment class, which contains all the current and previous enrollments. public class Course{ public int CourseID { get; set; } public string Title { get; set; } [Index] public int Credits { get; set; } public virtual ICollection<Enrollment> CurrEnrollments { get; set; } public virtual ICollection<Enrollment> PrevEnrollments { get; set; } } Code First creates {Class Name}_{Primary Key} foreign key column if the foreign key property is not included in a particular class as shown in the above classes. When the database is generated you will see a number of foreign keys as seen in the following screenshot. As you can see that Code First is not able to match up the properties in the two classes on its own. The database table for Enrollments should have one foreign key for the CurrCourse and one for the PrevCourse, but Code First will create four foreign key properties, i.e. CurrCourse_CourseID PrevCourse_CourseID Course_CourseID Course_CourseID1 To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties. public class Course{ public int CourseID { get; set; } public string Title { get; set; } [Index] public int Credits { get; set; } [InverseProperty("CurrCourse")] public virtual ICollection<Enrollment> CurrEnrollments { get; set; } [InverseProperty("PrevCourse")] public virtual ICollection<Enrollment> PrevEnrollments { get; set; } } As you can see now, when InverseProperty attribute is applied in the above Course class by specifying which reference property of Enrollment class it belongs to, Code First will generate database and create only two foreign key columns in Enrollments table as shown in the following screenshot. We recommend you to execute the above example for better understanding. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2640, "s": 2269, "text": "DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage...
Go - Functions
A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(). You can divide your code into separate functions. How you divide your code among different functions is up to you, but logically, the division should be such that each function performs a specific task. A function declaration tells the compiler about a function name, return type, and parameters. A function definition provides the actual body of the function. The Go standard library provides numerous built-in functions that your program can call. For example, the function len() takes arguments of various types and returns the length of the type. If a string is passed to it, the function returns the length of the string in bytes. If an array is passed to it, the function returns the length of the array. Functions are also known as method, sub-routine, or procedure. The general form of a function definition in Go programming language is as follows − func function_name( [parameter list] ) [return_types] { body of the function } A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function − Func − It starts the declaration of a function. Func − It starts the declaration of a function. Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature. Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required. Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required. Function Body − It contains a collection of statements that define what the function does. Function Body − It contains a collection of statements that define what the function does. The following source code shows a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two − /* function returning the max between two numbers */ func max(num1, num2 int) int { /* local variable declaration */ result int if (num1 > num2) { result = num1 } else { result = num2 } return result } While creating a Go function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with its function name. If the function returns a value, then you can store the returned value. For example − package main import "fmt" func main() { /* local variable definition */ var a int = 100 var b int = 200 var ret int /* calling a function to get max value */ ret = max(a, b) fmt.Printf( "Max value is : %d\n", ret ) } /* function returning the max between two numbers */ func max(num1, num2 int) int { /* local variable declaration */ var result int if (num1 > num2) { result = num1 } else { result = num2 } return result } We have kept the max() function along with the main() function and compiled the source code. While running the final executable, it would produce the following result − Max value is : 200 A Go function can return multiple values. For example − package main import "fmt" func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("Mahesh", "Kumar") fmt.Println(a, b) } When the above code is compiled and executed, it produces the following result − Kumar Mahesh If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Go uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. The above program, while calling the max() function, used the same method. A function can be used in the following ways: Functions can be created on the fly and can be used as values. Functions closures are anonymous functions and can be used in dynamic programming. Methods are special functions with a receiver. 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2267, "s": 1937, "text": "A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(). You can divide your code into separate functions. How you divide your code among different functions is up to you, but logical...
How to multiply each element of a numerical vector in R?
Sometimes we want to determine the multiplication of all the elements of a vector just like the sum. This might be required to test the changes in the mathematical operations that can be applied to a numerical vector. In base R, we have prod function which works same as sum but give us the multiplication of all the elements of a vector. Live Demo > v1<-1:5 > v1 [1] 1 2 3 4 5 > prod(v1) [1] 120 Live Demo > v2<-rnorm(10) > v2 [1] -0.500466629 0.394771317 0.575743107 0.026982141 0.812697502 [6] 0.995708241 2.198243938 -0.008609976 -0.931337300 -0.073743225 > prod(v2) [1] 3.228448e-06 Live Demo > v3<-rnorm(10,1.5) > v3 [1] 1.7328245888 -0.5772304935 2.5161349689 3.0401656274 0.1669773313 [6] -0.0001252235 0.7649984733 2.4901543043 1.5618729422 2.4392364199 > prod(v3) [1] 0.001161087 Live Demo > v4<-rpois(10,2) > v4 [1] 3 2 3 5 0 0 3 2 0 4 > prod(v4) [1] 0 Live Demo > v5<-rpois(100,20) > v5 [1] 17 31 19 15 20 25 18 22 18 29 22 19 20 26 21 23 14 34 14 14 19 15 24 23 20 [26] 14 23 26 14 17 15 32 21 17 16 23 19 24 22 15 27 19 20 26 11 18 26 20 23 16 [51] 26 17 16 15 12 20 25 18 15 18 22 22 20 22 19 14 13 18 23 24 23 21 21 23 23 [76] 13 18 24 16 21 17 17 18 20 29 18 12 27 16 23 26 19 28 21 14 19 25 18 22 17 > prod(v5) [1] 1.764217e+129 Live Demo > v6<-runif(50,2,5) > v6 [1] 4.384473 2.464259 3.052674 4.754015 3.149084 2.391700 3.156066 4.546584 [9] 3.473825 3.438115 2.668482 3.956325 2.315420 2.799798 3.830397 4.223601 [17] 4.617783 3.141474 4.908374 2.274919 3.714314 2.893030 4.800681 2.211926 [25] 4.778749 3.508617 3.073959 2.819000 4.860615 3.846824 2.608646 2.810488 [33] 2.562088 2.409402 3.357812 2.668864 4.677772 2.392214 2.070477 3.510179 [41] 3.333990 3.905242 4.144810 4.614480 2.137121 3.329712 3.224403 4.085072 [49] 2.697773 4.842452 > prod(v6) [1] 1.131786e+26 Live Demo > v7<-rexp(50,2) > v7 [1] 0.196256425 0.778689736 0.422888133 0.508051269 0.002485082 0.255892951 [7] 0.138419567 0.130393627 0.846025451 0.283145254 2.114919795 0.263044225 [13] 0.174996635 0.141883192 0.099179770 0.039533379 0.164351775 0.027566355 [19] 0.540246424 0.775166984 0.060083801 0.639466961 0.115555783 0.328276267 [25] 0.025136740 1.223544536 0.080570191 0.350975182 1.143206199 0.649686242 [31] 0.481954727 0.171125844 0.583099992 0.190488726 0.025616325 0.340935745 [37] 0.060853943 1.541687444 0.544305771 0.001036567 0.037164253 0.247312260 [43] 1.175060552 0.212010939 0.104288578 0.072779226 0.343334238 0.305414554 [49] 1.682843018 0.751852211 > prod(v7) [1] 8.528215e-35 Live Demo > v8<-sample(c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),50,replace=TRUE) > v8 [1] 0.5 0.8 0.5 0.3 0.3 0.1 0.5 0.6 0.7 0.9 0.3 0.2 0.3 0.4 0.5 0.2 0.5 0.1 0.9 [20] 0.3 0.5 0.6 0.8 0.2 0.8 0.9 0.2 0.3 0.6 0.3 0.7 0.7 0.1 0.9 0.4 0.6 0.5 0.2 [39] 0.3 0.6 0.1 0.2 0.1 0.6 0.1 0.8 0.1 0.4 0.8 0.4 > prod(v8) [1] 2.88936e-22 Live Demo > v9<-sample(1:5,50,replace=TRUE) > v9 [1] 4 3 1 2 3 1 5 3 1 5 4 2 3 5 2 2 4 5 4 5 5 3 1 3 2 2 5 1 1 1 1 5 1 5 2 1 5 1 [39] 5 5 4 1 3 1 1 1 5 3 2 4 > prod(v9) [1] 8.39808e+18 Live Demo > v10<-sample(-5:5,50,replace=TRUE) > v10 [1] 1 4 -1 -1 2 -3 0 -2 0 -4 2 4 0 2 -3 -1 1 2 5 -2 -3 -2 3 2 1 [26] -2 -1 2 5 4 0 -3 1 -4 -4 -2 2 2 -3 -3 -5 2 1 0 -4 -3 -3 -3 4 2 > prod(v10) [1] 0
[ { "code": null, "e": 1401, "s": 1062, "text": "Sometimes we want to determine the multiplication of all the elements of a vector just like the sum. This might be required to test the changes in the mathematical operations that can be applied to a numerical vector. In base R, we have prod function wh...
Network Analysis with R | Manipulating Network Data | by Jinhang Jiang | Towards Data Science
Network analysis is a technique that uses graph theory to study complex real-world problems, such as computational biology, engineering, finance, marketing, neuroscience, political science, and public health (Kolaczyk et al., 2014). In my previous works, I have done quite a lot of network analysis in the python environment with NetworkX and node2vec. However, recently I came across the book - “Statistical Analysis of Network Data with R” (this is the 1st version, and the 2nd version was published in 2020)- written by Eric D. Kolaczyk and Gábor Csárdi, which showed me many cool packages (e.g., igraph) in R which provides high-quality network analysis in terms of manipulating graphs, mathematical modeling, statistical modeling, etc. The book came with a list of code demos, which can be found here: https://github.com/kolaczyk/sand. This blog is built upon Chapter 2 of the book: Manipulating Network Data, assuming that you already understood the basic concepts of network analysis, such as nodes, edges, etc. However, if you need a comprehensive explanation, I encourage you to read the book. RStudio (or similar IDEs) and “igraph” (an R package, available in CRAN) In case you do not have “igraph” installed: ## Download and install the package install.packages("igraph") ## Load package library(igraph) To manually create a graph, the function “graph.formula” can be used. To make it more understandable for creating directed graphs, I proposed an airport network consisting of three airports: JFK (New York City airport), PEK (Beijing airport), and CDG (Paris airport). Thus, the directed graph that I created can be read: we only have one-way flights from JFK to PEK and CDG (assume some travel restrictions applied); PEK and CDG are mutually connected, and you can fly both ways. To make the blog concise, the rest of the demo will only focus on undirected graphs. For more reference, please visit the book’s GitHub repository. A graph, represented by G = (V, E), is a mathematical structure consisting of a set V of vertices and a set E of edges. The number of vertices and the number of edges in the graph are sometimes called the order and size of graph G (Kolaczyk et al., 2014). You may use V(graph) and E(graph) to check the vertices and edges; use vcount(graph) and ecount(graph) to check the order and size of the graph; use print_all(graph) to show the summary of the graph. You may use the command of plot(graph) to visualize the graph: I made the graph whose vertices were labeled with numbers 1 through N. In practice, you might already have natural labels, such as names. So here is how you could label your vertices and how it would look like: V(g)$name <-c("Adam","Judy","Bobby","Sam","Frank","Jay","Tom","Jerry")plot(g) Normally, the graph will be stored in three basic formats: adjacency lists, edge lists, and adjacency matrix (Kolaczyk et al., 2014). An adjacency list is a collection of unordered lists. Each unordered list describes the set of neighbors of a specific vertex in the graph within an adjacency list. This format is what igraph uses in the graph summary function. An edge list is a two-column table to list all the node pairs in the graph. This format is preferred by NetworkX (in python). The adjacency matrix’s entries show whether two vertices in the graph are connected or not. If there is a link between two nodes, “i and j,” the row-column indices (i, j) will be marked as 1, otherwise 0. Therefore, the adjacency matrix will be symmetric for undirected graphs. Statistical models normally prefer to encode graphs with this format, such as node2vec which requires the adjacency matrix as inputs. You can use the functions of get.adjlist(graph), get.edgelist(graph), and get.adjacency(graph) to get the three different formats, respectively. In practice, we might want to remove certain edges or join graphs to get subgraphs. In this case, the math operators can help you achieve the goal. The graph in (1, 1) is the original graph. The graph in (1, 1) removed two vertices from the original graph. The graph in (2, 1) is made of certain edges (the edges were removed from the original graph due to the removal of vertices). The graph in (2, 2) is the joined graph of (1, 1) and (2, 1), and it has the same structure as (1, 1). In real-world problems, we rarely make graphs manually. Instead, we have to import data. For the best practice to manipulate graphs, we normally need to prepare two data files/data frames. One of the files needs to contain all the attributes for each vertex in the graph. The other file needs to contain the edges in the network (typically an edge list). In the book, the author gave an example of a lawyer dataset of Lazega. The information is stored in two different files: elist.lazega and v.attr.lazega. The original data is available in the sand (Statistical Analysis of Network Data) library. Therefore, here is how you would read your own data: In this blog, I covered the code for creating directed and undirected graphs, visualizing graphs, getting statistics from graphs, labeling vertices, generating different formats of representations, subsetting and joining graphs, and reading your own network data with igraph. NetworkX: Code Demo for Manipulating Subgraphs Analyzing Disease Co-occurrence Using NetworkX, Gephi, and Node2Vec Statistical Analysis of Network Data with R, by Eric D. Kolaczyk and Csárdi Gábor, Springer, 2014, pp. 13–28.
[ { "code": null, "e": 915, "s": 172, "text": "Network analysis is a technique that uses graph theory to study complex real-world problems, such as computational biology, engineering, finance, marketing, neuroscience, political science, and public health (Kolaczyk et al., 2014). In my previous works, ...
Basics of CountVectorizer | by Pratyaksh Jain | Towards Data Science
Machines cannot understand characters and words. So when dealing with text data we need to represent it in numbers to be understood by the machine. Countvectorizer is a method to convert text to numerical data. To show you how it works let’s take an example: text = [‘Hello my name is james, this is my python notebook’] The text is transformed to a sparse matrix as shown below. We have 8 unique words in the text and hence 8 different columns each representing a unique word in the matrix. The row represents the word count. Since the words ‘is’ and ‘my’ were repeated twice we have the count for those particular words as 2 and 1 for the rest. Countvectorizer makes it easy for text data to be used directly in machine learning and deep learning models such as text classification. Let’s take another example, but this time with more than 1 input: text = [‘Hello my name is james' , ’this is my python notebook’] I have 2 text inputs, what happens is that each input is preprocessed, tokenized, and represented as a sparse matrix. By default, Countvectorizer converts the text to lowercase and uses word-level tokenization. Now that we have looked at a few examples lets actually code! We’ll first start by importing the necessary libraries. We’ll use the pandas library to visualize the matrix and the sklearn.feature_extraction.text which is a sklearn library to perform vectorization. import pandas as pdfrom sklearn.feature_extraction.text import CountVectorizertext = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer()count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) Lowercase Convert all characters to lowercase before tokenizing. Default is set to true and takes boolean value. text = [‘hello my name is james’,‘Hello my name is James’]coun_vect = CountVectorizer(lowercase=False)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) Now lets try without using ‘lowercase = False’ text = [‘hello my name is james’,‘Hello my name is James’]coun_vect = CountVectorizer()count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) Stop_words Stopwords are the words in any language which does not add much meaning to a sentence. They can safely be ignored without sacrificing the meaning of the sentence. There are 3 ways of dealing with stopwords: Custom stop words list Custom stop words list text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer(stop_words= [‘is’,’to’,’my’])count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) Sparse matrix after removing the words is , to and my: 2. sklearn built in stop words list text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer(stop_words=’english’)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) 3. Using max_df and min_df (covered later) Max_df: Max_df stands for maximum document frequency. Similar to min_df, we can ignore words which occur frequently. These words could be like the word ‘the’ that occur in every document and does not provide and valuable information to our text classification or any other machine learning model and can be safely ignored. Max_df looks at how many documents contain the word and if it exceeds the max_df threshold then it is eliminated from the sparse matrix. This parameter can again 2 types of values, percentage and absolute. Using absolute values: text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer(max_df=1)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) The words ‘is’, ‘to’, ‘james’, ‘my’ and ‘of’ have been removed from the sparse matrix as they occur in more than 1 document. Using percentage: text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer(max_df=0.75)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) As you can see the word ‘james’ appears in 4 out of 5 documents(85%) and hence crosses the threshold of 75% and removed from the sparse matrix Min_df: Min_df stands for minimum document frequency, as opposed to term frequency which counts the number of times the word has occurred in the entire dataset, document frequency counts the number of documents in the dataset (aka rows or entries) that have the particular word. When building the vocabulary Min_df ignores terms that have a document frequency strictly lower than the given threshold. For example in your dataset you may have names that appear in only 1 or 2 documents, now these could be ignored as they do not provide enough information on the entire dataset as a whole but only a couple of particular documents. min_df can take absolute values(1,2,3..) or a value representing a percentage of documents(0.50, ignore words appearing in 50% of documents) Using absolute values: text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’,‘james of words to try differnt’,‘features of count vectorizer’]coun_vect = CountVectorizer(min_df=2)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) max_features The CountVectorizer will select the words/features/terms which occur the most frequently. It takes absolute values so if you set the ‘max_features = 3’, it will select the 3 most common words in the data. text = [‘This is the first document.’,’This document is the second document.’,’And this is the third one.’, ‘Is this the first document?’,]coun_vect = CountVectorizer(max_features=3)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df)df Binary By setting ‘binary = True’, the CountVectorizer no more takes into consideration the frequency of the term/word. If it occurs it’s set to 1 otherwise 0. By default, binary is set to False. This is usually used when the count of the term/word does not provide useful information to the machine learning model. text = [‘This is the first document. Is this the first document?’ ]coun_vect = CountVectorizer(binary=True)count_matrix = coun_vect.fit_transform(text)count_array = count_matrix.toarray()df = pd.DataFrame(data=count_array,columns = coun_vect.get_feature_names())print(df) Even though all the words occur twice in the above input our sparse matrix just represents it with 1 Now let’s see if we used the default value: Vocabulary They are the collection of words in the sparse matrix. text = [‘hello my name is james’,‘Hello my name is James’]coun_vect = CountVectorizer()count_matrix = coun_vect.fit_transform(text)print(coun_vect.vocabulary_) The numbers do not represent the count of the words but the position of the words in the matrix If you just want the vocabulary without the position of the word in the sparse matrix, you can use the method ‘get_feature_names()’. If you notice this is the same method we use while creating our database and setting our columns. text = [‘Hello my name is james’,‘james this is my python notebook’,‘james trying to create a big dataset’]coun_vect = CountVectorizer()count_matrix = coun_vect.fit_transform(text)print( coun_vect.get_feature_names()) CountVectorizer is just one of the methods to deal with textual data. Td-idf is a better method to vectorize data. I’d recommend you check out the official document of sklearn for more information. Hope this helps :)
[ { "code": null, "e": 431, "s": 172, "text": "Machines cannot understand characters and words. So when dealing with text data we need to represent it in numbers to be understood by the machine. Countvectorizer is a method to convert text to numerical data. To show you how it works let’s take an examp...
Distributed Logging using ELK and Sleuth
In a distributed environment or in a monolithic environment, application logs are very critical for debugging whenever something goes wrong. In this section, we will look at how to effectively log and improve traceability so that we can easily look at the logs. Two major reasons why logging patterns become critical for logging − Inter-service calls − In a microservice architecture, we have async and sync calls between services. It is very critical to link these requests, as there can be more than one level of nesting for a single request. Inter-service calls − In a microservice architecture, we have async and sync calls between services. It is very critical to link these requests, as there can be more than one level of nesting for a single request. Intra-service calls − A single service gets multiple requests and the logs for them can easily get intermingled. That is why, having some ID associated with the request becomes important to filter all the logs for a request. Intra-service calls − A single service gets multiple requests and the logs for them can easily get intermingled. That is why, having some ID associated with the request becomes important to filter all the logs for a request. Sleuth is a well-known tool used for logging in application and ELK is used for simpler observation across the system. Let us use the case of Restaurant that we have been using in every chapter. So, let us say we have our Customer service and the Restaurant service communicating via API, i.e., synchronous communication. And we want to have Sleuth for tracing the request and the ELK stack for centralized visualization. To do that, first setup the ELK stack. To do that, first, we will setup the ELK stack. We will be starting the ELK stack using Docker containers. Here are the images that we can consider − https://github.com/deviantony/docker-elk https://github.com/deviantony/docker-elk https://elk-docker.readthedocs.io/ https://elk-docker.readthedocs.io/ https://hub.docker.com/r/sebp/elk/ https://hub.docker.com/r/sebp/elk/ Once ELK setup has been performed, ensure that it is working as expected by hitting the following APIs − Elasticsearch − localhost:9200 Elasticsearch − localhost:9200 Kibana − localhost:5601 Kibana − localhost:5601 We will look at logstash configuration file at the end of this section. Then, let us add the following dependency to our Customer Service and the Restaurant Service − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> Now that we have the dependency setup and ELK running, let us move to the core example. On a very basic level, following are the metadata that are added by Sleuth − Service name − Service currently processing the request. Service name − Service currently processing the request. Trace Id − A metadata ID is added to the logs which is sent across services for processing an input request. This is useful for inter-service communication for grouping all the internal requests which went in processing one input request. Trace Id − A metadata ID is added to the logs which is sent across services for processing an input request. This is useful for inter-service communication for grouping all the internal requests which went in processing one input request. Span Id − A metadata ID is added to the logs which is same across all log statements which are logged by a service for processing a request. It is useful for intra-service logs. Note that Span ID = Trace Id for the parent service. Span Id − A metadata ID is added to the logs which is same across all log statements which are logged by a service for processing a request. It is useful for intra-service logs. Note that Span ID = Trace Id for the parent service. Let us see this in action. For that, let us update our Customer Service code to contain log lines. Here is the controller code that we would use. package com.tutorialspoint; import java.util.HashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController class RestaurantCustomerInstancesController { Logger logger = LoggerFactory.getLogger(RestaurantCustomerInstancesController.class); static HashMap<Long, Customer> mockCustomerData = new HashMap(); static{ mockCustomerData.put(1L, new Customer(1, "Jane", "DC")); mockCustomerData.put(2L, new Customer(2, "John", "SFO")); mockCustomerData.put(3L, new Customer(3, "Kate", "NY")); } @RequestMapping("/customer/{id}") public Customer getCustomerInfo(@PathVariable("id") Long id) { logger.info("Querying customer with id: " + id); Customer customer = mockCustomerData.get(id); if(customer != null) { logger.info("Found Customer: " + customer); } return customer; } } Now let us execute the code, as always, start the Eureka Server. Note that this is not a hard requirement and is present here for the sake of completeness. Then, let us compile and start updating Customer Service using the following command − mvn clean install ; java -Dapp_port=8083 -jar .\target\spring-cloud-eurekaclient- 1.0.jar And we are set, let us now test our code pieces by hitting the API − curl -X GET http://localhost:8083/customer/1 Here is the output that we will get for this API − { "id": 1, "name": "Jane", "city": "DC" } And now let us check the logs for Customer Service − 2021-03-23 13:46:59.604 INFO [customerservice, b63d4d0c733cc675,b63d4d0c733cc675] 11860 --- [nio-8083-exec-7] .t.RestaurantCustomerInstancesController : Querying customer with id: 1 2021-03-23 13:46:59.605 INFO [customerservice, b63d4d0c733cc675,b63d4d0c733cc675] 11860 --- [nio-8083-exec-7] .t.RestaurantCustomerInstancesController : Found Customer: Customer [id=1, name=Jane, city=DC] ..... So, effectively, as we see, we have the name of the service, trace ID, and the span ID added to our log statements. Let us see how we can do logging and tracing across service. So, for example, what we will do is to use the Restaurant Service which internally calls the Customer Service. For that, let us update our Restaurant Service code to contain log lines. Here is the controller code that we would use. package com.tutorialspoint; import java.util.HashMap; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController class RestaurantController { @Autowired CustomerService customerService; Logger logger = LoggerFactory.getLogger(RestaurantController.class); static HashMap<Long, Restaurant> mockRestaurantData = new HashMap(); static{ mockRestaurantData.put(1L, new Restaurant(1, "Pandas", "DC")); mockRestaurantData.put(2L, new Restaurant(2, "Indies", "SFO")); mockRestaurantData.put(3L, new Restaurant(3, "Little Italy", "DC")); mockRestaurantData.put(4L, new Restaurant(4, "Pizeeria", "NY")); } @RequestMapping("/restaurant/customer/{id}") public List<Restaurant> getRestaurantForCustomer(@PathVariable("id") Long id) { logger.info("Get Customer from Customer Service with customer id: " + id); Customer customer = customerService.getCustomerById(id); logger.info("Found following customer: " + customer); String customerCity = customer.getCity(); return mockRestaurantData.entrySet().stream().filter( entry -> entry.getValue().getCity().equals(customerCity)) .map(entry -> entry.getValue()) .collect(Collectors.toList()); } } Let us compile and start updating Restaurant Service using the following command − mvn clean install; java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client-1.0.jar Ensure that we have the Eureka server and the Customer service running. And we are set, let us now test our code pieces by hitting the API − curl -X GET http://localhost:8082/restaurant/customer/2 Here is the output that we will get for this API − [ { "id": 2, "name": "Indies", "city": "SFO" } ] And now, let us check the logs for Restaurant Service − 2021-03-23 14:44:29.381 INFO [restaurantservice, 6e0c5b2a4fc533f8,6e0c5b2a4fc533f8] 19600 --- [nio-8082-exec-6] com.tutorialspoint.RestaurantController : Get Customer from Customer Service with customer id: 2 2021-03-23 14:44:29.400 INFO [restaurantservice, 6e0c5b2a4fc533f8,6e0c5b2a4fc533f8] 19600 --- [nio-8082-exec-6] com.tutorialspoint.RestaurantController : Found following customer: Customer [id=2, name=John, city=SFO] Then, let us check the logs for Customer Service − 2021-03-23 14:44:29.392 INFO [customerservice, 6e0c5b2a4fc533f8,f2806826ac76d816] 11860 --- [io-8083-exec-10] .t.RestaurantCustomerInstancesController : Querying customer with id: 2 2021-03-23 14:44:29.392 INFO [customerservice, 6e0c5b2a4fc533f8,f2806826ac76d816] 11860 --- [io-8083-exec-10] .t.RestaurantCustomerInstancesController : Found Customer: Customer [id=2, name=John, city=SFO]..... So, effectively, as we see, we have the name of the service, trace ID, and the span ID added to our log statements. Plus, we see the trace Id, i.e., 6e0c5b2a4fc533f8 being repeated in Customer Service and the Restaurant Service. What we have seen till now is a way to improve our logging and tracing capability via Sleuth. However, in microservice architecture, we have multiple services running and multiple instances of each service running. It is not practical to look at the logs of each instance to identify the request flow. And that is where ELK helps us. Let us use the same case of inter-service communication as we did for Sleuth. Let us update our Restaurant and Customer to add logback appenders for the ELK stack. Before moving ahead, please ensure that ELK stack has been setup and Kibana is accessible at localhost:5601. Also, configure the Lostash configuration with the following setup − input { tcp { port => 8089 codec => json } } output { elasticsearch { index => "restaurant" hosts => ["http://localhost:9200"] } } Once this is done, there are two steps we need to do to use logstash in our Spring app. We will perform the following steps for both our services. First, add a dependency for logback to use appender for Logstash. <dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>6.6</version> </dependency> And secondly, add an appender for logback so that the logback can use this appender to send the data to Logstash <?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="logStash" class="net.logstash.logback.appender.LogstashTcpSocketAppender"> <destination>10.24.220.239:8089</destination> <encoder class="net.logstash.logback.encoder.LogstashEncoder" /> </appender> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="logStash" /> <appender-ref ref="console" /> </root> </configuration> The above appender would log to console as well as send the logs to logstash. Now one this is done, we are all set to test this out. Now, let us execute the above code as always, start the Eureka Server. Then, let us compile and start updating Customer Service using the following command − mvn clean install ; java -Dapp_port=8083 -jar .\target\spring-cloud-eurekaclient- 1.0.jar Then, let us compile and start updating Restaurant Service using the following command − mvn clean install; java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client- 1.0.jar And we are set, let us now test our code pieces by hitting the API − curl -X GET http://localhost:8082/restaurant/customer/2 Here is the output that we will get for this API − [ { "id": 2, "name": "Indies", "city": "SFO" } ] But more importantly, the log statements would also be available on Kibana. So, as we see, we can filter for a traceId and see all the log statements across services which were logged to fulfill the request. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2140, "s": 1878, "text": "In a distributed environment or in a monolithic environment, application logs are very critical for debugging whenever something goes wrong. In this section, we will look at how to effectively log and improve traceability so that we can easily look at t...
XML - Encoding
Encoding is the process of converting unicode characters into their equivalent binary representation. When the XML processor reads an XML document, it encodes the document depending on the type of encoding. Hence, we need to specify the type of encoding in the XML declaration. There are mainly two types of encoding − UTF-8 UTF-16 UTF stands for UCS Transformation Format, and UCS itself means Universal Character Set. The number 8 or 16 refers to the number of bits used to represent a character. They are either 8(1 to 4 bytes) or 16(2 or 4 bytes). For the documents without encoding information, UTF-8 is set by default. Encoding type is included in the prolog section of the XML document. The syntax for UTF-8 encoding is as follows − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> The syntax for UTF-16 encoding is as follows − <?xml version = "1.0" encoding = "UTF-16" standalone = "no" ?> Following example shows the declaration of encoding − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <contact-info> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </contact-info> In the above example encoding="UTF-8", specifies that 8-bits are used to represent the characters. To represent 16-bit characters, UTF-16 encoding can be used. The XML files encoded with UTF-8 tend to be smaller in size than those encoded with UTF-16 format. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 1961, "text": "Encoding is the process of converting unicode characters into their equivalent binary representation. When the XML processor reads an XML document, it encodes the document depending on the type of encoding. Hence, we need to specify the type of encoding...
C - Quick Guide
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written in C. C has now become a widely used professional language for various reasons − Easy to learn Structured language It produces efficient programs It can handle low-level activities It can be compiled on a variety of computer platforms C was invented to write an operating system called UNIX. C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around the early 1970s. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute (ANSI). The language was formalized in 1988 by the American National Standard Institute (ANSI). The UNIX OS was totally written in C. The UNIX OS was totally written in C. Today C is the most widely used and popular System Programming Language. Today C is the most widely used and popular System Programming Language. Most of the state-of-the-art software have been implemented using C. Most of the state-of-the-art software have been implemented using C. Today's most popular Linux OS and RDBMS MySQL have been written in C. Today's most popular Linux OS and RDBMS MySQL have been written in C. C was initially used for system development work, particularly the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language. Some examples of the use of C might be − Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Databases Language Interpreters Utilities A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to write your C program into a file. This tutorial assumes that you know how to edit a text file and how to write source code inside a program file. If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler. This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. The name and version of text editors can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX. The files you create with your editor are called the source files and they contain the program source codes. The source files for C programs are typically named with the extension ".c". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The source code written in source file is the human readable source for your program. It needs to be "compiled", into machine language so that your CPU can actually execute the program as per the instructions given. The compiler compiles the source codes into final executable programs. The most frequently used and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective operating systems. The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming languages. If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line − $ gcc -v If you have GNU compiler installed on your machine, then it should print a message as follows − Using built-in specs. Target: i386-redhat-linux Configured with: ../configure --prefix=/usr ....... Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system. If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++. Xcode is currently available at developer.apple.com/technologies/tools/. To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe. While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names. After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line. Before we study the basic building blocks of the C programming language, let us look at a bare minimum C program structure so that we can take it as a reference in the upcoming chapters. A C program basically consists of the following parts − Preprocessor Commands Functions Variables Statements & Expressions Comments Let us look at a simple code that would print the words "Hello World" − #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; } Let us take a look at the various parts of the above program − The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. The next line int main() is the main function where the program execution begins. The next line int main() is the main function where the program execution begins. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. The next line return 0; terminates the main() function and returns the value 0. The next line return 0; terminates the main() function and returns the value 0. Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps − Open a text editor and add the above-mentioned code. Open a text editor and add the above-mentioned code. Save the file as hello.c Save the file as hello.c Open a command prompt and go to the directory where you have saved the file. Open a command prompt and go to the directory where you have saved the file. Type gcc hello.c and press enter to compile your code. Type gcc hello.c and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file. If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file. Now, type a.out to execute your program. Now, type a.out to execute your program. You will see the output "Hello World" printed on the screen. You will see the output "Hello World" printed on the screen. $ gcc hello.c $ ./a.out Hello, World! Make sure the gcc compiler is in your path and that you are running it in the directory containing the source file hello.c. You have seen the basic structure of a C program, so it will be easy to understand other basic building blocks of the C programming language. A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf("Hello, World! \n"); The individual tokens are − printf ( "Hello, World! \n" ) ; In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Given below are two different statements − printf("Hello, World! \n"); return 0; Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below − /* my first program in C */ You cannot have comments within comments and they do not occur within a string or character literals. A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names. A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − int age; there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges; // get the total fruit no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability. Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The types in C can be classified as follows − Basic Types They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types. Enumerated types They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program. The type void The type specifier void indicates that no value is available. Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. The array types and structure types are referred collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see the basic types in the following section, where as other types will be covered in the upcoming chapters. The following table provides the details of standard integer types with their storage sizes and value ranges − To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size of various type on a machine using different constant defined in limits.h header file − #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int main(int argc, char** argv) { printf("CHAR_BIT : %d\n", CHAR_BIT); printf("CHAR_MAX : %d\n", CHAR_MAX); printf("CHAR_MIN : %d\n", CHAR_MIN); printf("INT_MAX : %d\n", INT_MAX); printf("INT_MIN : %d\n", INT_MIN); printf("LONG_MAX : %ld\n", (long) LONG_MAX); printf("LONG_MIN : %ld\n", (long) LONG_MIN); printf("SCHAR_MAX : %d\n", SCHAR_MAX); printf("SCHAR_MIN : %d\n", SCHAR_MIN); printf("SHRT_MAX : %d\n", SHRT_MAX); printf("SHRT_MIN : %d\n", SHRT_MIN); printf("UCHAR_MAX : %d\n", UCHAR_MAX); printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX); printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX); printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX); return 0; } When you compile and execute the above program, it produces the following result on Linux − CHAR_BIT : 8 CHAR_MAX : 127 CHAR_MIN : -128 INT_MAX : 2147483647 INT_MIN : -2147483648 LONG_MAX : 9223372036854775807 LONG_MIN : -9223372036854775808 SCHAR_MAX : 127 SCHAR_MIN : -128 SHRT_MAX : 32767 SHRT_MIN : -32768 UCHAR_MAX : 255 UINT_MAX : 4294967295 ULONG_MAX : 18446744073709551615 USHRT_MAX : 65535 The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision − The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. The following example prints the storage space taken by a float type and its range values − #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int main(int argc, char** argv) { printf("Storage size for float : %d \n", sizeof(float)); printf("FLT_MAX : %g\n", (float) FLT_MAX); printf("FLT_MIN : %g\n", (float) FLT_MIN); printf("-FLT_MAX : %g\n", (float) -FLT_MAX); printf("-FLT_MIN : %g\n", (float) -FLT_MIN); printf("DBL_MAX : %g\n", (double) DBL_MAX); printf("DBL_MIN : %g\n", (double) DBL_MIN); printf("-DBL_MAX : %g\n", (double) -DBL_MAX); printf("Precision value: %d\n", FLT_DIG ); return 0; } When you compile and execute the above program, it produces the following result on Linux − Storage size for float : 4 FLT_MAX : 3.40282e+38 FLT_MIN : 1.17549e-38 -FLT_MAX : -3.40282e+38 -FLT_MIN : -1.17549e-38 DBL_MAX : 1.79769e+308 DBL_MIN : 2.22507e-308 -DBL_MAX : -1.79769e+308 Precision value: 6 The void type specifies that no value is available. It is used in three kinds of situations − Function returns as void There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); Function arguments as void There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, int rand(void); Pointers to void A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type. A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types − char Typically a single octet(one byte). It is an integer type. int The most natural size of integer for the machine. float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type. C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types. A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the value 'x'. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined. A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code. Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − #include <stdio.h> // Variable declaration: extern int a, b; extern int c; extern float f; int main () { /* variable definition: */ int a, b; int c; float f; /* actual initialization */ a = 10; b = 20; c = a + b; printf("value of c : %d \n", c); f = 70.0/3.0; printf("value of f : %f \n", f); return 0; } When the above code is compiled and executed, it produces the following result − value of c : 30 value of f : 23.333334 The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; } There are two kinds of expressions in C − lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements − int g = 20; // valid statement 10 = 20; // invalid statement; would generate compile-time error Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition. An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */ Following are other examples of various types of integer literals − 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing decimal form, you must include the decimal point, the exponent, or both; and while representing exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals − 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t). Here, you have a list of such escape sequence codes − Escape sequence Meaning \\ \ character \' ' character \" " character \? ? character \a Alert or bell \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \ooo Octal number of one to three digits \xhh . . . Hexadecimal number of one or more digits Following is the example to show a few escape sequence characters − #include <stdio.h> int main() { printf("Hello\tWorld\n\n"); return 0; } When the above code is compiled and executed, it produces the following result − Hello World String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using white spaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, \ dear" "hello, " "d" "ear" There are two simple ways in C to define constants − Using #define preprocessor. Using #define preprocessor. Using const keyword. Using const keyword. Given below is the form to use #define preprocessor to define a constant − #define identifier value The following example explains it in detail − #include <stdio.h> #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − value of area : 50 You can use const prefix to declare constants with a specific type as follows − const type variable = value; The following example explains it in detail − #include <stdio.h> int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − value of area : 50 Note that it is a good programming practice to define constants in CAPITALS. A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program − auto register static extern The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables. The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). { register int miles; } The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class. #include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */ main() { while(count--) { func(); } return 0; } /* function definition */ void func( void ) { static int i = 5; /* local static variable */ i++; printf("i is %d and count is %d\n", i, count); } When the above code is compiled and executed, it produces the following result − i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. First File: main.c #include <stdio.h> int count ; extern void write_extern(); main() { count = 5; write_extern(); } Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %d\n", count); } Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program a.out. When this program is executed, it produces the following result − count is 5 An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators We will, in this chapter, look into the way each operator works. The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then − Show Examples The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then − Show Examples Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then − Show Examples Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows − Assume A = 60 and B = 13 in binary format, they will be as follows − A = 0011 1100 B = 0000 1101 ----------------- A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then − Show Examples The following table lists the assignment operators supported by the C language − Show Examples Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language. Show Examples Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Show below is the general form of a typical decision making structure found in most of the programming languages − C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. C programming language provides the following types of decision making statements. An if statement consists of a boolean expression followed by one or more statements. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. You can use one if or else if statement inside another if or else if statement(s). A switch statement allows a variable to be tested for equality against a list of values. You can use one switch statement inside another switch statement(s). We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this − Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages − C programming language provides the following types of loops to handle looping requirements. Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. It is more like a while statement, except that it tests the condition at the end of the loop body. You can use one or more loops inside any other while, for, or do..while loop. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C supports the following control statements. Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Transfers control to the labeled statement. A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty. #include <stdio.h> int main () { for( ; ; ) { printf("This loop will run forever.\n"); } return 0; } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys. A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. 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. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc. The general form of a function definition in C programming language is as follows − return_type function_name( parameter list ) { body of the function } A function definition in C programming consists of a function header and a function body. Here are all the parts of a function − Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that define what the function does. Function Body − The function body contains a collection of statements that define what the function does. Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − return_type function_name( parameter list ); For the above defined function max(), the function declaration is as follows − int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example − #include <stdio.h> /* function declaration */ int max(int num1, int num2); int main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result − Max value is : 200 If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways in which arguments can be passed to a function − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language − Inside a function or a block which is called local variables. Inside a function or a block which is called local variables. Outside of all functions which is called global variables. Outside of all functions which is called global variables. In the definition of function parameters which are called formal parameters. In the definition of function parameters which are called formal parameters. Let us understand what are local and global variables, and formal parameters. Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function. #include <stdio.h> int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; } Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The following program show how global variables are used in a program. #include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; } A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example − #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces the following result − value of g = 10 Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example − #include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0; } /* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; } When the above code is compiled and executed, it produces the following result − value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows − It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory location. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement − double balance[10]; Here balance is a variable array which is sufficient to hold up to 10 double numbers. You can initialize an array in C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array − balance[4] = 50.0; The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above − An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[9]; The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays − #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); } return 0; } When the above code is compiled and executed, it produces the following result − Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer − C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. You can pass to the function a pointer to an array by specifying the array's name without an index. C allows a function to return an array. You can generate a pointer to the first element of an array by simply specifying the array name, without any index. Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined − #include <stdio.h> int main () { int var1; char var2[10]; printf("Address of var1 variable: %x\n", &var1 ); printf("Address of var2 variable: %x\n", &var2 ); return 0; } When the above code is compiled and executed, it produces the following result − Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations − #include <stdio.h> int main () { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("Address of var variable: %x\n", &var ); /* address stored in pointer variable */ printf("Address stored in ip variable: %x\n", ip ); /* access the value using the pointer */ printf("Value of *ip variable: %d\n", *ip ); return 0; } When the above code is compiled and executed, it produces the following result − Address of var variable: bffd8b3c Address stored in ip variable: bffd8b3c Value of *ip variable: 20 It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − #include <stdio.h> int main () { int *ptr = NULL; printf("The value of ptr is : %x\n", ptr ); return 0; } When the above code is compiled and executed, it produces the following result − The value of ptr is 0 In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer, you can use an 'if' statement as follows − if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */ Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer − There are four arithmetic operators that can be used in pointers: ++, --, +, - You can define arrays to hold a number of pointers. C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function. C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well. Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; If you follow the rule of array initialization then you can write the above statement as follows − char greeting[] = "Hello"; Following is the memory presentation of the above defined string in C/C++ − Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string − #include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello C supports a wide range of functions that manipulate null-terminated strings − strcpy(s1, s2); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. The following example uses some of the above-mentioned functions − #include <stdio.h> #include <string.h> int main () { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* copy str1 into str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); /* concatenates str1 and str2 */ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); /* total lenghth of str1 after concatenation */ len = strlen(str1); printf("strlen(str1) : %d\n", len ); return 0; } When the above code is compiled and executed, it produces the following result − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds. Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows − struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure − struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book; To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. The following example shows how to use a structure in a program − #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info */ printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 subject : %s\n", Book1.subject); printf( "Book 1 book_id : %d\n", Book1.book_id); /* print Book2 info */ printf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf( "Book 2 subject : %s\n", Book2.subject); printf( "Book 2 book_id : %d\n", Book2.book_id); return 0; } When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 You can pass a structure as a function argument in the same way as you pass any other variable or pointer. #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; /* function declaration */ void printBook( struct Books book ); int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info */ printBook( Book1 ); /* Print Book2 info */ printBook( Book2 ); return 0; } void printBook( struct Books book ) { printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); } When the above code is compiled and executed, it produces the following result − Book title : C Programming Book author : Nuha Ali Book subject : C Programming Tutorial Book book_id : 6495407 Book title : Telecom Billing Book author : Zara Ali Book subject : Telecom Billing Tutorial Book book_id : 6495700 You can define pointers to structures in the same way as you define pointer to any other variable − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the → operator as follows − struct_pointer->title; Let us re-write the above example using structure pointer. #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; /* function declaration */ void printBook( struct Books *book ); int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info by passing address of Book1 */ printBook( &Book1 ); /* print Book2 info by passing address of Book2 */ printBook( &Book2 ); return 0; } void printBook( struct Books *book ) { printf( "Book title : %s\n", book->title); printf( "Book author : %s\n", book->author); printf( "Book subject : %s\n", book->subject); printf( "Book book_id : %d\n", book->book_id); } When the above code is compiled and executed, it produces the following result − Book title : C Programming Book author : Nuha Ali Book subject : C Programming Tutorial Book book_id : 6495407 Book title : Telecom Billing Book author : Zara Ali Book subject : Telecom Billing Tutorial Book book_id : 6495700 Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples include − Packing several objects into a machine word. e.g. 1 bit flags can be compacted. Packing several objects into a machine word. e.g. 1 bit flags can be compacted. Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers. Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers. C allows us to do this in a structure definition by putting :bit length after the variable. For example − struct packed_struct { unsigned int f1:1; unsigned int f2:1; unsigned int f3:1; unsigned int f4:1; unsigned int type:4; unsigned int my_int:9; } pack; Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int. C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields while others would store the next field in the next word. A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows − union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data having three members i, f, and str − union Data { int i; float f; char str[20]; } data; Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays the total memory size occupied by the above union − #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0; } When the above code is compiled and executed, it produces the following result − Memory size occupied by data : 20 To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use unions in a program − #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); return 0; } When the above code is compiled and executed, it produces the following result − data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions − #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); return 0; } When the above code is compiled and executed, it produces the following result − data.i : 10 data.f : 220.500000 data.str : C Programming Here, all the members are getting printed very well because one member is being used at a time. Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows − struct { unsigned int widthValidated; unsigned int heightValidated; } status; This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of the variables. The C programming language offers a better way to utilize the memory space in such situations. If you are using such variables inside a structure then you can define the width of a variable which tells the C compiler that you are going to use only those number of bytes. For example, the above structure can be re-written as follows − struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status; The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to store the values. If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4 bytes. However as soon as you have 33 variables, it will allocate the next slot of the memory and it will start using 8 bytes. Let us check the following example to understand the concept − #include <stdio.h> #include <string.h> /* define simple structure */ struct { unsigned int widthValidated; unsigned int heightValidated; } status1; /* define a structure with bit fields */ struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2; int main( ) { printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2)); return 0; } When the above code is compiled and executed, it produces the following result − Memory size occupied by status1 : 8 Memory size occupied by status2 : 4 The declaration of a bit-field has the following form inside a structure − struct { type [member_name] : width ; }; The following table describes the variable elements of a bit field − type An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int, or unsigned int. member_name The name of the bit-field. width The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type. The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a width of 3 bits as follows − struct { unsigned int age : 3; } Age; The above structure definition instructs the C compiler that the age variable is going to use only 3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to do so. Let us try the following example − #include <stdio.h> #include <string.h> struct { unsigned int age : 3; } Age; int main( ) { Age.age = 4; printf( "Sizeof( Age ) : %d\n", sizeof(Age) ); printf( "Age.age : %d\n", Age.age ); Age.age = 7; printf( "Age.age : %d\n", Age.age ); Age.age = 8; printf( "Age.age : %d\n", Age.age ); return 0; } When the above code is compiled it will compile with a warning and when executed, it produces the following result − Sizeof( Age ) : 4 Age.age : 4 Age.age : 7 Age.age : 0 The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers − typedef unsigned char BYTE; After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example.. BYTE b1, b2; By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows − typedef unsigned char byte; You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows − #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "Nuha Ali"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); return 0; } When the above code is compiled and executed, it produces the following result − Book title : C Programming Book author : Nuha Ali Book subject : C Programming Tutorial Book book_id : 6495407 #define is a C-directive which is also used to define the aliases for various data types similar to typedef but with the following differences − typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc. typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc. typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor. typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor. The following example shows how to use #define in a program − #include <stdio.h> #define TRUE 1 #define FALSE 0 int main( ) { printf( "Value of TRUE : %d\n", TRUE); printf( "Value of FALSE : %d\n", FALSE); return 0; } When the above code is compiled and executed, it produces the following result − Value of TRUE : 1 Value of FALSE : 0 When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files. C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen. The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen. The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen. The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example − #include <stdio.h> int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows − $./a.out Enter a value : this is test You entered: t The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout. NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want to use fgets(). #include <stdio.h> int main( ) { char str[100]; printf( "Enter a value :"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows − $./a.out Enter a value : this is test You entered: this is test The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided. The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better − #include <stdio.h> int main( ) { char str[100]; int i; printf( "Enter a value :"); scanf("%s %d", str, &i); printf( "\nYou entered: %s %d ", str, i); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows − $./a.out Enter a value : seven 7 You entered: seven 7 Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf(). The last chapter explained the standard input and output devices handled by C programming language. This chapter cover how C programmers can create, open, close text or binary files for their data storage. A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management. You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows − FILE *fopen( const char * filename, const char * mode ); Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values − r Opens an existing text file for reading purpose. w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. r+ Opens a text file for both reading and writing. w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones − "rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b" To close a file, use the fclose( ) function. The prototype of this function is − int fclose( FILE *fp ); The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h. There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string. Following is the simplest function to write individual characters to a stream − int fputc( int c, FILE *fp ); The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream − int fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example. Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine. #include <stdio.h> main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); } When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section. Given below is the simplest function to read a single character from a file − int fgetc( FILE * fp ); The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream − char *fgets( char *buf, int n, FILE *fp ); The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character. #include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %s\n", buff ); fclose(fp); } When the above code is compiled and executed, it reads the file created in the previous section and produces the following result − 1 : This 2: is testing for fprintf... 3: This is testing for fputs... Let's see a little more in detail about what happened here. First, fscanf() read just This because after that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely. There are two functions, that can be used for binary input and output − size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Both of these functions should be used to read or write blocks of memories - usually arrays or structures. The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP. All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives − #define Substitutes a preprocessor macro. #include Inserts a particular header from another file. #undef Undefines a preprocessor macro. #ifdef Returns true if this macro is defined. #ifndef Returns true if this macro is not defined. #if Tests if a compile time condition is true. #else The alternative for #if. #elif #else and #if in one statement. #endif Ends preprocessor conditional. #error Prints error message on stderr. #pragma Issues special commands to the compiler, using a standardized method. Analyze the following examples to understand various directives. #define MAX_ARRAY_LENGTH 20 This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability. #include <stdio.h> #include "myheader.h" These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file. #undef FILE_SIZE #define FILE_SIZE 42 It tells the CPP to undefine existing FILE_SIZE and define it as 42. #ifndef MESSAGE #define MESSAGE "You wish!" #endif It tells the CPP to define MESSAGE only if MESSAGE isn't already defined. #ifdef DEBUG /* Your debugging statements here */ #endif It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation. ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified. __DATE__ The current date as a character literal in "MMM DD YYYY" format. __TIME__ The current time as a character literal in "HH:MM:SS" format. __FILE__ This contains the current filename as a string literal. __LINE__ This contains the current line number as a decimal constant. __STDC__ Defined as 1 when the compiler complies with the ANSI standard. Let's try the following example − #include <stdio.h> int main() { printf("File :%s\n", __FILE__ ); printf("Date :%s\n", __DATE__ ); printf("Time :%s\n", __TIME__ ); printf("Line :%d\n", __LINE__ ); printf("ANSI :%d\n", __STDC__ ); } When the above code in a file test.c is compiled and executed, it produces the following result − File :test.c Date :Jun 2 2012 Time :03:36:24 Line :8 ANSI :1 The C preprocessor offers the following operators to help create macros − A macro is normally confined to a single line. The macro continuation operator (\) is used to continue a macro that is too long for a single line. For example − #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example − #include <stdio.h> #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") int main(void) { message_for(Carole, Debra); return 0; } When the above code is compiled and executed, it produces the following result − Carole and Debra: We love you! The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example − #include <stdio.h> #define tokenpaster(n) printf ("token" #n " = %d", token##n) int main(void) { int token34 = 40; tokenpaster(34); return 0; } When the above code is compiled and executed, it produces the following result − token34 = 40 It happened so because this example results in the following actual output from the preprocessor − printf ("token34 = %d", token34); This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting. The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows − #include <stdio.h> #if !defined (MESSAGE) #define MESSAGE "You wish!" #endif int main(void) { printf("Here is the message: %s\n", MESSAGE); return 0; } When the above code is compiled and executed, it produces the following result − Here is the message: You wish! One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows − int square(int x) { return x * x; } We can rewrite above the code using a macro as follows − #define square(x) ((x) * (x)) Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example − #include <stdio.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) int main(void) { printf("Max between 20 and 10 is %d\n", MAX(10, 20)); return 0; } When the above code is compiled and executed, it produces the following result − Max between 20 and 10 is 20 A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler. You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler. Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program. A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required. Both the user and the system header files are included using the preprocessing directive #include. It has the following two forms − #include <file> This form is used for system header files. It searches for a file named 'file' in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code. #include "file" This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code. The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current source file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the #include directive. For example, if you have a header file header.h as follows − char *test (void); and a main program called program.c that uses the header file, like this − int x; #include "header.h" int main (void) { puts (test ()); } the compiler will see the same token stream as it would if program.c read. int x; char *test (void); int main (void) { puts (test ()); } If a header file happens to be included twice, the compiler will process its contents twice and it will result in an error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this − #ifndef HEADER_FILE #define HEADER_FILE the entire header file file #endif This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice. Sometimes it is necessary to select one of the several different header files to be included into your program. For instance, they might specify configuration parameters to be used on different sorts of operating systems. You could do this with a series of conditionals as follows − #if SYSTEM_1 # include "system_1.h" #elif SYSTEM_2 # include "system_2.h" #elif SYSTEM_3 ... #endif But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of #include, you simply put a macro name there − #define SYSTEM_H "system_1.h" ... #include SYSTEM_H SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D option. Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows − (type_name) expression Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation − #include <stdio.h> main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %f\n", mean ); } When the above code is compiled and executed, it produces the following result − Value of mean : 3.400000 It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value. Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary. Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character with an integer − #include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; printf("Value of sum : %d\n", sum ); } When the above code is compiled and executed, it produces the following result − Value of sum : 116 Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of 'c' to ASCII before performing the actual addition operation. The usual arithmetic conversions are implicitly performed to cast their values to a common type. The compiler first performs integer promotion; if the operands still have different types, then they are converted to the type that appears highest in the following hierarchy − The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take the following example to understand the concept − #include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ float sum; sum = i + c; printf("Value of sum : %f\n", sum ); } When the above code is compiled and executed, it produces the following result − Value of sum : 116.000000 Here, it is simple to understand that first c gets converted to integer, but as the final value is double, usual arithmetic conversion applies and the compiler converts i and c into 'float' and adds them yielding a 'float' result. As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during any function call. You can find various error codes defined in <error.h> header file. So a C programmer can check the returned values and can take appropriate action depending on the return value. It is a good practice, to set errno to 0 at the time of initializing a program. A value of 0 indicates that there is no error in the program. The C programming language provides perror() and strerror() functions which can be used to display the text message associated with errno. The perror() function displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value. The perror() function displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value. The strerror() function, which returns a pointer to the textual representation of the current errno value. The strerror() function, which returns a pointer to the textual representation of the current errno value. Let's try to simulate an error condition and try to open a file which does not exist. Here I'm using both the functions to show the usage, but you can use one or more ways of printing your errors. Second important point to note is that you should use stderr file stream to output all the errors. #include <stdio.h> #include <errno.h> #include <string.h> extern int errno ; int main () { FILE * pf; int errnum; pf = fopen ("unexist.txt", "rb"); if (pf == NULL) { errnum = errno; fprintf(stderr, "Value of errno: %d\n", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %s\n", strerror( errnum )); } else { fclose (pf); } return 0; } When the above code is compiled and executed, it produces the following result − Value of errno: 2 Error printed by perror: No such file or directory Error opening file: No such file or directory It is a common problem that at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error. The code below fixes this by checking if the divisor is zero before dividing − #include <stdio.h> #include <stdlib.h> main() { int dividend = 20; int divisor = 0; int quotient; if( divisor == 0){ fprintf(stderr, "Division by zero! Exiting...\n"); exit(-1); } quotient = dividend / divisor; fprintf(stderr, "Value of quotient : %d\n", quotient ); exit(0); } When the above code is compiled and executed, it produces the following result − Division by zero! Exiting... It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming out after a successful operation. Here, EXIT_SUCCESS is a macro and it is defined as 0. If you have an error condition in your program and you are coming out then you should exit with a status EXIT_FAILURE which is defined as -1. So let's write above program as follows − #include <stdio.h> #include <stdlib.h> main() { int dividend = 20; int divisor = 5; int quotient; if( divisor == 0) { fprintf(stderr, "Division by zero! Exiting...\n"); exit(EXIT_FAILURE); } quotient = dividend / divisor; fprintf(stderr, "Value of quotient : %d\n", quotient ); exit(EXIT_SUCCESS); } When the above code is compiled and executed, it produces the following result − Value of quotient : 4 Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc. The following example calculates the factorial of a given number using a recursive function − #include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; } When the above code is compiled and executed, it produces the following result − Factorial of 12 is 479001600 The following example generates the Fibonacci series for a given number using a recursive function − #include <stdio.h> int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i)); } return 0; } When the above code is compiled and executed, it produces the following result − 0 1 1 2 3 5 8 13 21 34 Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function. int func(int, ... ) { . . . } int main() { func(1, 2, 3); func(1, 2, 3, 4); } It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments and follow the given steps − Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Create a va_list type variable in the function definition. This type is defined in stdarg.h header file. Create a va_list type variable in the function definition. This type is defined in stdarg.h header file. Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use va_arg macro and va_list variable to access each item in argument list. Use va_arg macro and va_list variable to access each item in argument list. Use a macro va_end to clean up the memory assigned to va_list variable. Use a macro va_end to clean up the memory assigned to va_list variable. Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average − #include <stdio.h> #include <stdarg.h> double average(int num,...) { va_list valist; double sum = 0.0; int i; /* initialize valist for num number of arguments */ va_start(valist, num); /* access all the arguments assigned to valist */ for (i = 0; i < num; i++) { sum += va_arg(valist, int); } /* clean memory reserved for valist */ va_end(valist); return sum/num; } int main() { printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5)); printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15)); } When the above code is compiled and executed, it produces the following result. It should be noted that the function average() has been called twice and each time the first argument represents the total number of variable arguments being passed. Only ellipses will be used to pass variable number of arguments. Average of 2, 3, 4, 5 = 3.500000 Average of 5, 10, 15 = 10.000000 This chapter explains dynamic memory management in C. The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file. void *calloc(int num, int size); This function allocates an array of num elements each of which size in bytes will be size. void free(void *address); This function releases a block of memory block specified by address. void *malloc(size_t size); This function allocates an array of num bytes and leave them uninitialized. void *realloc(void *address, int newsize); This function re-allocates memory extending it upto newsize. While programming, if you are aware of the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go up to a maximum of 100 characters, so you can define something as follows − char name[100]; But now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory as shown in the below example − #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Zara Ali"); /* allocate memory dynamically */ description = malloc( 200 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Zara ali a DPS student in class 10th"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); } When the above code is compiled and executed, it produces the following result. Name = Zara Ali Description: Zara ali a DPS student in class 10th Same program can be written using calloc(); only thing is you need to replace malloc with calloc as follows − calloc(200, sizeof(char)); So you have complete control and you can pass any size value while allocating memory, unlike arrays where once the size defined, you cannot change it. When your program comes out, operating system automatically release all the memory allocated by your program but as a good practice when you are not in need of memory anymore then you should release that memory by calling the function free(). Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc(). Let us check the above program once again and make use of realloc() and free() functions − #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Zara Ali"); /* allocate memory dynamically */ description = malloc( 30 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Zara ali a DPS student."); } /* suppose you want to store bigger description */ description = realloc( description, 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcat( description, "She is in class 10th"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); /* release memory using free() function */ free(description); } When the above code is compiled and executed, it produces the following result. Name = Zara Ali Description: Zara ali a DPS student.She is in class 10th You can try the above example without re-allocating extra memory, and strcat() function will give an error due to lack of available memory in description. It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly − #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } When the above code is compiled and executed with single argument, it produces the following result. $./a.out testing The argument supplied is testing When the above code is compiled and executed with a two arguments, it produces the following result. $./a.out testing1 testing2 Too many arguments supplied. When the above code is compiled and executed without passing any argument, it produces the following result. $./a.out One argument expected It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2. You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes − #include <stdio.h> int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result. $./a.out "testing1 testing2" Progranm name ./a.out The argument supplied is testing1 testing2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2301, "s": 2084, "text": "C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972." }, { "code": null, "e":...
Objective-C Environment Setup
If you are still willing to set up your own environment for Objective-C programming language, then you need to install Text Editor and The GCC Compiler on your computer. This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Objective-C programs are typically named with the extension ".m". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The source code written in source file is the human readable source for your program. It needs to be "compiled" to turn into machine language, so that your CPU can actually execute the program as per instructions given. This GCC compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler. GCC compiler is available for free on various platforms and the procedure to set up on various platforms is explained below. The initial step is install gcc along with gcc Objective-C package. This is done by − $ su - $ yum install gcc $ yum install gcc-objc The next step is to set up package dependencies using following command − $ yum install make libpng libpng-devel libtiff libtiff-devel libobjc libxml2 libxml2-devel libX11-devel libXt-devel libjpeg libjpeg-devel In order to get full features of Objective-C, download and install GNUStep. This can be done by downloading the package from http://main.gnustep.org/resources/downloads.php. Now, we need to switch to the downloaded folder and unpack the file by − $ tar xvfz gnustep-startup-.tar.gz Now, we need to switch to the folder gnustep-startup that gets created using − $ cd gnustep-startup-<version> Next, we need to configure the build process − $ ./configure Then, we can build by − $ make We need to finally set up the environment by − $ . /usr/GNUstep/System/Library/Makefiles/GNUstep.sh We have a helloWorld.m Objective-C as follows − #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@"hello world"); [pool drain]; return 0; } Now, we can compile and run a Objective-C file say helloWorld.m by switching to folder containing the file using cd and then using the following steps − $ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/Local/Library/Libraries -lgnustep-base helloWorld.m -o helloWorld $ ./helloWorld We can see the following output − 2013-09-07 10:48:39.772 tutorialsPoint[12906] hello world If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode set up, you will be able to use GNU compiler for C/C++. Xcode is currently available at developer.apple.com/technologies/tools/. In order to run Objective-C program on windows, we need to install MinGW and GNUStep Core. Both are available at https://www.gnu.org/software/gnustep/windows/installer.html. First, we need to install the MSYS/MinGW System package. Then, we need to install the GNUstep Core package. Both of which provide a windows installer, which is self-explanatory. Then to use Objective-C and GNUstep by selecting Start -> All Programs -> GNUstep -> Shell Switch to the folder containing helloWorld.m We can compile the program by using − $ gcc `gnustep-config --objc-flags` -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc We can run the program by using − ./hello.exe We get the following output − 2013-09-07 10:48:39.772 tutorialsPoint[1200] hello world 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2730, "s": 2560, "text": "If you are still willing to set up your own environment for Objective-C programming language, then you need to install Text Editor and The GCC Compiler on your computer." }, { "code": null, "e": 2874, "s": 2730, "text": "This will be...
How to remove notification from notification bar programmatically in android?
This example demonstrate about How to remove notification from notification bar programmatically in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width = "match_parent" android :layout_height = "match_parent" tools :context = ".MainActivity" > <Button android :onClick = "createNotification" android :layout_width = "match_parent" android :layout_height = "wrap_content" android :layout_centerInParent = "true" android :layout_margin = "16dp" android :text = "Create notification" /> </RelativeLayout> Step 3 − Add the following code to res/layout/custom_notification_layout.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android :id = "@+id/layout" android :layout_width = "fill_parent" android :layout_height = "96dp" android :padding = "10dp" > <ImageView android :id = "@+id/image" android :layout_width = "wrap_content" android :layout_height = "fill_parent" android :layout_alignParentStart = "true" android :layout_marginEnd = "10dp" android :contentDescription = "@string/app_name" android :src = "@mipmap/ic_launcher" /> <TextView android :id = "@+id/title" android :layout_width = "wrap_content" android :layout_height = "wrap_content" android :layout_toEndOf = "@id/image" android :text = "Testing" android :textColor = "#000" android :textSize = "18sp" /> <TextView android :layout_width = "match_parent" android :layout_height = "wrap_content" android :layout_below = "@+id/title" android :layout_marginTop = "8dp" android :layout_toEndOf = "@+id/image" android :hint = "Thi is just testing notification" android :inputType = "text" android :textSize = "14sp" /> </RelativeLayout> Step 4 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.os.Bundle ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import android.widget.RemoteViews ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; onNewIntent(getIntent()) ; } NotificationManager mNotificationManager ; int notificationId = 0 ; public void createNotification (View view) { RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ; mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ; mBuilder.setContent(contentView) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager .createNotificationChannel(notificationChannel) ; } notificationId = ( int ) System. currentTimeMillis () ; assert mNotificationManager != null; mNotificationManager .notify( notificationId , mBuilder.build()) ; } public void removeNotification (View view) { if ( notificationId != 0 ) mNotificationManager .cancel( notificationId ) ; } } Step 5 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <application android :allowBackup = "true" android :icon = "@mipmap/ic_launcher" android :label = "@string/app_name" android :roundIcon = "@mipmap/ic_launcher_round" android :supportsRtl = "true" android :theme = "@style/AppTheme" > <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1170, "s": 1062, "text": "This example demonstrate about How to remove notification from notification bar programmatically in android" }, { "code": null, "e": 1299, "s": 1170, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project ...
Image Similarity: Theory and Code | by Adam Mehdi | Towards Data Science
How could we compute how similar one image is to another? For similarity among data in a vectorized form, we can find the sum of the squared differences between two examples, or use similar methods like cosine similarity. However, performing such techniques on images — summing the squared difference between each pixel value — fails, since the information in images lie in the interaction between pixels. We would have to first extract the meaningful features out of the images into a vectorized form if we were to proceed. But how do we extract features out of unstructured data like images? To do so with words, we use learnable embeddings — feature vectors containing the meaning of particular words. We use vectors to represent the meaning in words, and we can do something similar with images. A CNN can be trained to map images to vectors, and we can use those vectors as we would word embeddings. This is a central task of the developing field of zero-shot learning; however, this project takes a different, more end-to-end approach. I propose a compound deep learning pipeline as an explainable heuristic for automatically predicting similarity between images. To do so, I used the Oxford PETS dataset. This pipeline is probably similar to that of facial recognition technologies, although I am unfamiliar with those approaches. In this article, I walk through each step of my project, from classification of pet breeds to finding similarity with the Siamese model and interpreting predictions with class activation maps (CAMs). The code is written using PyTorch and fastai. I will conclude by discussing potential applications of this heuristic as a crude clustering algorithm for minimally labelled datasets and matching similar patients for medical prognosis. Here is the original project’s notebook. I suggest working through the notebook as you read through the following commentary since I omit some details for brevity. And, if you wish to read this article in a cleaner format, I recommend reading it from my own website. Let’s begin where we can get a clear view of the whole project: at the end. The SimilarityFinder class is my modularized version of the inference pipeline, and once we understand its three methods, we will have grokked the essence of the project. SimilarityFinder strings together two models, a classifier that predicts the breed of a pet and a comparison (Siamese) model that determines whether two images are similar. We use them to predict the image in our comparison image files that is most similar to the input image. class SimilarityFinder: def __init__(self, classifier_learner, siamese_learner, files): def predict(self, fn, compare_n=15): def similar_cams(self): In __init__ we preprocess the image files that we are using for comparison into lbl2files, a useful mapping for predict, and initialize our two Learners. A Learner is a fastai class that wraps the model, data, and a few other training components into a single class, so we can think of them as the two parts of our pipeline. def label_func(fname): """extracts the pet breed from a file name""" return re.match(r'^(.+)_\d+.jpg$', fname.name).groups()[0]class SimilarityFinder: def __init__(self, classifier_learner, siamese_learner, files): self.clearn,self.slearn = classifier_learner,siamese_learner labels = L(map(label_func, files)).unique() self.lbl2files = {l:[f for f in files if label_func(f)==l] for l in labels} The classifier Learner will serve as a heuristic for reducing the amount of images we have to sift through in predicting similarity. The Siamese Learner predicts similarity between two images. Together, they will allow us to find the most similar image in a sizeable dataset. Let’s continue by looking at how we built those two Learners. We predict the pet breed from images of pets. This is a standard classification problem, so it should seem trivial to those familiar with CNNs. There are three basic steps: Extract the image files from a directory. The PETS dataset is available by default in the fastai library, so we use untar_data to access it. Extract the image files from a directory. The PETS dataset is available by default in the fastai library, so we use untar_data to access it. path = untar_data(URLs.PETS)files = get_image_files(path/"images") 2. Preprocess the image files and store them in DataLoaders with fastai’s Data Block API. cdls = DataBlock(blocks = (ImageBlock, CategoryBlock), get_items = get_image_files, get_y = using_attr(RegexLabeller(r'(.+)_\d+.jpg$'),'name', splitter = RandomSplitter(), item_tfms = Resize(224), batch_tfms = aug_transforms()).dataloaders(path/'images') 3. Wrap everything in a fastai Learner and train the model. I used a couple tricks for training (label smoothing, mixed-precision training) in the project, but I omit them here for simplicity. They are available in the original notebook. clearn = cnn_learner(cdls, resnet34, metrics=accuracy) clearn.fit_one_cycle(n_epochs, lr) The classification pipeline is complete; let’s move on to the more complicated comparison pipeline. We trained a model to predict pet breed. Now, we train use a model that predicts whether two images are of the same breed. It will require defining some custom data types and a custom model, as it is not a standard application. The following implementation is drawn from the Siamese tutorial on the fastai documentation, but I made modicications on the model and training process. Implementing the Siamese model is very similar to implementing the classifier; however, there are two key modifications. We input two images into the model instead of one. This means that, firstly, we need to represent our DataLoaders with three elements per example–first image, second image, and whether they are similar–and, secondly, we pass each image individually through the same body and concatenate the outputs of the body in the head. Exactly as before, retrieve the image files. Exactly as before, retrieve the image files. path = untar_data(URLs.PETS)files = get_image_files(path/"images") 2. Preprocess the data with fastai’s mid-level API. We create a Transform that opens files, pairs them with others, and outputs it as a SiameseImage, which is essentially a container used to display the data. Then, we apply the necessary transforms on all files with TfmdLists and dataloaders. class SiameseTransform(Transform): def __init__(self, files, splits): """setup files into train and valid sets""" def encodes(self, f): """applies transforms on f and pairs it with another image""" f2,same = self.valid.get(f, self._draw(f)) im1,im2 = PILImage.create(f),PILImage.create(f2) return SiameseImage(im1,im2,int(same)) def _draw(self, f, splits=0): """retrieve a file--same class as f with probability 0.5"""splits = RandomSplitter(seed=23)(files)tfm = SiameseTransform(files, splits)tls = TfmdLists(files, tfm, splits=splits)sdls = tls.dataloaders(after_item=[Resize(224), ToTensor], after_batch=[IntToFloatTensor, Normalize.from_stats(*imagenet_stats)]) 3. Build the Model. We pass each image in the pair through the body (aka encoder), concatenate the outputs, and pass them through the head to get the prediction. Note that there is only one encoder for both images, not two encoders for each image. Then, we download some pretrained weights and assemble them together into a model. class SiameseModel(Module): def __init__(self, encoder, head): self.encoder,self.head = encoder,head def forward(self, x1, x2): ftrs = torch.cat([self.encoder(x1), self.encoder(x2)], dim=1) return self.head(ftrs)encoder = create_body(resnet34, cut=-2)head = create_head(512*2, 2, ps=0.5)smodel = SiameseModel(encoder, head) 4. Create the Learner and train the model. We deal with little wrinkles in Learner: specify the location of the body and head with siamese_splitter and cast the target as a float in loss_func. Note that after we customized the data and model, everything else falls into place, and we can proceed training in the standard way. slearn = Learner(sdls, smodel, loss_func=loss_func, splitter=siamese_splitter, metrics=accuracy)slearn.fit_one_cycle(n_epochs, lr) We use the capability of determining shared breed as a heuristic for image similarity. I use the probability that the two pets are of the same breed as a proxy for similarity: if the model is 95% confident that two pets are of the same breed, they are taken to be more similar than if the model predicts with 80% confidence. Now, let’s return to the heart of the project, SimilarityFinder, in which we string these capabilities together. This is the most complex method in the project, so I’ll break it down bit by bit. The gist is as follows: input an image file, predict its class, search through a repository of images of that same class, record activations of the body with a hook (for similar_cams), and output the most similar image. class SimilarityFinder: def predict(self, fn, compare_n=15): self.preds,self.acts,self.images,self.fns = [],[],[],[] # 1. predict breed of input image cls = predict_class(fn,self.clearn) # 2. retrieve a list of same-class images for comparison compare_fns = self.lbl2files[cls][:compare_n] # 3. register a hook to record activations of the body hook_layer = self.slearn.model.encoder with Hook(hook_layer) as hook: for f2 in compare_fns: # 4. preprocess image files for comparison and predict similarity im1,im2 = PILImage.create(fn),PILImage.create(f2) ims = SiameseImage(im1,im2) output = slearn.siampredict(ims)[0][1] # 5. record state and outputs self.preds.append(torch.sigmoid(output)) self.fns.append((fn,f2)) self.images.append((im1,im2)) self.acts.append(hook.stored) hook.reset() # 6. retrieve most similar image and show it with original self.idx = np.array(self.preds).argmax() sim_ims = self.images[self.idx] title = f'{self.preds[self.idx].item()*100:.2f}% Similarity' SiameseImage(sim_ims[0], sim_ims[1], title).show() return self.fns[self.idx][1] Predict breed of input image. predict_class does preprocessing on an image file and outputs the predicted class using the classifier model. Predict breed of input image. predict_class does preprocessing on an image file and outputs the predicted class using the classifier model. def predict_class(fn,learn): im = first(learn.dls.test_dl([fn,]))[0].cpu() with torch.no_grad(): output = learn.model.eval().cpu()(im) return learn.dls.vocab[output.argmax()] 2. Retrieve a list of same-class images for comparison. I am using predicted class as a heuristic to reduce the amount of images we must search through to retrieve the most similar. compare_n specifies the amount of images we would search through, so if case we want speedy results, we would reduce compare_n. If compare_n is 20, calling predict takes about one second. 3. Register a hook to record activations of the body. Hooks are pieces of code that we inject into PyTorch models if we want them to perform additional functionality. They work well with context managers (with blocks) because we must remove the hook after using it. Here, I used the hook to store the final activations of the model’s body so I could implement similar_cams (explained later). class Hook(): def __init__(self, m): self.hook = m.register_forward_hook(self.hook_func) self.stored = [] def hook_func(self,m,i,o): self.stored.append(o.detach().cpu()) def reset(self): self.stored = [] def __enter__(self,*args,**kwargs): return self def __exit__(self,*args,**kwargs): self.hook.remove() 4. Preprocess image files for comparison and predict similarity. SiameseImage is a modified tuple used to group and show our images. The siampredict method is a version of Learner.predict with modified defaults to deal with some wrinkles with the custom model. 5. Record some statistics. 6. Retrieve the image pair with the greatest predicted probability of similarity, taking them to be the most similar of the images considered. Show the images side-by-side with SiameseImage.show and output the file name of the most similar image. That is the primary functionality of the pipeline, but, if implemented as such, we would not know why the images were considered the “most similar”. In other words, it would be useful if we could determine the image features that the model utilized to make the prediction. Lest the model predicts two images to be similar due to extraneous factors (i.e. similar backgrounds), I added a CAM functionality. Class activation maps are grids that show the places on the original image that most contribute to the output. We create one by matrix multiplying the activations of the model’s body (called a spatial map) with a matrix containing the gradient of the output. Here, I used the weight matrix of the final layer of the model as the gradients, as the derivative of the output with respect to the input of the final layer is the final layer’s weights. Intuitively, the spatial map shows the prominence of the features in each position of the image, and the gradient matrix connects each feature with the output, showing the extent to which each feature was used. The result is an illustration of how each position in the image contributed to the output. class SimilarityFinder: def similar_cams(self): # 1. grab the final weights and spatial maps of the most similar images sweight = self.slearn.model.head[-1].weight.cpu() act1,act2 = self.acts[self.idx] # 2. matrix multiply the weights and spatial maps cam_map1 = torch.einsum('ik,kjl->ijl', sweight, act1[0]) cam_map2 = torch.einsum('ik,kjl->ijl', sweight, act2[0]) # 3. open the most similar images to show them f1,f2 = self.fns[self.idx] t1,t2 = to_tensor(f1,slearn.dls),to_tensor(f2,slearn.dls) # 4. show the CAMs overlain on the images _,axs = plt.subplots(ncols=2) show_cam(t1,cam_map1,axs[0]) show_cam(t2,cam_map2,axs[1]) Grab the final weights of the Siamese model as well as the spatial maps of the most similar images, which we recorded with the hook in predict.Perform the dot product between the weights and spatial maps with torch.einsum (a method of custom matrix multiplications).Open the files predicted to be the most similar in predict, and convert them into preprocessed tensors that we will be able to show.Overlay the CAMs on the original images and show them side-by-side. Grab the final weights of the Siamese model as well as the spatial maps of the most similar images, which we recorded with the hook in predict. Perform the dot product between the weights and spatial maps with torch.einsum (a method of custom matrix multiplications). Open the files predicted to be the most similar in predict, and convert them into preprocessed tensors that we will be able to show. Overlay the CAMs on the original images and show them side-by-side. def show_cam(t, cam_map, ctx): show_image(t, ctx=ctx) ctx.imshow(cam_map[0].detach().cpu(), extent[0, t.shape[2], t.shape[1],0], alpha=.7, interpolation='BILINEAR', cmap='magma') In this project, we predicted the most similar pet and then interpreted that prediction with CAMs. To conclude, I will attempt to more precisely define “most similar” and explain why this nuanced definition holds practical consequences. The central insight in this project is that we can use a Siamese model’s confidence in a prediction as a proxy for image similarity. However, “image similarity” in this context does not mean similarity in images as a whole. Rather, it refers to how obviously two images share the features that distinguish a target class. When using the SimilarityFinder, then, the classes with which we label our images affect which image is predicted to be the most similar. For instance, if we differentiate pets with breed as we did here, the SimilarityFinder might predict that two dogs sharing, say, the pointed nose that is distinctive of their breed, are most similar even if their other traits differ considerably. By contrast, if we are to distinguish pets based on another class, such as whether they are cute or not, the model might consider similar floppy ears more in its prediction than a pointed nose, since floppy ears would contribute more to cuteness. Thus, SimilarityFinder overemphasizes the features that are most important to determining the class on which it is trained. This variability in predicted image similarity based on training label is a useful feature of SimilarityFinder if we are to apply it to more practical problems. For instance, SimilarityFinder would be a useful heuristic for finding the similarity between CT scans of pneumonia patients, as that similarity measure would help evaluating treatment options. To illustrate, if we can find the past patient with the most similar case of pneumonia and they responded well to their treatment, say, Cleocin, it is plausible that Cleocin would be a good treatment option for the present patient. We would determine the similarity of the cases from the CT scan images, but we do not want the model to predict similarity due to extraneous factors such as bone structure or scan quality; we want the similarity to be based on the progression and nature of the disease. Hence, it is useful to determine the features that will contribute to the prediction by specifying class label (e.g. severity and type of pneumonia) and to confirm that appropriate features were utilized by analyzing our CAMs. The purpose of this project was to implement an algorithm that can compute similarity on unstructured image data. SimilarityFinder serves as an interpretable heuristic to fulfill that purpose. For now, I am interested in applying that heuristic to medical contexts, providing extra data for such clinical tasks as matching pairs for interpretation of randomized control trials. More to come in subsequent posts. Deep Learning for Coders with Fastai and PyTorchfastai documentationgrad-CAM paper Deep Learning for Coders with Fastai and PyTorch
[ { "code": null, "e": 1214, "s": 172, "text": "How could we compute how similar one image is to another? For similarity among data in a vectorized form, we can find the sum of the squared differences between two examples, or use similar methods like cosine similarity. However, performing such techniq...
Python String isspace() Method
Python string method isspace() checks whether the string consists of whitespace. Following is the syntax for isspace() method − str.isspace() NA NA This method returns true if there are only whitespace characters in the string and there is at least one character, false otherwise. The following example shows the usage of isspace() method. #!/usr/bin/python str = " "; print str.isspace() str = "This is string example....wow!!!"; print str.isspace() When we run above program, it produces following result − True False 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
[ { "code": null, "e": 2326, "s": 2244, "text": "Python string method isspace() checks whether the string consists of whitespace." }, { "code": null, "e": 2373, "s": 2326, "text": "Following is the syntax for isspace() method −" }, { "code": null, "e": 2388, "s": 2...
How do I do a case insensitive string comparison in Python?
The following code is an example of case insensitive string comparison in Python. string1 = 'Star Wars' string2 = 'star wars' if string1.lower() == string2.lower(): print "The strings are case insensitive" else: print "The strings are not case insensitive" This code gives the following output The strings are case insensitive
[ { "code": null, "e": 1144, "s": 1062, "text": "The following code is an example of case insensitive string comparison in Python." }, { "code": null, "e": 1327, "s": 1144, "text": "string1 = 'Star Wars'\nstring2 = 'star wars'\nif string1.lower() == string2.lower():\n print \"Th...
Matplotlib - Lasso Selector Widget - GeeksforGeeks
23 Feb, 2021 Matplotlib provides us with a variety of widgets. In this article, we will be learning about Lasso Selector Widget Demo. A Lasso Selector Widget is a tool that helps us to make a selection curve of arbitrary space. We will be adding the axes manually to our plot and then use the lasso-selector-widget tool. Implementation: Python3 # importing matplotlib packageimport matplotlib.pyplot as plt # importing LassoSelector from# Matplotlib.widgetsfrom matplotlib.widgets import LassoSelector # Creating a figure of the plotfig = plt.figure() # Add set of axes to figure(Manually)# left, bottom, width, height (ranging in between 0 and 1)axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Set the label of X-Axisaxes.set_xlabel('X-axis') # Set the label of Y-Axisaxes.set_ylabel('Y-Axis') # Set the title of the plotaxes.set_title('LassoSelector-Demo-Widget') # OnSelect function:Gets triggered# as soon as the mouse is pressed# in the plotdef onSelect(geeksforgeeks): print(geeksforgeeks) # line defines the color, width and opacity# of the line to be drawnline = {'color': 'green', 'linewidth': 8, 'alpha': 1} # Three parameters are passed inside the lasso# Selector class defining the axis, line# property and on select functionlsso = LassoSelector(ax=axes, onselect=onSelect, lineprops=line, button=2) # Show the above plotplt.show() Output: Explanation: In the above code, we are importing matplotlib package to our python project along with the LassoSelector tool from the matplotlib.widgets module. After importing the packages, we are creating a figure(i.e an empty canvas) and adding axes to it manually. Then, we are defining a function onSelect() that gets triggered as soon as the mouse is pressed in the plot. Then, we are creating line that defines the properties of the line, and then comes LassoSelector which helps us to draw inside the plots. Now inside LassoSelector there are four parameters, the first one defines the axes that we have created, the second one defines the onSelect() function, the third parameter is defining the properties of the line(line) and the last parameter defines which click of the mouse will be used to draw the plot(left, right, middle). Here, Instead of manually adding axes, we can also do it using plt.subplots which automatically creates axes. Python3 # importing matplotlib packageimport matplotlib.pyplot as plt # importing LassoSelector from# Matplotlib.widgetsfrom matplotlib.widgets import LassoSelector # Creating a Subplot in matplotlibfig, axes = plt.subplots() # Set the label of X-Axisaxes.set_xlabel('X-axis') # Set the label of Y-Axisaxes.set_ylabel('Y-Axis') # Set the title of the plotaxes.set_title( 'LassoSelector-Demo-Widget with axes created automatically with subplots') # onSelect function gets triggered# as soon as the mouse is pressed# in the plotdef onSelect(geeksforgeeks): print(geeksforgeeks) # line defines the color, width and opacity# of the line to be drawnline = {'color': 'green', 'linewidth': 8, 'alpha': 1} # Three parameters are passed inside the lasso# Selector class defining the axis, line# property and on select functionlsso = LassoSelector(ax=axes, onselect=onSelect, lineprops=line, button=2) # If you want to print x and y while pressing# and releasing mouse, then use mpl_connect# and replace pressed and released with event # Shows the above plotplt.show() Output: Explanation: The same series of events are taking place just like our previous approach. The only difference is that here we are automatically creating axes with the help of plt.subplots(). If you go through the terminal, you can see a large number of coordinates which are the points on which we have drawn in the graph. Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? 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 Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n23 Feb, 2021" }, { "code": null, "e": 24116, "s": 23901, "text": "Matplotlib provides us with a variety of widgets. In this article, we will be learning about Lasso Selector Widget Demo. A Lasso Selector Widget is a tool that hel...
Can we call Superclass’s static method from subclass in Java?
A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name. Live Demo public class Sample{ public static void display(){ System.out.println("This is the static method........"); } public static void main(String args[]){ Sample.display(); } } This is the static method........ It also works, if you call a static method using an instance. But, it is not recommended. Live Demo public class Sample{ public static void display(){ System.out.println("This is the static method........"); } public static void main(String args[]){ new Sample().display(); } } This is the static method........ If you compile the above program in eclipse you will get a warning as − The static method display() from the type Sample should be accessed in a static way You can call the static method of the superclass − Using the constructor of the superclass. new SuperClass().display(); Directly, using the name of the superclass. SuperClass.display(); Directly, using the name of the subclass. SubClass.display(); Following Java example calls the static method of the superclass in all the 3 possible ways − Live Demo class SuperClass{ public static void display() { System.out.println("This is a static method of the superclass"); } } public class SubClass extends SuperClass{ public static void main(String args[]){ //Calling static method of the superclass new SuperClass().display(); //superclass constructor SuperClass.display(); //superclass name SubClass.display(); //subclass name } } This is a static method of the superclass This is a static method of the superclass This is a static method of the superclass
[ { "code": null, "e": 1243, "s": 1062, "text": "A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name." }, { "code": null, "e": 1254, "s": 1243, "text": " ...
Implementing Part of Speech Tagging for English Words Using Viterbi Algorithm from Scratch | by Cleopatra Douglas | Towards Data Science
The complete code for this article can be found HERE Part of speech tagging is the process of assigning a part of speech to each word in a text, this is a disambiguation task and words can have more than one possible part of speech and our goal is to find the correct tag for the situation. We will use a classic sequence labeling algorithm, the Hidden Markov Model to demonstrate, sequence labeling is a task in which we assign to each word x1 in an input word sequence, a label y1, so the output sequence Y has the same length as the input sequence X. An HMM is a probabilistic sequence model based on augmenting the Markov chain. A Markov chain makes a very strong assumption that if we want to predict the future in the sequence, all that matters is the current state. For example, predicting the probability that I write an article next week depends on me writing an article this week and no more. You can watch the video HERE for more examples and I would say a more detailed explanation. The Hidden Markov Model allows us to talk about observed events — words that we see in the put and hidden events — part of speech tags that we think of as casual factors in our probabilistic model. We will be implementing our tagger using the Brown Corpus where each file contains sentences of tokenized words followed by POS tags and where each line contains a sentence. You can find the manual for our data describing the tags HERE. Note we will implement our POS tagger using a bigram HMM. We can see a sample of our data below: [('RB', 'manifestly'), ('VB', 'admit')] First, let's create a function for generating n-grams. def ngrams(self, text, n): n_grams = [] for i in range(len(text)): n_grams.append(tuple(text[i: i + n])) return n_grams An HMM has two components that transition probabilities A and emission probabilities B. The transition probabilities are the probability of a tag occurring given the previous tag, for example, a verb will is most likely to be followed by another form of a verb like dance, so it will have a high probability. We can calculate this probability using the equation above, implemented below: Here we are dividing the count of the bigram by its unigram count for each bigram we create and store it in a transition_probabilities dictionary. The emission probabilities are the probability given a tag that it will be associated with a given word. We can calculate this probability using the equation above, implemented below: Here we are dividing the count of the tag followed by that word by a count of the same tag and storing it in an emission_probabilities dictionary. HMM taggers make two further simplifying assumptions. The first is that the probability of a word appearing depends only on its own tag and is independent of neighboring words and tags, second assumption, the bigram assumption, is that the probability of a tag is dependent only on the previous tag, rather than the entire tag sequence. Plugging the two assumptions results in the following equation for the most probable tag sequence from our bigram tagger: For any model, such as an HMM that contains hidden variables — the parts of speech, the task of determining the sequence of the hidden variable corresponding to the sequence of observations is called decoding, and this is done using the Viterbi algorithm. The Viterbi algorithm is a dynamic programming algorithm for obtaining the maximum a posteriori probability estimate of the most likely sequence of hidden states — called the Viterbi path — that results in a sequence of observed events, especially in the context of Markov information sources and hidden Markov models (HMM). Also, a good explanatory video can be found HERE Viterbi decoding efficiently determines the most probable path from the exponentially many possibilities. It finds the highest probability given for a word against all our tags by looking through our transmission and emission probabilities, multiplying the probabilities, and then finding the max probability. We will define a default value of 0.0000000000001 for unknown probabilities. We will start by calculating our initial probabilities / the start probability for that state, this is the probability that the word started the sentence, in our case we used a “START” token def initial_probabilities(self, tag): return self.transition_probabilities["START", tag] To test our solution we will use a sentence already broken into words, as below: test_sent = ["We", "have", "learned", "much", "about", "interstellar", "drives", "since", "a", "hundred", "years", "ago", "that", "is", "all", "I", "can", "tell", "you", "about", "them", ]cleaned_test_sent = [self.clean(w) for w in test_sent]print(self.vertibi(cleaned_test_sent, all_tags)) Our result i: we,PPSShave,HV-HLlearned,VBNmuch,AP-TLabout,RBinterstellar,JJ-HLdrives,NNSsince,INa,AThundred,CDyears,NNSago,RBthat,CSis,BEZ-NCall,QLi,PPSScan,MDtell,VB-NCyou,PPO-NCabout,RPthem,DTS This is correct based on our documentation. I look forward to hearing feedback or questions.
[ { "code": null, "e": 225, "s": 172, "text": "The complete code for this article can be found HERE" }, { "code": null, "e": 463, "s": 225, "text": "Part of speech tagging is the process of assigning a part of speech to each word in a text, this is a disambiguation task and words c...
How to make a div span two rows in a grid using CSS ? - GeeksforGeeks
15 Oct, 2020 Suppose we have 5 elements in a row and the task to put a bigger element in the middle of a row. How to make a DIV span the 2 rows of the grid with the help of CSS. Approach 1: First get the height of the outer DIV of ID(‘outer’). We know the height of the outer element now design can be achieved using CSS Flexbox with flex-direction: column and flex-wrap: wrap. fixed height on the container tells the flex items where to wrap. Example: <!DOCTYPE HTML><html> <head> <style> #outer { display: flex; flex-direction: column; flex-wrap: wrap; height: 120px; width: 516px; } .div { width: 90px; flex: 0 0 50px; margin: 5px; background-color: green; } .big { flex-basis: 110px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> How to make a div span two rows in a grid using CSS </p> <div id="outer"> <div class="div"></div> <div class="div"></div> <div class="div big"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> </div></body> </html> Output: Approach 2: Make a block-level outer DIV. Create a 90px width column of grid and do it 5 times. Rows will be created automatically. The properties like. grip-gap is shorthand for grid-row-gap and grid-column-gap are used. The large item will be span from row lines 1 to 3 The large item will be span from grid column lines 2 to 3. Example: <!DOCTYPE HTML><html> <head> <style> #outer { display: grid; grid-template-columns: repeat(5, 90px); grid-auto-rows: 50px; grid-gap: 10px; width: 516px; } .big { grid-row: 1 / 3; grid-column: 2 / 3; } .div { background-color: green; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> How to make a div span two rows in a grid using CSS </p> <div id="outer"> <div class="div"></div> <div class="div"></div> <div class="div big"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? How to set div width to fit content using CSS ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 23779, "s": 23751, "text": "\n15 Oct, 2020" }, { "code": null, "e": 23944, "s": 23779, "text": "Suppose we have 5 elements in a row and the task to put a bigger element in the middle of a row. How to make a DIV span the 2 rows of the grid with the help of CSS...
Data Visualization using Plotnine and ggplot2 in Python - GeeksforGeeks
29 Dec, 2021 Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze the trends or patterns that may be present in the data as it summarizes the huge amount of data in a simple and easy-to-understand format. In this article, we will discuss how to visualize data using plotnine in Python which is a strict implementation of the grammar of graphics. Before starting let’s understand a brief about what is the grammar of graphics. A grammar of graphics is basically a tool that enables us to describe the components of a given graphic. Basically, this allows us to see beyond the named graphics, (scatter plot, to name one) and to basically see the underlying statistics behind it. Consider grammar of graphics as the grammar of English where we use different words, tenses, punctuations to form a sentence. Typically, to build or describe any visualization with one or more dimensions, we can use the components shown in the below image. First, we will see the three main components that are required to create a plot, and without these components, the plotnine would not be able to plot the graph. These are- Data is the dataset that is used for plotting the plot. Aesthetics (aes) is the mapping between the data variables and the variables used by the plot such as x-axis, y-axis, color, fill, size, labels, alpha, shape, line width, line type. Geometric Objects (geoms) is the type of plot or a geometric object that we want to use such as point, line, histogram, bar, boxplot, etc. There are various optional components that can make the plot more meaningful and presentable. These are – Facets allow the data to be divided into groups and each group is plotted separately. Statistical transformations compute the data before plotting it. Coordinates define the position of the object in a 2D plane. Themes define the presentation of the data such as font, color, etc. The plotnine is based on ggplot2 in R Programming language which is used to implement grammar of graphics in Python. To install plotnine type the below command in the terminal. pip install plotnine Here we will use the three main components i.e. data, aesthetics, and geometric objects for plotting our data. Let’s go through each component in detail. The data is the dataset which is needed to be plotted. We can specify the data using the ggplot constructor and passing the dataset to that constructor. We will use the Iris dataset and will read it using Pandas. Python3 import pandas as pdfrom plotnine import ggplot # reading datasetdf = pandas.read_csv("Iris.csv") # passing the data to the ggplot # constructorggplot(df) Output: This will give us a blank output as we have not specified the other two main components. Now let’s define the variable that we want to use for each axis in the plot. Aesthetics maps data variables to graphical attributes, like 2D position and color. Python3 import pandas as pdfrom plotnine import ggplot, aes # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="Species", y="SepalLengthCm") Output: In the above example, we can see that Species is shown on the x-axis and sepal length is shown on the y-axis. But still there is no figure in the plot. This can be added using geometric objects. After defining the data and the aesthetics we need to define the type of plot that we want for visualization. This tells the plotline that how the data points should be shown. It provides a variety of geometric objects like scatter plots, line charts, bar charts, box plots, etc. Let’s see a variety of them and how to use them. Note: For the list of all the geoms refer to the plotnine’s geom API reference. Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_col # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_col() Output: In the above example, we have used the geam_col() geom that is a bar plot with the base on the x-axis. We can change this to different types of geoms that we find suitable for our plot. Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_histogram # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="SepalLengthCm") + geom_histogram() Output: Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_point # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_point() Output: Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_boxplot # reading datasetdf = pd.read_csv("Iris.csv") # passing the data to the ggplot # constructorggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_boxplot() Output: Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_line # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_line() Output: Till now we have learnt about how to create a basic chart using the concept of grammar of graphics and it’s three main components. Now let’s learn how to customize these charts using the other optional components. Here we will learn about the remaining optional components. These components are – Facets Statistical transformations Coordinates Themes Facets are used to plot subsets of data. it allows an individual plot for groups of data in the same image. For example, let’s consider the tips dataset that contains information about people who probably had food at a restaurant and whether or not they left a tip, their age, gender and so on. Lets have a look at it. Note: To download the dataset used, click here. Now let’s suppose we want to plot about what was the total bill according to the gender and on each day. In such cases facets can be very useful, let’s see how. Python3 import pandas as pdfrom plotnine import ggplot, aes, facet_grid, labs, geom_col # reading datasetdf = pd.read_csv("tips.csv") ( ggplot(df) + facet_grid(facets="~sex") + aes(x="day", y="total_bill") + labs( x="day", y="total_bill", ) + geom_col()) Output: Statistical transformations means computing data before plotting it. It can be seen in the case of a histogram. Now let’s consider the above example, where we wanted to find the measurement of the sepal length column and now we want to distribute that measurement into 15 columns. The geom_histogram() function of the plotnine computes and plot this data automatically. Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_histogram # reading datasetdf = pd.read_csv("Iris.csv") ggplot(df) + aes(x="SepalLengthCm") + geom_histogram(bins=15) Output: The coordinates system defines the imappinof the data point with the 2D graphical location on the plot. Let’s see the above example of histogram, we want to plot this histogram horizontally. We can simply do this by using the coord_flip() function. Python3 import pandas as pdfrom plotnine import ggplot, aes, geom_histogram, coord_flip # reading datasetdf = pd.read_csv("Iris.csv") ( ggplot(df) + aes(x="SepalLengthCm") + geom_histogram(bins=15) + coord_flip()) Output: Themes are used for improving the looks of the data visualization. Plotnine includes a lot of theme which can be found in the plotnine’s themes API. Let’s use the above example with facets and try to make the visualization more interactive. Python3 import pandas as pdfrom plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd # reading datasetdf = pd.read_csv("tips.csv") ( ggplot(df) + facet_grid(facets="~sex") + aes(x="day", y="total_bill") + labs( x="day", y="total_bill", ) + geom_col() + theme_xkcd()) Output: We can also fill the color according to add more information to this graph. We can add color for the time variable in the above graph using the fill parameter of the aes function. Till now we have seen how to plot more than 2 variables in the case of facets. Now let’s suppose we want to plot data using four variables, doing this with facets can be a little bit of hectic, but with using the color we can plot 4 variables in the same plot only. We can fill the color using the fill parameter of the aes() function. Python3 import pandas as pdfrom plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd # reading datasetdf = pd.read_csv("tips.csv") ( ggplot(df) + facet_grid(facets="~sex") + aes(x="day", y="total_bill", fill="time") + labs( x="day", y="total_bill", ) + geom_col() + theme_xkcd()) Output: We can simply save the plot using the save() method. This method will esport the plot as an image. Python3 import pandas as pdfrom plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd # reading datasetdf = pd.read_csv("tips.csv") plot = ( ggplot(df) + facet_grid(facets="~sex") + aes(x="day", y="total_bill", fill="time") + labs( x="day", y="total_bill", ) + geom_col() + theme_xkcd()) plot.save("gfg plotnine tutorial.png") Output: Data Visualization 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()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n29 Dec, 2021" }, { "code": null, "e": 24594, "s": 24292, "text": "Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze t...
Creating a new table in SAP HANA
New tables can be created using the two methods given below − Using SQL editor Using GUI option The new table can be created using SQL Create Table statement – Create column Table Test1 ( ID INTEGER, NAME VARCHAR(10), PRIMARY KEY (ID) ); When you run this SQL query, you get a message like this: The statement 'Create column Table Test1 ( ID INTEGER, NAME VARCHAR(10), PRIMARY KEY (ID) )' successfully executed in 5 ms 136 μs (server processing time: 4 ms 432 μs) - Rows Affected: 0 To create a table using GUI, you need to right-click on any schema name -> New Table It will open a window to enter the Table name, Choose Schema name from the drop-down, Define Table type from the drop-down list: Column Store or Row Store. Define data type as shown below. Columns can be added by clicking on the + sign, Primary Key can be chosen by clicking on the cell under Primary key in front of the Column name, Not Null will be active by default. Once columns are added, click on Execute.
[ { "code": null, "e": 1124, "s": 1062, "text": "New tables can be created using the two methods given below −" }, { "code": null, "e": 1141, "s": 1124, "text": "Using SQL editor" }, { "code": null, "e": 1158, "s": 1141, "text": "Using GUI option" }, { "...
Check for balanced parentheses in an expression in C++
Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid. The task is simple; we will use stack to do this. We should follow these steps to get the solution − Traverse through the expression until it has exhaustedif the current character is opening bracket like (, { or [, then push into stackif the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise that is not balanced. if the current character is opening bracket like (, { or [, then push into stack if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise that is not balanced. After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced. Live Demo #include <iostream> #include <stack> using namespace std; bool isBalancedExp(string exp) { stack<char> stk; char x; for (int i=0; i<exp.length(); i++) { if (exp[i]=='('||exp[i]=='['||exp[i]=='{') { stk.push(exp[i]); continue; } if (stk.empty()) return false; switch (exp[i]) { case ')': x = stk.top(); stk.pop(); if (x=='{' || x=='[') return false; break; case '}': x = stk.top(); stk.pop(); if (x=='(' || x=='[') return false; break; case ']': x = stk.top(); stk.pop(); if (x =='(' || x == '{') return false; break; } } return (stk.empty()); } int main() { string expresion = "()[(){()}]"; if (isBalancedExp(expresion)) cout << "This is Balanced Expression"; else cout << "This is Not Balanced Expression"; } This is Balanced Expression
[ { "code": null, "e": 1314, "s": 1062, "text": "Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid." ...
How to generate multiple insert queries via java?
JDBC provides a mechanism known as batch processing, in which you can group a set of INSERT or, UPDATE or, DELETE commands (those produce update count value) and execute them at once. You can insert multiple records in to a table using this. Statement, PreparedStatement and CallableStatement objects hold a list (of commands) to which you can add related statements (those return update count value) using the addBatch() method. stmt.addBatch(insert1); stmt.addBatch(insert2); stmt.addBatch(insert3); After adding the required statements, you can execute a batch using the executeBatch() method of the Statement interface. stmt.executeBatch(); Using batch updates, we can reduce the communication overhead and increase the performance of our Java application. Note: Before adding statements to the batch you need to turn the auto commit off using the con.setAutoCommit(false) and, after executing the batch you need to save the changes using the con.commit() method. Let us create a table with name sales in MySQL database using CREATE statement as shown below − CREATE TABLE sales( Product_Name varchar(255), Name_Of_Customer varchar(255), Month_Of_Dispatch varchar(255), Price int, Location varchar(255) ); Following JDBC program tries to insert a set of statements into the above mentioned table using batch update. import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class BatchUpdates { public static void main(String args[])throws Exception { //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Setting auto-commit false con.setAutoCommit(false); //Statements to insert records String insert1 = "INSERT INTO Dispatches VALUES ('KeyBoard', 'Amith', 'January', 1000, 'Hyderabad')"; String insert2 = "INSERT INTO Dispatches VALUES ('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')"; String insert3 = "INSERT INTO Dispatches VALUES ('Mouse', 'Sudha', 'September', 200, 'Vijayawada')"; //Adding the statements to batch stmt.addBatch(insert1); stmt.addBatch(insert2); stmt.addBatch(insert3); //Executing the batch stmt.executeBatch(); //Saving the changes con.commit(); System.out.println("Records inserted......"); } } Connection established...... Records inserted...... If you verify the contents of the table, you can find the inserted records in it as − +--------------+------------------+-------------------+-------+----------------+ | Product_Name | Name_Of_Customer | Month_Of_Dispatch | Price | Location | +--------------+------------------+-------------------+-------+----------------+ | KeyBoard | Amith | January | 1000 | Hyderabad | | Earphones | SUMITH | March | 500 | Vishakhapatnam | | Mouse | Sudha | September | 200 | Vijayawada | +--------------+------------------+-------------------+-------+----------------+
[ { "code": null, "e": 1304, "s": 1062, "text": "JDBC provides a mechanism known as batch processing, in which you can group a set of INSERT or, UPDATE or, DELETE commands (those produce update count value) and execute them at once. You can insert multiple records in to a table using this." }, { ...
JavaScript | Namespace - GeeksforGeeks
21 Mar, 2020 Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Using namespaces in such a scenario will isolate these contexts such that the same identifier can be used in different namespaces. In this article, we will discuss how namespaces can be initialized and used in JavaScript. JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables. Syntax: To initialise an empty namespace var <namespace> = {}; var <namespace> = {}; To access variables in the namespace <namespace>.<identifier> <namespace>.<identifier> Below example illustrates the namespace in JavaScript: Example: As shown below, the identifier startEngine is used to denote different functions in car and bike objects. In this manner, we can use the same identifier in different namespaces by attaching it to different global objects. <script>var car = { startEngine: function () { console.log("Car started"); } } var bike = { startEngine: function () { console.log("Bike started"); }} car.startEngine();bike.startEngine();</script> Output: Car started Bike started javascript-basics Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24587, "s": 24559, "text": "\n21 Mar, 2020" }, { "code": null, "e": 25231, "s": 24587, "text": "Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. ...
How to use REPLACE() function with column’s data of MySQL table?
For using it with column’s data we need to provide column name as the argument of REPLACE() function. It can be demonstrated by using ‘Student’ table data as follows − mysql> Select Id, Name, Subject, REPLACE(Subject, 's', ' Science') from Student WHERE Subject = 'Computers'; +------+--------+-----------+-----------------------------------+ | Id | Name | Subject | REPLACE(Subject, 's', ' Science') | +------+--------+-----------+-----------------------------------+ | 1 | Gaurav | Computers | Computer Science | | 20 | Gaurav | Computers | Computer Science | +------+--------+-----------+-----------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1230, "s": 1062, "text": "For using it with column’s data we need to provide column name as the argument of REPLACE() function. It can be demonstrated by using ‘Student’ table data as follows −" }, { "code": null, "e": 1760, "s": 1230, "text": "mysql> Select ...
Apply a function to each row or column in Dataframe using pandas.apply() - GeeksforGeeks
19 Jul, 2021 There are different ways to apply a function to each row or column in DataFrame. We will learn about various ways in this post. Let’s create a small dataframe first and see that. Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Create a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Outputdf Output : Method 1: Applying lambda function to each row/column. Example 1: For Column Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Create a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a lambda function to each# column which will add 10 to the valuenew_df = df.apply(lambda x : x + 10) # Outputnew_df Output : Example 2: For Row Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a lambda function to each# row which will add 5 to the valuenew_df = df.apply(lambda x: x + 5, axis = 1) # Outputnew_df Output : Method 2: Applying user defined function to each row/column Example 1: For Column Python3 # function to returns x*xdef squareData(x): return x * x # import pandas and numpy packagesimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a user defined function to# each column that will square the given# valuenew_df = df.apply(squareData) # Outputnew_df Output : Example 2: For Row Python3 # function to returns x*Xdef squareData(x): return x * x # import pandas and numpy libraryimport pandas as pdimport numpy as np # List of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a user defined function# to each row that will square the given valuenew_df = df.apply(squareData, axis = 1) # Outputnew_df Output : In the above examples, we saw how a user defined function is applied to each row and column. We can also apply user defined functions which take two arguments. Example 1: For Column Python3 # function to returns x+ydef addData(x, y): return x + y # import pandas and numpy libraryimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a user defined function to each# column which will add value in each# column by given numbernew_df = df.apply(addData, args = [1]) # Outputprint(new_df) Output: Example 2: For Row Python3 # function to returns x+ydef addData(x, y): return x + y # import pandas and numpy libraryimport pandas as pdimport numpy as np # List of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a user defined function to each# row which will add value in each row by# given numbernew_df = df.apply(addData, axis = 1, args = [3]) # Outputnew_df Output : Method 3: Applying numpy function to each row/column Example 1: For Column Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # list of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a numpy function to each# column by squaring each valuenew_df = df.apply(np.square) # Outputnew_df Output : Example 2: For Row Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # List of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Apply a numpy function to each row# to find square root of each valuenew_df = df.apply(np.sqrt, axis = 1) # Outputnew_df Output : Method 4: Applying a Reducing function to each row/column A Reducing function will take row or column as series and returns either a series of same size as that of input row/column or it will return a single variable depending upon the function we use. Example 1: For Column Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # List of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a numpy function to get the sum# of all values in each columnnew_df = df.apply(np.sum) # Outputnew_df Output : Example 2: For Row Python3 # import pandas and numpy libraryimport pandas as pdimport numpy as np # List of tuplesmatrix = [(1,2,3,4), (5,6,7,8,), (9,10,11,12), (13,14,15,16) ] # Creating a Dataframe objectdf = pd.DataFrame(matrix, columns = list('abcd')) # Applying a numpy function to get t# he sum of all values in each rownew_df = df.apply(np.sum, axis = 1) # Outputnew_df Output : rajeev0719singh Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 25036, "s": 25008, "text": "\n19 Jul, 2021" }, { "code": null, "e": 25216, "s": 25036, "text": "There are different ways to apply a function to each row or column in DataFrame. We will learn about various ways in this post. Let’s create a small dataframe firs...
Adding Text with a Float number Using String.Format() Method in C# - GeeksforGeeks
26 May, 2020 Here the task is to add the text T with a float number F using String.Format() method. Example : Input : F = 12.3, T = “abc”Output : 12abc.abc3 Input : F = 0.0, T = “Geeks”Output : Geeks0.0Geeks The text T can be add to a float number F using String.Format() method in a following way: Add text T only to left of integral part of a float number F. Add text T only to right of integral part of a float number F. Add text T only to left of fractional part of a float number F. Add text T only to right of fractional part of a float number F. Add text T to both side of decimal point of a float number F. Add text T to both side of a float number F. Below is the implementation of the above different ways: Example 1: Adding text T only to left of integral part of a float number F. C# // C# program to add text T // only to left of integral // part of a float number F. using System; public class GFG{ // function to add text at // left of integral part // of a float number. static string Add_text(float F, string T) { // string format string s = "{0:"; s += T; s += "0.0}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; //function calling string str = Add_text(F, T); // print the added text float number Console.WriteLine(str); }} Output: abc12.3 Example 2: Adding text T only to right of integral part of a float number F. C# // C# program to add text T // only to right of integral // part of a float number F. using System; public class GFG{ // function to add text at // right of integral part // of a float number. static string Add_text(float F, string T) { // string format string s = "{0:0"; s += T; s += ".0}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; // function calling string str = Add_text(F, T); // print the added text float number Console.WriteLine(str); }} Output: 12abc.3 Example 3: Adding text T only to left of fractional part of a float number F. C# // C# program to add text T // only to left of fractional // part of a float number F. using System; public class GFG{ // function to add text at // left of fractional part // of a float number F. static string Add_text(float F, string T) { // string format string s = "{0:0."; s += T; s += "0}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; // function calling string str = Add_text(F, T); // print the added text // float number Console.WriteLine(str); }} Output: 12.abc3 Example 4: Adding text T only to right of fractional part of a float number F. C# // C# program to add text T // only to right of fractional // part of a float number F. using System; public class GFG{ // function to add text at // right of fractional part // of a float number F. static string Add_text(float F, string T) { // string format string s = "{0:0.0"; s += T; s += "}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; // function calling string str = Add_text(F, T); // print the added text float number Console.WriteLine(str); }} Output: 12.3abc Example 5: Adding text T to both side of decimal point of a float number F. C# // C# program to add text// to both side of decimal// point of a float number using System; public class GFG{ // function to add text at // both side of decimal // point of a float number static string Add_text(float F, string T) { // string format string s = "{0:0"; s += T; s += "."; s += T; s += "0}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; // function calling string str = Add_text(F, T); // print the added text float number Console.WriteLine(str); }} Output: 12abc.abc3 Example 6: Adding text T to both side of a float number F. C# // C# program to add text// to both side of a float number using System; public class GFG{ // function to add text at // both side of a float number static string Add_text(float F, string T) { // string format string s = "{0:"; s += T; s += "0.0"; s += T; s += "}"; // use of String.Format() method return String.Format(s, F); } // Main Method static void Main(string[] args) { float F = 12.3f; string T = "abc"; // function calling string str = Add_text(F, T); // print the added text float number Console.WriteLine(str); }} Output: abc12.3abc CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n26 May, 2020" }, { "code": null, "e": 25634, "s": 25547, "text": "Here the task is to add the text T with a float number F using String.Format() method." }, { "code": null, "e": 25644, "s": 25634, "text": "Exa...
Node.js fs.exists() Method - GeeksforGeeks
12 Oct, 2021 The fs.exists() method is an inbuilt application programming interface of fs module which provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. The fs.exists() method is used to test whether the given path exists or not in the file system. Syntax: fs.exists( path, callback ) Parameters: This method accept two parameters as mentioned above and described below: path: The path at which directory is to be tested for existence. It can be string, buffer, etc. callback: It is a callback function passed to the exists() method. Return value: It returns boolean values which signifies that the path exists or not. Note: It is now deprecated. Below examples illustrate the use of fs.exists() method in Node.js: Example 1: // Node.js program to demonstrate the // fs.exists() method var fs = require('fs'); // Using fs.exists() methodfs.exists('/etc/passwd', (exists) => { console.log(exists ? 'Found' : 'Not Found!');}); Output: Found Example 2: // Node.js program to demonstrate the // fs.exists() method var fs = require('fs'); // Using fs.exists() methodfs.exists('/etc/geeks', (exists) => { console.log(exists ? 'Found' : 'Not found!');}); Output: Not found! Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/dist/latest-v13.x/docs/api/fs.html#fs_fs_exists_path_callback Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Express.js express.Router() Function Node.js fs.writeFile() Method How to update NPM ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 37176, "s": 37148, "text": "\n12 Oct, 2021" }, { "code": null, "e": 37476, "s": 37176, "text": "The fs.exists() method is an inbuilt application programming interface of fs module which provides an API for interacting with the file system in a manner closely ...
Console.MoveBufferArea Method in C# - GeeksforGeeks
08 Mar, 2019 Console.MoveBufferArea Method is used to move the specified screen area to destination area. Syntax: public static void MoveBufferArea (int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop); Parameters:sourceLeft: The leftmost column of the source area.sourceTop: The topmost row of the source area.sourceWidth: The number of columns in the source area.sourceHeight: The number of rows in the source area.targetLeft: The leftmost column of the destination area.targetTop: The topmost row of the destination area. Exceptions: ArgumentOutOfRangeException:One or more of the parameters is less than zero.If sourceLeft or targetLeft is greater than or equal to BufferWidth.If sourceTop or targetTop is greater than or equal to BufferHeight.If sourceTop + sourceHeight is greater than or equal to BufferHeight.If sourceLeft + sourceWidth is greater than or equal to BufferWidth. One or more of the parameters is less than zero. If sourceLeft or targetLeft is greater than or equal to BufferWidth. If sourceTop or targetTop is greater than or equal to BufferHeight. If sourceTop + sourceHeight is greater than or equal to BufferHeight. If sourceLeft + sourceWidth is greater than or equal to BufferWidth. IOException: If an I/O error occured. Example 1: // C# program to print GeeksForGeeksusing System; namespace GFG { class Program { static void Main(string[] args) { Console.WriteLine("GeeksForGeeks"); }}} Output: Example 2: // C# program to change area// of GeeksForGeeksusing System; namespace GFG { class Program { static void Main(string[] args) { Console.WriteLine("GeeksForGeeks"); // using the method Console.MoveBufferArea(0, 0, Console.BufferWidth, Console.BufferHeight, 10, 10); }}} Output: Note: See the difference of text positions in output images. If the destination and source parameters specify a position located outside the boundaries of the current screen buffer, only the portion of the source area that fits within the destination area is copied. That is, the source area is clipped to fit the current screen buffer. The MoveBufferArea method copies the source area to the destination area. If the destination area does not intersect the source area, the source area is filled with blanks using the current foreground and background colors. Otherwise, the intersected portion of the source area is not filled. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.movebufferarea?view=netframework-4.7.2 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors
[ { "code": null, "e": 26429, "s": 26401, "text": "\n08 Mar, 2019" }, { "code": null, "e": 26522, "s": 26429, "text": "Console.MoveBufferArea Method is used to move the specified screen area to destination area." }, { "code": null, "e": 26663, "s": 26522, "text"...
C++ Program to Implement Dijkstra’s Algorithm Using Set
This is a C++ Program to Implement Dijkstra’s Algorithm using Set. Here we need to have two sets. We generate a shortest path tree with given source node as root. One set contains vertices included in shortest path tree and other set includes vertices not yet included in shortest path tree. At every step, we find a vertex which is in the other set (set of not yet included) and has minimum distance from source. Begin function dijkstra() to find minimum distance: 1) Create a set Set that keeps track of vertices included in shortest path tree, Initially, the set is empty. 2) A distance value is assigned to all vertices in the input graph. Initialize all distance values as INFINITE. Distance value is assigned as 0 for the source vertex so that it is picked first. 3) While Set doesn’t include all vertices a) Pick a vertex u which is not there in the Set and has minimum distance value. b) Include u to Set. c) Distance value is updated of all adjacent vertices of u. For updating the distance values, iterate through all adjacent vertices. if sum of distance value of u (from source) and weight of edge u-v for every adjacent vertex v, is less than the distance value of v, then update the distance value of v. End #include <iostream> #include <climits> #include <set> using namespace std; #define N 5 int minDist(int dist[], bool Set[])//calculate minimum distance { int min = INT_MAX, min_index; for (int v = 0; v < N; v++) if (Set[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } int printSol(int dist[], int n)//print the solution { cout<<"Vertex Distance from Source\n"; for (int i = 0; i < N; i++) cout<<" \t\t \n"<< i<<" \t\t "<<dist[i]; } void dijkstra(int g[N][N], int src) { int dist[N]; bool Set[N]; for (int i = 0; i < N; i++) dist[i] = INT_MAX, Set[i] = false; dist[src] = 0; for (int c = 0; c < N- 1; c++) { int u = minDist(dist, Set); Set[u] = true; for (int v = 0; v < N; v++) if (!Set[v] && g[u][v] && dist[u] != INT_MAX && dist[u] + g[u][v] < dist[v]) dist[v] = dist[u] + g[u][v]; } printSol(dist, N); } int main() { int g[N][N] = { { 0, 4, 0, 0, 0 }, { 4, 0, 7, 0, 0 }, { 0, 8, 0, 9, 0 }, { 0, 0, 7, 0, 6 }, { 0, 2, 0, 9, 0 }}; dijkstra(g, 0); return 0; } Vertex Distance from Source 0 0 1 4 2 11 3 20 4 26
[ { "code": null, "e": 1476, "s": 1062, "text": "This is a C++ Program to Implement Dijkstra’s Algorithm using Set. Here we need to have two sets. We generate a shortest path tree with given source node as root. One set contains vertices included in shortest path tree and other set includes vertices n...
Calculate extra cost to be paid for luggage based on weight for Air travel - GeeksforGeeks
11 Jan, 2022 Given an array weight[] of size N containing weights of luggage. If the weights are within a threshold of W then it does not require any extra cost. But after the weights cross the threshold they need to pay extra cost according to the following table. The task is to calculate the extra cost of the luggage required. Examples: Input: weight[] = {5, 4, 3, 6}, W = 8Output: 0Explanation: No weight crosses the threshold. So no extra cost is incurred. Input: weight[] = {120, 135, 280, 60, 300}, W = 90Output: 1700Explanation: The weight 120 is 30 more than the threshold. So, it requires 100 extra cost.The weight 135 is 45 more than the threshold. So, it requires 100 extra cost.The weight 280 is 190 more than the threshold. So, it requires 500 extra cost.The weight 300 is 210 more than the threshold. So, it requires 1000 extra cost.And the weight 60 is within threshold. So, it requires no cost.The total extra cost is (100 + 100 + 500 + 1000) = 1700 Approach: The approach is based on following observation. If a luggage has weight above threshold W then it incurs extra cost according to the given table. Follow the steps mentioned below to solve the problem: Iterate the array from the start.Check if the current luggage has weight more than W.If it has, then add extra cost according the excess weight following the table given.Else continue iteration. Check if the current luggage has weight more than W.If it has, then add extra cost according the excess weight following the table given.Else continue iteration. If it has, then add extra cost according the excess weight following the table given. Else continue iteration. Return the total extra cost Below is the implementation of the above approach, C++ Java Python C# Javascript // C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the extra costint weighingMachine(int N, int weight[], int W){ int amount = 0; // Loop to calculate the excess cost for (int i = 0; i < N; i++) { if (weight[i] - W > 0 && weight[i] - W <= 50) amount += 100; else if (weight[i] - W > 50 && weight[i] - W <= 100) amount += 200; else if (weight[i] - W > 100 && weight[i] - W <= 150) amount += 300; else if (weight[i] - W > 150 && weight[i] - W <= 200) amount += 500; else if (weight[i] - W > 200) amount += 1000; } return amount;} // Driver codeint main(){ int weight[] = { 120, 135, 280, 60, 300 }; int N = 5; int W = 90; cout << weighingMachine(N, weight, W);} // This code is contributed by Samim Hossain Mondal. // Java code to implement the above approachimport java.util.*; class GFG { // Function to calculate the extra cost static int weighingMachine(int N, int weight[], int W) { int amount = 0; // Loop to calculate the excess cost for (int i = 0; i < N; i++) { if (weight[i] - W > 0 && weight[i] - W <= 50) amount += 100; else if (weight[i] - W > 50 && weight[i] - W <= 100) amount += 200; else if (weight[i] - W > 100 && weight[i] - W <= 150) amount += 300; else if (weight[i] - W > 150 && weight[i] - W <= 200) amount += 500; else if (weight[i] - W > 200) amount += 1000; } return amount; } // Driver code public static void main(String[] args) { int weight[] = { 120, 135, 280, 60, 300 }; int N = 5; int W = 90; System.out.println( weighingMachine(N, weight, W)); }} # Python code to implement the above approach # Function to calculate the extra costdef weighingMachine(N, weight, W): amount = 0; # Loop to calculate the excess cost for i in range(0, N): if (weight[i] - W > 0 and weight[i] - W <= 50): amount = amount + 100 elif (weight[i] - W > 50 and weight[i] - W <= 100): amount = amount + 200 elif (weight[i] - W > 100 and weight[i] - W <= 150): amount = amount + 300 elif (weight[i] - W > 150 and weight[i] - W <= 200): amount = amount + 500; elif (weight[i] - W > 200): amount = amount + 1000 return amount # Driver codeweight = [ 120, 135, 280, 60, 300 ]N = 5W = 90 print(weighingMachine(N, weight, W)) # This code is contributed by Samim Hossain Mondal. // C# code to implement the above approachusing System; public class GFG { // Function to calculate the extra cost static int weighingMachine(int N, int []weight, int W) { int amount = 0; // Loop to calculate the excess cost for (int i = 0; i < N; i++) { if (weight[i] - W > 0 && weight[i] - W <= 50) amount += 100; else if (weight[i] - W > 50 && weight[i] - W <= 100) amount += 200; else if (weight[i] - W > 100 && weight[i] - W <= 150) amount += 300; else if (weight[i] - W > 150 && weight[i] - W <= 200) amount += 500; else if (weight[i] - W > 200) amount += 1000; } return amount; } // Driver code public static void Main(String[] args) { int []weight = { 120, 135, 280, 60, 300 }; int N = 5; int W = 90; Console.WriteLine( weighingMachine(N, weight, W)); }} // This code is contributed by 29AjayKumar <script> // JavaScript code for the above approach // Function to calculate the extra cost function weighingMachine(N, weight, W) { let amount = 0; // Loop to calculate the excess cost for (let i = 0; i < N; i++) { if (weight[i] - W > 0 && weight[i] - W <= 50) amount += 100; else if (weight[i] - W > 50 && weight[i] - W <= 100) amount += 200; else if (weight[i] - W > 100 && weight[i] - W <= 150) amount += 300; else if (weight[i] - W > 150 && weight[i] - W <= 200) amount += 500; else if (weight[i] - W > 200) amount += 1000; } return amount; } // Driver code let weight = [120, 135, 280, 60, 300]; let N = 5; let W = 90; document.write( weighingMachine(N, weight, W)); // This code is contributed by Potta Lokesh </script> 1700 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 shikhasingrajput samim2000 Algo-Geek 2021 Algo Geek Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Lexicographically smallest string formed by concatenating any prefix and its mirrored form Check if the given string is valid English word or not Check if an edge is a part of any Minimum Spanning Tree Find One’s Complement of an Integer | Set 2 Sorting given character Array using Linked List Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 26328, "s": 26300, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26646, "s": 26328, "text": "Given an array weight[] of size N containing weights of luggage. If the weights are within a threshold of W then it does not require any extra cost. But after the ...
Code to generate the map of India (with explanation) - GeeksforGeeks
02 Sep, 2021 Given an obfuscated code that generates the map of India, explain its working.The following code when executed generates the map of India – The above code is a typical example of obfuscated code i.e. code that is difficult for humans to understand.How does it work?Basically, the string is a run-length encoding of the map of India. Alternating characters in the string store how many times to draw space, and how many times to draw an exclamation mark consecutively. Here is an analysis of the different elements of this program –The encoded string "Hello!Welcome to GeeksForGeeks." "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL" "OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; Notice [b+++21] at the end of the encoded string. As b+++21 is equivalent to (b++ + 21) which will evaluate to 31 (10 + 21), the first 31 characters of this string are ignored and do not contribute to anything. The remaining encoded string contains instructions for drawing the map. The individual characters determine how many spaces or exclamation marks to draw consecutively.Outer for loopThis loop goes over the characters in the string. Each iteration increases the value of b by one and assigns the next character in the string to a.Inner for loopThis loop draws individual characters, and a new line whenever it reaches the end of the line. Consider this putchar statement putchar(++c=='Z' ? c = c/9 : 33^b&1); As ‘Z’ represents number 90 in ASCII, 90/9 will give us 10 which is a newline character. Decimal 33 is ASCII for ‘!’. Toggling the low-order bit of 33 gives you 32, which is ASCII for a space. This causes! to be printed if b is odd, and a blank space to be printed if b is even. Below is a less obfuscated version of the above code – C++ C Java Python3 C# PHP // C++ program to print map of India#include <iostream>using namespace std; int main(){ int a = 10, b = 0, c = 10; // The encoded string after removing first 31 characters // Its individual characters determine how many spaces // or exclamation marks to draw consecutively. char* str = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq " "TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL" "OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm " "SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; while (a != 0) { // read each character of encoded string a = str[b++]; while (a-- > 64) { if (++c == 90) // 'Z' is 90 in ascii { // reset c to 10 when the end of line is reached c = 10; // '\n' is 10 in ascii // print newline putchar('\n'); // or putchar(c); } else { // draw the appropriate character // depending on whether b is even or odd if (b % 2 == 0) putchar('!'); else putchar(' '); } } } return 0;} // This code is contributed by SHUBHAMSINGH10. // C program to print map of India#include <stdio.h> int main(){ int a = 10, b = 0, c = 10; // The encoded string after removing first 31 characters // Its individual characters determine how many spaces // or exclamation marks to draw consecutively. char* str = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq " "TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL" "OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm " "SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; while (a != 0) { // read each character of encoded string a = str[b++]; while (a-- > 64) { if (++c == 90) // 'Z' is 90 in ascii { // reset c to 10 when the end of line is reached c = 10; // '\n' is 10 in ascii // print newline putchar('\n'); // or putchar(c); } else { // draw the appropriate character // depending on whether b is even or odd if (b % 2 == 0) putchar('!'); else putchar(' '); } } } return 0;} // Java program to print map of Indiaclass GFG{ public static void main(String[] args) { int a =10, b = 0, c = 10; // The encoded string after removing first 31 characters // Its individual characters determine how many spaces // or exclamation marks to draw consecutively. String s1="TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QP,\n" + "bEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelc,\n" + "lcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; // read each character of encoded string a=s1.charAt(b); while (a != 0) { if (b < 170) { a = s1.charAt(b); b++; while (a-- > 64) { if (++c=='Z') { c/=9; System.out.print((char)(c)); } else System.out.print((char)(33 ^ (b & 0x01))); } } else break; } }} # Python3 program to print map of Indiaa = 10b = 0c = 10 # The encoded string after removing first# 31 characters. Its individual characters# determine how many spaces or exclamation# marks to draw consecutively.s = ("TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs" " UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPe" "HBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFA" "gcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm S" "On TNn ULo0ULo#ULo-WHq!WFs XDt!") # Read each character of encoded stringa = ord(s[b]) while a != 0: if b < 170: a = ord(s[b]) b += 1 while a > 64: a -= 1 c += 1 if c == 90: c = c // 9 print(end = chr(c)) else: print(chr(33 ^ (b & 0X01)), end = '') else: break # The code is contributed by aayush_chouhan // C# program to print map of Indiausing System; class GFG{ public static void Main() { int a = 10, b = 0, c = 10; // The encoded string after removing first 31 characters // Its individual characters determine how many spaces // or exclamation marks to draw consecutively. string s1 = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QP,\n" + "bEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelc,\n" + "lcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; // read each character of encoded string a = s1[b]; while (a != 0) { if (b < 170) { a = s1[b]; b++; while (a-- > 64) { if (++c == 'Z') { c/=9; Console.Write((char)(c)); } else Console.Write((char)(33 ^ (b & 0x01))); } } else break; } }} //This code is contributed by vt_m. <?php// PHP Implementation to// print map of India $a = 10;$b = 0;$c = 10; // The encoded string after removing first 31 characters// Its individual characters determine how many spaces// or exclamation marks to draw consecutively.$s1 = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq ". "TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL". "OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm ". "SOn TNn ULo0ULo#ULo-WHq!WFs XDt!";$a=ord($s1[$b]); while ($a != 0) { if ($b < 170) { $a = ord($s1[$b]); $b++; while ($a-- > 64) { if (++$c==90) { $c=floor($c/9); echo chr($c); } else printf(chr(33 ^ ($b & 0x01))); } } else break; } // note: ord() function convert the// characters into its Ascii value //this code is contributed by mits?> Output: Reference: http://stackoverflow.com/questions/3533348/how-does-this-code-generate-the-map-of-indiaThis article is contributed by Aditya Goel. 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. Mithun Kumar aayush009 SHUBHAMSINGH10 jeevanyasa computer-graphics pattern-printing C Language C++ pattern-printing CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Core Dump (Segmentation fault) in C/C++ fork() in C Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 26321, "s": 26293, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26463, "s": 26321, "text": "Given an obfuscated code that generates the map of India, explain its working.The following code when executed generates the map of India – " }, { "code":...
Alternating split of a given Singly Linked List | Set 1 - GeeksforGeeks
04 Apr, 2022 Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists ‘a’ and ‘b’. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and the other should be 1->1->1. Method 1(Simple) The simplest approach iterates over the source list and pull nodes off the source and alternately put them at the front (or beginning) of ‘a’ and b’. The only strange part is that the nodes will be in the reverse order that occurred in the source list. Method 2 inserts the node at the end by keeping track of the last node in sublists. C++ C Python Javascript /* C++ Program to alternatively splita linked list into two halves */#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next;}; /* pull off the front node ofthe source and put it in dest */void MoveNode(Node** destRef, Node** sourceRef) ; /* Given the source list, split itsnodes into two shorter lists. If we numberthe elements 0, 1, 2, ... then all the evenelements should go in the first list, andall the odd elements in the second. Theelements in the new lists may be in any order. */void AlternatingSplit(Node* source, Node** aRef, Node** bRef){ /* split the nodes of source to these 'a' and 'b' lists */ Node* a = NULL; Node* b = NULL; Node* current = source; while (current != NULL) { MoveNode(&a, ¤t); /* Move a node to list 'a' */ if (current != NULL) { MoveNode(&b, ¤t); /* Move a node to list 'b' */ } } *aRef = a; *bRef = b;} /* Take the node from the front ofthe source, and move it to the frontof the dest. It is an error to callthis with the source list empty. Before calling MoveNode():source == {1, 2, 3}dest == {1, 2, 3} After calling MoveNode():source == {2, 3} dest == {1, 1, 2, 3} */void MoveNode(Node** destRef, Node** sourceRef){ /* the front source node */ Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodesin a given linked list */void printList(Node *node){ while(node!=NULL) { cout<<node->data<<" "; node = node->next; }} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; Node* a = NULL; Node* b = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 0->1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); push(&head, 0); cout<<"Original linked List: "; printList(head); /* Remove duplicates from linked list */ AlternatingSplit(head, &a, &b); cout<<"\nResultant Linked List 'a' : "; printList(a); cout<<"\nResultant Linked List 'b' : "; printList(b); return 0;} // This code is contributed by rathbhupendra /*Program to alternatively split a linked list into two halves */#include<stdio.h>#include<stdlib.h>#include<assert.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* pull off the front node of the source and put it in dest */void MoveNode(struct Node** destRef, struct Node** sourceRef) ; /* Given the source list, split its nodes into two shorter lists. If we number the elements 0, 1, 2, ... then all the even elements should go in the first list, and all the odd elements in the second. The elements in the new lists may be in any order. */void AlternatingSplit(struct Node* source, struct Node** aRef, struct Node** bRef){ /* split the nodes of source to these 'a' and 'b' lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* current = source; while (current != NULL) { MoveNode(&a, ¤t); /* Move a node to list 'a' */ if (current != NULL) { MoveNode(&b, ¤t); /* Move a node to list 'b' */ } } *aRef = a; *bRef = b;} /* Take the node from the front of the source, and move it to the front of the dest. It is an error to call this with the source list empty. Before calling MoveNode(): source == {1, 2, 3} dest == {1, 2, 3} After calling MoveNode(): source == {2, 3} dest == {1, 1, 2, 3} */void MoveNode(struct Node** destRef, struct Node** sourceRef){ /* the front source node */ struct Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the linked list */void push(struct node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while(node!=NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; struct Node* a = NULL; struct Node* b = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 0->1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); push(&head, 0); printf("\n Original linked List: "); printList(head); /* Remove duplicates from linked list */ AlternatingSplit(head, &a, &b); printf("\n Resultant Linked List 'a' "); printList(a); printf("\n Resultant Linked List 'b' "); printList(b); getchar(); return 0;} # Python program to alternatively split# a linked list into two halves # Node classclass Node: def __init__(self, data, next = None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Given the source list, split its # nodes into two shorter lists. If we number # the elements 0, 1, 2, ... then all the even # elements should go in the first list, and # all the odd elements in the second. The # elements in the new lists may be in any order. def AlternatingSplit(self, a, b): first = self.head second = first.next while (first is not None and second is not None and first.next is not None): # Move a node to list 'a' self.MoveNode(a, first) # Move a node to list 'b' self.MoveNode(b, second) first = first.next.next if first is None: break second = first.next # Pull off the front node of the # source and put it in dest def MoveNode(self, dest, node): # Make the new node new_node = Node(node.data) if dest.head is None: dest.head = new_node else: # Link the old dest off the new node new_node.next = dest.head # Move dest to point to the new node dest.head = new_node # UTILITY FUNCTIONS # Function to insert a node at # the beginning of the linked list def push(self, data): # 1 & 2 allocate the Node & # put the data new_node = Node(data) # Make the next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Function to print nodes # in a given linked list def printList(self): temp = self.head while temp: print temp.data, temp = temp.next print("") # Driver Codeif __name__ == "__main__": # Start with empty list llist = LinkedList() a = LinkedList() b = LinkedList() # Created linked list will be # 0->1->2->3->4->5 llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) llist.push(0) llist.AlternatingSplit(a, b) print "Original Linked List: ", llist.printList() print "Resultant Linked List 'a' : ", a.printList() print "Resultant Linked List 'b' : ", b.printList() # This code is contributed by kevalshah5 <script>// JavaScript program to alternatively split// a linked list into two halves // Node classclass Node{ constructor(data,next = null){ this.data = data this.next = next }} class LinkedList{ constructor() { this.head = null } // Given the source list, split its // nodes into two shorter lists. If we number // the elements 0, 1, 2, ... then all the even // elements should go in the first list, and // all the odd elements in the second. The // elements in the new lists may be in any order. AlternatingSplit(a, b){ let first = this.head let second = first.next while (first != null && second != null && first.next != null){ // Move a node to list 'a' this.MoveNode(a, first) // Move a node to list 'b' this.MoveNode(b, second) first = first.next.next if(first == null) break second = first.next } } // Pull off the front node of the // source and put it in dest MoveNode(dest, node){ // Make the new node let new_node = new Node(node.data) if(dest.head == null) dest.head = new_node else{ // Link the old dest off the new node new_node.next = dest.head // Move dest to point to the new node dest.head = new_node } } // UTILITY FUNCTIONS // Function to insert a node at // the beginning of the linked list push(data){ // 1 & 2 allocate the Node & // put the data let new_node = new Node(data) // Make the next of new Node as head new_node.next = this.head // Move the head to point to new Node this.head = new_node } // Function to print nodes // in a given linked list printList(){ let temp = this.head while(temp){ document.write(temp.data," "); temp = temp.next } document.write("</br>") }} // Driver Code // Start with empty listlet llist = new LinkedList()let a = new LinkedList()let b = new LinkedList() // Created linked list will be// 0->1->2->3->4->5llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1)llist.push(0) llist.AlternatingSplit(a, b) document.write("Original Linked List: ");llist.printList() document.write("Resultant Linked List 'a' : ");a.printList() document.write("Resultant Linked List 'b' : ");b.printList() // This code is contributed by shinjanpatra </script> Output: Original linked List: 0 1 2 3 4 5 Resultant Linked List 'a' : 4 2 0 Resultant Linked List 'b' : 5 3 1 Time Complexity: O(n) where n is a number of nodes in the given linked list.Method 2(Using Dummy Nodes) Here is an alternative approach that builds the sub-lists in the same order as the source list. The code uses temporary dummy header nodes for the ‘a’ and ‘b’ lists as they are being built. Each sublist has a “tail” pointer that points to its current last node — that way new nodes can be appended to the end of each list easily. The dummy nodes give the tail pointers something to point to initially. The dummy nodes are efficient in this case because they are temporary and allocated in the stack. Alternately, local “reference pointers” (which always point to the last pointer in the list instead of to the last node) could be used to avoid Dummy nodes. C++ C Java Python3 C# Javascript void AlternatingSplit(Node* source, Node** aRef, Node** bRef){ Node aDummy; /* points to the last node in 'a' */ Node* aTail = &aDummy; Node bDummy; /* points to the last node in 'b' */ Node* bTail = &bDummy; Node* current = source; aDummy.next = NULL; bDummy.next = NULL; while (current != NULL) { MoveNode(&(aTail->next), ¤t); /* add at 'a' tail */ aTail = aTail->next; /* advance the 'a' tail */ if (current != NULL) { MoveNode(&(bTail->next), ¤t); bTail = bTail->next; } } *aRef = aDummy.next; *bRef = bDummy.next;} // This code is contributed// by rathbhupendra void AlternatingSplit(struct Node* source, struct Node** aRef, struct Node** bRef){ struct Node aDummy; struct Node* aTail = &aDummy; /* points to the last node in 'a' */ struct Node bDummy; struct Node* bTail = &bDummy; /* points to the last node in 'b' */ struct Node* current = source; aDummy.next = NULL; bDummy.next = NULL; while (current != NULL) { MoveNode(&(aTail->next), ¤t); /* add at 'a' tail */ aTail = aTail->next; /* advance the 'a' tail */ if (current != NULL) { MoveNode(&(bTail->next), ¤t); bTail = bTail->next; } } *aRef = aDummy.next; *bRef = bDummy.next;} static void AlternatingSplit(Node source, Node aRef, Node bRef){ Node aDummy = new Node(); Node aTail = aDummy; /* points to the last node in 'a' */ Node bDummy = new Node(); Node bTail = bDummy; /* points to the last node in 'b' */ Node current = source; aDummy.next = null; bDummy.next = null; while (current != null) { MoveNode((aTail.next), current); /* add at 'a' tail */ aTail = aTail.next; /* advance the 'a' tail */ if (current != null) { MoveNode((bTail.next), current); bTail = bTail.next; } } aRef = aDummy.next; bRef = bDummy.next;} // This code is contributed by rutvik_56 def AlternatingSplit(source, aRef, bRef): aDummy = Node(); aTail = aDummy; ''' points to the last Node in 'a' ''' bDummy = Node(); bTail = bDummy; ''' points to the last Node in 'b' ''' current = source; aDummy.next = None; bDummy.next = None; while (current != None): MoveNode((aTail.next), current); ''' add at 'a' tail ''' aTail = aTail.next; ''' advance the 'a' tail ''' if (current != None): MoveNode((bTail.next), current); bTail = bTail.next; aRef = aDummy.next; bRef = bDummy.next; # This code is contributed by umadevi9616 static void AlternatingSplit(Node source, Node aRef, Node bRef){ Node aDummy = new Node(); Node aTail = aDummy; /* points to the last node in 'a' */ Node bDummy = new Node(); Node bTail = bDummy; /* points to the last node in 'b' */ Node current = source; aDummy.next = null; bDummy.next = null; while (current != null) { MoveNode((aTail.next), current); /* add at 'a' tail */ aTail = aTail.next; /* advance the 'a' tail */ if (current != null) { MoveNode((bTail.next), current); bTail = bTail.next; } } aRef = aDummy.next; bRef = bDummy.next;} // This code is contributed by pratham_76 <script>function AlternatingSplit( source, aRef, bRef){ var aDummy = new Node(); var aTail = aDummy; /* points to the last node in 'a' */ var bDummy = new Node(); var bTail = bDummy; /* points to the last node in 'b' */ var current = source; aDummy.next = null; bDummy.next = null; while (current != null) { MoveNode((aTail.next), current); /* add at 'a' tail */ aTail = aTail.next; /* advance the 'a' tail */ if (current != null) { MoveNode((bTail.next), current); bTail = bTail.next; } } aRef = aDummy.next; bRef = bDummy.next;} // This code contributed by aashish1995</script> Time Complexity: O(n) where n is number of node in the given linked list.Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdfPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. rathbhupendra nidhi_biet kevalshah5 rutvik_56 pratham76 aashish1995 simranarora5sos umadevi9616 shinjanpatra Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Delete a Linked List node at a given position Implement a stack using singly linked list Queue - Linked List Implementation Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Remove duplicates from a sorted linked list Function to check if a singly linked list is palindrome Top 20 Linked List Interview Question Find Length of a Linked List (Iterative and Recursive) Remove duplicates from an unsorted linked list
[ { "code": null, "e": 25977, "s": 25949, "text": "\n04 Apr, 2022" }, { "code": null, "e": 26287, "s": 25977, "text": "Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists ‘a’ and ‘b’. The sublists should be made from alternatin...
Algorithms | Recursion | Question 6 - GeeksforGeeks
01 Jun, 2021 Output of following program? #include<stdio.h>void print(int n){ if (n > 4000) return; printf("%d ", n); print(2*n); printf("%d ", n);} int main(){ print(1000); getchar(); return 0;} (A) 1000 2000 4000(B) 1000 2000 4000 4000 2000 1000(C) 1000 2000 4000 2000 1000(D) 1000 2000 2000 1000Answer: (B)Explanation: First time n=1000Then 1000 is printed by first printf function then call print(2*1000) then again print 2000 by printf function then call print(2*2000) and it prints 4000 next time print(4000*2) is called. Here 8000 is greater than 4000 condition becomes true and it return at function(2*4000). Here n=4000 then 4000 will again print through second printf. Similarly print(2*2000) after that n=2000 then 2000 will print and come back at print(2*1000) here n=1000, so print 1000 through second printf. Option (B) is correct.Quiz of this Question vivekkumarmth0077 amalchandranmv Algorithms-Recursion Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithms | Graph Traversals | Question 2 Algorithms | Graph Traversals | Question 12 Algorithms | Analysis of Algorithms | Question 17 Algorithms | Graph Traversals | Question 12 Algorithms | Graph Traversals | Question 1 Algorithms | Analysis of Algorithms | Question 8 Algorithms | Sorting | Question 5 Algorithms | Sorting | Question 7 Algorithms | Sorting | Question 1 Algorithms Quiz | Dynamic Programming | Question 8
[ { "code": null, "e": 26235, "s": 26207, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26264, "s": 26235, "text": "Output of following program?" }, { "code": "#include<stdio.h>void print(int n){ if (n > 4000) return; printf(\"%d \", n); print(2*n); pr...
Program to get next integer permutation of a number in C++
Suppose we have a number n, we have to find the next bigger permutation of its digits. When n is already in its largest permutation, then rotate it down to the smallest permutation. So, if the input is like n = 319, then the output will be 391. To solve this, we will follow these steps − Define a function makeArray(), this will take x, Define a function makeArray(), this will take x, Define an array ret Define an array ret while x is non-zero, do −insert x mod 10 at the end of retx := x / 10 while x is non-zero, do − insert x mod 10 at the end of ret insert x mod 10 at the end of ret x := x / 10 x := x / 10 reverse the array ret reverse the array ret return ret return ret Define a function combine(), this will take an array v, Define a function combine(), this will take an array v, ret := 0 ret := 0 for each element i in vret := ret * 10ret := ret + i for each element i in v ret := ret * 10 ret := ret * 10 ret := ret + i ret := ret + i return ret return ret Define a function getIndex(), this will take an array v, Define a function getIndex(), this will take an array v, ret := -1 ret := -1 for initialize i := size of v, when i >= 1, update (decrease i by 1), do −if v[i] > v[i - 1], then −ret := iCome out from the loop for initialize i := size of v, when i >= 1, update (decrease i by 1), do − if v[i] > v[i - 1], then −ret := iCome out from the loop if v[i] > v[i - 1], then − ret := i ret := i Come out from the loop Come out from the loop if ret is not equal to -1, then −x := v[ret - 1]idx := retfor initialize j := ret + 1, when j < size of v, update (increase j by 1), do −if v[j] < v[idx] and v[j] > x, then −idx := jexchange v[ret - 1] and v[idx] if ret is not equal to -1, then − x := v[ret - 1] x := v[ret - 1] idx := ret idx := ret for initialize j := ret + 1, when j < size of v, update (increase j by 1), do −if v[j] < v[idx] and v[j] > x, then −idx := j for initialize j := ret + 1, when j < size of v, update (increase j by 1), do − if v[j] < v[idx] and v[j] > x, then −idx := j if v[j] < v[idx] and v[j] > x, then − idx := j idx := j exchange v[ret - 1] and v[idx] exchange v[ret - 1] and v[idx] return ret return ret From the main method do the following − From the main method do the following − Define an array v := makeArray(num) Define an array v := makeArray(num) idx := getIndex(v) idx := getIndex(v) if idx is same as -1, then −sort the array v if idx is same as -1, then − sort the array v sort the array v Otherwisesort the array v Otherwise sort the array v sort the array v return combine(v) return combine(v) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> makeArray(int x) { vector<int> ret; while (x) { ret.push_back(x % 10); x /= 10; } reverse(ret.begin(), ret.end()); return ret; } int combine(vector<int>& v) { int ret = 0; for (int i : v) { ret *= 10; ret += i; } return ret; } int getIndex(vector& v) { int ret = -1; for (int i = v.size() - 1; i >= 1; i--) { if (v[i] > v[i - 1]) { ret = i; break; } } if (ret != -1) { int x = v[ret - 1]; int idx = ret; for (int j = ret + 1; j < v.size(); j++) { if (v[j] < v[idx] && v[j] > x) { idx = j; } } swap(v[ret - 1], v[idx]); } return ret; } int solve(int num) { vector<int> v = makeArray(num); int idx = getIndex(v); if(idx == -1) { sort(v.begin(), v.end()); } else { sort(v.begin() + idx, v.end()); } return combine(v); } }; int solve(int n) { return (new Solution())->solve(n); } int main(){ int n = 319; cout << solve(n); } 319 391
[ { "code": null, "e": 1244, "s": 1062, "text": "Suppose we have a number n, we have to find the next bigger permutation of its digits. When n is already in its largest permutation, then rotate it down to the smallest permutation." }, { "code": null, "e": 1307, "s": 1244, "text": "...
Program to calculate Resistance using given color code in circuits
08 Jun, 2020 There are many different types of Resistor available which can be used in both electrical and electronic circuits. The resistance value, tolerance, and wattage rating are generally printed onto the body of the resistor as color bands. The task is to find the resistance of 4-band resistor and 5-band resistor. Given four strings A, B, C and D which denotes the color codes of the 4-band resistor. The task is to find the resistance, tolerance and wattage rating using the given color codes. Examples: Input: A = “black”, B = “brown”, C = “red”, D = “green”Output: Resistance = 01 x 100 ohms +/- 0.5 % Input: A = “red”, B = “orange”, C = “yellow”, D = “green”Output: Resistance = 23 x 10k ohms +/- 0.5 % Approach: The idea is to store the digits and multiplers as in the hash-map and then the resistance of the resistor can be computed. Below is the implementation of the above approach: Python3 # Python implementation to find the # resistance of the resistor with# the given color codes # Function to find the resistance # using color codesdef findResistance(a, b, c, d): # Hash-map to store the values # of the color-digits color_digit = {'black': '0', 'brown': '1', 'red': '2', 'orange': '3', 'yellow': '4', 'green' : '5', 'blue' : '6', 'violet' : '7', 'grey' : '8', 'white': '9'} multiplier = {'black': '1', 'brown': '10', 'red': '100', 'orange': '1k', 'yellow': '10k', 'green' : '100k', 'blue' : '1M', 'violet' : '10M', 'grey' : '100M', 'white': '1G'} tolerance = {'brown': '+/- 1 %', 'red' : '+/- 2 %', 'green': "+/- 0.5 %", 'blue': '+/- 0.25 %', 'violet' : '+/- 0.1 %', 'gold': '+/- 5 %', 'silver' : '+/- 10 %', 'none': '+/-20 %'} if a in color_digit and b in color_digit\ and c in multiplier and d in tolerance: xx = color_digit.get(a) yy = color_digit.get(b) zz = multiplier.get(c) aa = tolerance.get(d) print("Resistance = "+xx + yy+\ " x "+zz+" ohms "+aa) else: print("Invalid Colors") # Driver Codeif __name__ == "__main__": a = "black" b = "brown" c = "red" d = "green" # Function Call findResistance(a, b, c, d) Resistance = 01 x 100 ohms +/- 0.5 % Given five strings A, B, C, D and E which denotes the color codes of the 5-band resistor. The task is to find the resistance, tolerance and wattage rating using the given color codes. Examples: Input: A = “black”, B = “brown”, C = “red”, D = “green”, E = “silver”Output: Resistance = 012 x 100k ohms +/- 10 % Input: A = “red”, B = “orange”, C = “yellow”, D = “green”, E = “gold”Output: Resistance = 234 x 100k ohms +/- 5 % Approach: The idea is to store the digits and multiplers as in the hash-map and then the resistance of the resistor can be computed. Below is the implementation of the above approach: Python3 # Python implementation to find the # resistance of the resistor with# the given color codes # Function to find the resistance # using color codesdef findResistance(a, b, c, d, e): # Hash-map to store the values # of the color-digits color_digit = {'black': '0', 'brown': '1', 'red': '2', 'orange': '3', 'yellow': '4', 'green' : '5', 'blue' : '6', 'violet' : '7', 'grey' : '8', 'white': '9'} multiplier = {'black': '1', 'brown': '10', 'red': '100', 'orange': '1k', 'yellow': '10k', 'green' : '100k', 'blue' : '1M', 'violet' : '10M', 'grey' : '100M', 'white': '1G'} tolerance = {'brown': '+/- 1 %', 'red' : '+/- 2 %', 'green': "+/- 0.5 %", 'blue': '+/- 0.25 %', 'violet' : '+/- 0.1 %', 'gold': '+/- 5 %', 'silver' : '+/- 10 %', 'none': '+/-20 %'} if a in color_digit and b in color_digit\ and c in color_digit and d in multiplier\ and e in tolerance: xx = color_digit.get(a) yy = color_digit.get(b) zz = color_digit.get(c) aa = multiplier.get(d) bb = tolerance.get(e) print("Resistance = "+xx + yy\ + zz+" x "+aa+" ohms "+bb) else: print("Invalid Colors") # Driver Codeif __name__ == "__main__": a = "red" b = "orange" c = "yellow" d = "green" e = "gold" # Function Call findResistance(a, b, c, d, e) Resistance = 234 x 100k ohms +/- 5 % Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 338, "s": 28, "text": "There are many different types of Resistor available which can be used in both electrical and electronic circuits. The resistance value, tolerance, and wattage rating are gene...
Change button Color in Kivy
27 Feb, 2020 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. In this article, we will learn about how to change the button color in kivy. There is a property named background_color which is used to change the color of the button in kivy python . background_color – The background-color kivy property sets the background color of an element. It is specified as a single color value. Syntax: background_color: 1, 0, 0, 1 Note: By default the color of button is black (little grey) if you want to change it then we use this property.and it only takes the value between 0 to 1 any other value given will lead to misbehaving of program. Basic Approach to follow while changing button color:1) import kivy2) import kivyApp3) import all needed4) set minimum version(optional)5) Add widgets6) Add buttons at set their colors6) Extend the class7) Return layout8) Run an instance of the class Kivy Tutorial – Learn Kivy with Examples. Now below is the code how can you change the color of button: Code 1# def build(self): # use a (r, g, b, a) tuple btn = Button(text ="Push Me !", font_size ="20sp", # Here you can give the color # The value must be between 0 to 1 # greyish black color background_color =(1, 1, 1, 1), size =(32, 32), size_hint =(.2, .2), pos =(300, 250)) return btn Code #2 ## Sample Python application demonstrating the ## How to change button color in Kivy.################################################### # import kivy module import kivy # to choose the colors randomly # every time you run it shows different color import random # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require("1.9.1") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # BoxLayout arranges children in a vertical or horizontal box. # or help to put the children at the desired location. from kivy.uix.boxlayout import BoxLayout # declaring the colours you can use directly also red = [1, 0, 0, 1] green = [0, 1, 0, 1] blue = [0, 0, 1, 1] purple = [1, 0, 1, 1] # class in which we are creating the button class ChangeColorApp(App): def build(self): superBox = BoxLayout(orientation ='vertical') HB = BoxLayout(orientation ='horizontal') # creating the list of defined colors colors = [red, green, blue, purple] # Changing the color of buttons # here you can see how you can change the color btn1 = Button(text ="One", # Color of button is changed not default background_color = random.choice(colors), font_size = 32, size_hint =(0.7, 1)) btn2 = Button(text ="Two", background_color = random.choice(colors), font_size = 32, size_hint =(0.7, 1)) HB.add_widget(btn1) HB.add_widget(btn2) VB = BoxLayout(orientation ='vertical') btn3 = Button(text ="Three", background_color = random.choice(colors), font_size = 32, size_hint =(1, 10)) btn4 = Button(text ="Four", background_color = random.choice(colors), font_size = 32, size_hint =(1, 15)) VB.add_widget(btn3) VB.add_widget(btn4) superBox.add_widget(HB) superBox.add_widget(VB) return superBox # creating the object root for App class root = ChangeColorApp() # run function runs the whole program # i.e run() method which calls the # target function passed to the constructor. root.run() Output: Picked Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2020" }, { "code": null, "e": 265, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it do...
Ruby | String concat Method
07 Jan, 2020 concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted to a character before concatenation. Syntax:String_Object.concat(String_Object) Parameters: This method can take the string object and normal string as the parameters. If it will take integer then this method will convert them into the character. Returns: This method returns the concatenated string as a result. Example 1: # Ruby program for concat method # taking a string objectstr = "Geeks" # using the methodstr.concat("ForGeeks") # displaying the resultputs str Output: GeeksForGeeks Example 2: # Ruby program for concat method # taking a string objectstr = "Geeks" # using the method# but taking integer also inside the method# it will convert it to characterstr.concat("ForGeeks", 33) # displaying the resultputs str Output: GeeksForGeeks! Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | unless Statement and unless Modifier Ruby | Hash delete() function Ruby For Beginners Ruby | Array class find_index() operation
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2020" }, { "code": null, "e": 241, "s": 28, "text": "concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted...
Node.js Buffer.compare() Method
13 Oct, 2021 Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like an array of integers. Buffer.compare() method compares the two given buffers. Syntax: buffer1.compare( targetBuffer, targetStart, targetEnd, sourceStart, sourceEnd ) Parameters: This method accepts five parameters as mentioned above and described below: targetBuffer: This parameter holds the buffer which will be compared with other buffer. targetStart: It refers to the starting index from which the elements of target buffer will begin comparing. Its default value is 0. targetEnd: It refers to the index till which the elements of target buffer will be compared. The default value is 0. sourceStart: The index in input buffer from which the comparing of values will start. The default value is 0. sourceEnd: The index in input buffer till which the comparing of values will be done. The default value is buffer.length Return Value: It returns a number indicating the difference in both buffers. The returns number are: 0: If they are equal. 1: If buffer1 is higher than buffer2 i.e. if buffer1 should come before buffer2 when sorted. -1: If buffer2 is higher than buffer1 i.e. if buffer2 should come before buffer1 when sorted. Below examples illustrate the Buffer.compare() Method in Node.js: Example 1: // Node.js program to demonstrate the // Buffer.compare() Method // Creating a buffervar buffer1 = Buffer.from('Geek');var buffer2 = Buffer.from('Geek');var op = Buffer.compare(buffer1, buffer2);console.log(op); var buffer1 = Buffer.from('GFG');var buffer2 = Buffer.from('Python');var op = Buffer.compare(buffer1, buffer2);console.log(op); Output: 0 -1 Example 2: // Node.js program to demonstrate the // Buffer.compare() Method // Creating a buffervar buffer1 = Buffer.from('2');var buffer2 = Buffer.from('1');var buffer3 = Buffer.from('3');var array = [buffer1, buffer2, buffer3]; // Before sortingconsole.log(array); // After sorting arrayconsole.log(array.sort(Buffer.compare)); Output: [ <Buffer 32>, <Buffer 31>, <Buffer 33> ] [ <Buffer 31>, <Buffer 32>, <Buffer 33> ] Example 3: // Node.js program to demonstrate the // Buffer.compare() Method var buffer1 = Buffer.from('GeeksOne');var buffer2 = Buffer.from('GeekTwo'); // Print: -1 as size of buffer1 starting // from index 4 is less than buffer2 sizevar op = buffer1.compare(buffer2, 4); // Print: 1 as the size of buffer2 starting // from index 5 is less than size of buffer1// starting from 0th indexvar op1 = buffer1.compare(buffer2, 0, 7, 5); console.log(op);console.log(op1); Output: -1 1 Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/api/buffer.html#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend Node.js-Buffer-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Oct, 2021" }, { "code": null, "e": 226, "s": 28, "text": "Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like an array of integers. Buffer.compare() method compares ...
Groovy - Data Types
In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to store the value associated with the variable. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy − byte − This is used to represent a byte value. An example is 2. byte − This is used to represent a byte value. An example is 2. short − This is used to represent a short number. An example is 10. short − This is used to represent a short number. An example is 10. int − This is used to represent whole numbers. An example is 1234. int − This is used to represent whole numbers. An example is 1234. long − This is used to represent a long number. An example is 10000090. long − This is used to represent a long number. An example is 10000090. float − This is used to represent 32-bit floating point numbers. An example is 12.34. float − This is used to represent 32-bit floating point numbers. An example is 12.34. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. char − This defines a single character literal. An example is ‘a’. char − This defines a single character literal. An example is ‘a’. Boolean − This represents a Boolean value which can either be true or false. Boolean − This represents a Boolean value which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. The following table shows the maximum allowed values for the numerical and decimal literals. Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed − java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double In addition, the following classes can be used for supporting arbitrary precision arithmetic − The following code example showcases how the different built-in data types can be used − class Example { static void main(String[] args) { //Example of a int datatype int x = 5; //Example of a long datatype long y = 100L; //Example of a floating point datatype float a = 10.56f; //Example of a double datatype double b = 10.5e40; //Example of a BigInteger datatype BigInteger bi = 30g; //Example of a BigDecimal datatype BigDecimal bd = 3.5g; println(x); println(y); println(a); println(b); println(bi); println(bd); } } When we run the above program, we will get the following result −
[ { "code": null, "e": 2668, "s": 2372, "text": "In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to sto...
Python | math.fabs() function
11 Mar, 2019 In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.fabs() function returns the absolute value of the number. Syntax: math.fabs(x) Parameter: x: This is a numeric expression. Returns: the absolute value of the number. Code #1: # Python code to demonstrate the working of fabs() # importing "math" for mathematical operations import math x = -33.7 # returning the fabs of 33.7print ("The fabs of 33.7 is : ", end ="") print (math.fabs(x)) The fabs of 33.7 is : 33.7 Code #2: # Python code to demonstrate the working of fabs() # importing "math" for mathematical operations import math # prints the fabs using fabs() method print ("math.fabs(-13.1) : ", math.fabs(-13.1))print ("math.fabs(101.96) : ", math.fabs(101.96)) math.fabs(-13.1) : 13.1 math.fabs(101.96) : 101.96 Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Mar, 2019" }, { "code": null, "e": 211, "s": 28, "text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.fabs() function returns the absolute value of the ...
Python - Tkinter Bitmaps
This attribute to displays a bitmap. There are following type of bitmaps available − "error" "gray75" "gray50" "gray25" "gray12" "hourglass" "info" "questhead" "question" "warning" from Tkinter import * import Tkinter top = Tkinter.Tk() B1 = Tkinter.Button(top, text ="error", relief=RAISED,\ bitmap="error") B2 = Tkinter.Button(top, text ="hourglass", relief=RAISED,\ bitmap="hourglass") B3 = Tkinter.Button(top, text ="info", relief=RAISED,\ bitmap="info") B4 = Tkinter.Button(top, text ="question", relief=RAISED,\ bitmap="question") B5 = Tkinter.Button(top, text ="warning", relief=RAISED,\ bitmap="warning") B1.pack() B2.pack() B3.pack() B4.pack() B5.pack() top.mainloop() When the above code is executed, it produces the following result −
[ { "code": null, "e": 2464, "s": 2378, "text": "This attribute to displays a bitmap. There are following type of bitmaps available −" }, { "code": null, "e": 2472, "s": 2464, "text": "\"error\"" }, { "code": null, "e": 2481, "s": 2472, "text": "\"gray75\"" }...
DataFrame.read_pickle() method in Pandas
16 Jul, 2020 Prerequisite : pd.to_pickle method() The read_pickle() method is used to pickle (serialize) the given object into the file. This method uses the syntax as given below : Syntax: pd.read_pickle(path, compression='infer') Parameters: Below is the implementation of the above method with some examples : Python3 # importing packages import pandas as pd # dictionary of data dct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframe data = pd.DataFrame(dct) # using to_pickle function to form file # with name 'pickle_file' pd.to_pickle(data,'./pickle_file.pkl') # unpickled the data by using the# pd.read_pickle methodunpickled_data = pd.read_pickle("./pickle_file.pkl")print(unpickled_data) Output : Example 2: Python3 # importing packages import pandas as pd # dictionary of data dct = {"f1": range(6), "b1": range(6, 12)} # forming dataframe data = pd.DataFrame(dct) # using to_pickle function to form file # with name 'pickle_data' pd.to_pickle(data,'./pickle_data.pkl') # unpickled the data by using the# pd.read_pickle methodunpickled_data = pd.read_pickle("./pickle_data.pkl")print(unpickled_data) Output : Python pandas-pickling Python-pandas 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 65, "s": 28, "text": "Prerequisite : pd.to_pickle method()" }, { "code": null, "e": 197, "s": 65, "text": "The read_pickle() method is used to pickle (serialize) the given object...
Load Balancing on Servers (Randomized Algorithm)
15 Nov, 2015 Consider a high traffic website that receives millions of requests (of different types) per five minutes, the site has k (for example n = 1000) servers to process the requests. How should the load be balanced among servers? The solutions that we generally think of area) Round Robinb) Assign new request to a server that has minimum load. Both of the above approaches look good, but they require additional state information to be maintained for load balancing. Following is a simple approach that works better than above approaches. Do following whenever a new request comes in, Pick a random server and assign the request to a random server The above approach is simpler, lightweight and surprisingly effective. This approach doesn’t calculate existing load on server and doesn’t need time management. Analysis of above Random ApproachLet us analyze the average load on a server when above approach of randomly picking server is used. Let there be k request (or jobs) J1, J2, ... Jk Let there be n servers be S1, S2, ... Sk. Let time taken by i’th job be Ti Let Rij be load on server Si from Job Jj. Rij is Tj if j’th job (or Jj) is assigned to Si, otherwise 0. Therefore, value of Rij is Tj with probability 1/n and value is 0 with probability (1-1/n) Let Ri be load on i’th server Average Load on i'th server 'Ex(Ri)' [Applying Linearity of Expectation] = = = (Total Load)/n So average load on a server is total load divided by n which is a perfect result. What is the possibility of deviation from average (A particular server gets too much load)?The average load from above random assignment approach looks good, but there may be possibility that a particular server becomes too loaded (even if the average is ok).It turns out that the probability of deviation from average is also very low (can be proved using Chernoff bound). Readers can refer below reference links for proves of deviations. For example, in MIT video lecture, it is shown that if there are 2500 requests per unit time and there are 10 servers, then the probability that any particular server gets 10% more load is at most 1/16000. Similar results are shown at the end of second reference also. So above simple load balancing scheme works perfect. In-fact this scheme is used in load balancers. References:http://www.cs.princeton.edu/courses/archive/fall09/cos521/Handouts/probabilityandcomputing.pdf MIT Video Lecture This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Randomized Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Nov, 2015" }, { "code": null, "e": 276, "s": 52, "text": "Consider a high traffic website that receives millions of requests (of different types) per five minutes, the site has k (for example n = 1000) servers to process the request...
Flutter – Ripple Effect
16 Oct, 2020 In Flutter, the InkWell widget is used to perform ripple animation when tapped. This effect is common for all the app components that follow the material design guideline. A ripple animation in its simplest term can be understood as a black (default) bar at the bottom of an app that displays some data when a tap is done on the respective component of the application. Let’s better understand these ripple effects using a simple application. To build such an app follow the below steps: Create a simple widget that can be tapped. Use the InkWell widget to add callback on the tap action. Let’s discuss them in detail. Let’s create a simple widget that has a button that can be tapped using the below code: Dart Scaffold.of(context).showSnackBar(SnackBar( content: Text('Hello Geeks!'), )); }, child: Container( padding: EdgeInsets.all(12.0), child: Text(' Button'), ), Now wrap the widget that we just created above with the InkWell widget as shown below: Dart InkWell( onTap: () { Scaffold.of(context).showSnackBar(SnackBar( content: Text('Hello Geeks!'), )); }, child: Container( padding: EdgeInsets.all(12.0), child: Text('Button'), ),); Now let’s build the complete app from the below-given source code. Complete Source Code: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp( title: title, home: MyHomePage(title: title), ); }} class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: Center(child: MyButton()), ); }} class MyButton extends StatelessWidget { @override Widget build(BuildContext context) { return InkWell( onTap: () { Scaffold.of(context).showSnackBar(SnackBar( content: Text('Hello Geeks!'), )); }, child: Container( padding: EdgeInsets.all(12.0), color: Colors.green, child: Text(' Button'), ), ); }} Output: android Flutter Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2020" }, { "code": null, "e": 399, "s": 28, "text": "In Flutter, the InkWell widget is used to perform ripple animation when tapped. This effect is common for all the app components that follow the material design guideline. A ...
PHP & MySQL - Connect Database Example
PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure. $mysqli = new mysqli($host, $username, $passwd, $dbName, $port, $socket); $host Optional − The host name running the database server. If not specified, then the default value will be localhost:3306. $username Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process. $passwd Optional − The password of the user accessing the database. If not specified, then the default will be an empty password. $dbName Optional − database name on which query is to be performed. $port Optional − the port number to attempt to connect to the MySQL server.. $socket Optional − socket or named pipe that should be used. You can disconnect from the MySQL database anytime using another PHP function close(). $mysqli->close(); Try the following example to connect to a MySQL server − Copy and paste the following example as mysql_example.php − <html> <head> <title>Connecting MySQL Server</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass); if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); $mysqli->close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output.
[ { "code": null, "e": 2458, "s": 2266, "text": "PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure." }, { "code": null, "e": 2533, "s": 2458, ...
Iterating over Arrays in Java
11 Dec, 2018 Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways. Method 1: Using for loop:This is the simplest of all where we just have to use a for loop where a counter variable accesses each element one by one. // Java program to iterate over an array// using for loopimport java.io.*;class GFG { public static void main(String args[]) throws IOException { int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int i, x; // iterating over an array for (i = 0; i < ar.length; i++) { // accessing each element of array x = ar[i]; System.out.print(x + " "); } }} Output : 1 2 3 4 5 6 7 8 Method 2: Using for each loop :For each loop optimizes the code, save typing and time. // JAVA program to iterate over an array// using for loopimport java.io.*;class GFG { public static void main(String args[]) throws IOException { int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int x; // iterating over an array for (int i : ar) { // accessing each element of array x = i; System.out.print(x + " "); } }} Output : 1 2 3 4 5 6 7 8 This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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. Java-Array-Programs Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Collections in Java Stream In Java Singleton Class in Java Set in Java Initializing a List in Java Introduction to Java Multithreading in Java Constructors in Java Exceptions in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Dec, 2018" }, { "code": null, "e": 213, "s": 52, "text": "Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways." }, { ...
Python program to remove K length words in String
24 Dec, 2021 Given a String, write a Python program to remove all the words with K length. Examples: Input : test_str = ‘Gfg is best for all geeks’, K = 3 Output : is best geeks Explanation : Gfg, for and all are of length 3, hence removed. Input : test_str = ‘Gfg is best for all geeks’, K = 2 Output : Gfg best for all geeks Explanation : is of length 2, hence removed. Method #1 : Using split() + join() + list comprehension + len() In this each word is split using split(), and then lengths are checked using len(), and then are omitted matching K. At last words are joined. Python3 # Python3 code to demonstrate working of# Remove K length words in String# Using split() + join() + list comprehension + len() # initializing stringtest_str = 'Gfg is best for all geeks' # printing original stringprint("The original string is : " + (test_str)) # initializing KK = 3 # getting splitstemp = test_str.split() # omitting K lengthsres = [ele for ele in temp if len(ele) != K] # joining resultres = ' '.join(res) # printing resultprint("Modified String : " + (res)) Output: The original string is : Gfg is best for all geeks Modified String : is best geeks Method #2 : Using filter() + lambda + split() + len() + join() In this, we perform task of filtering using filter() + lambda, rest all the functionalities are similar to above method. Python3 # Python3 code to demonstrate working of# Remove K length words in String# Using filter() + lambda + split() + len() + join() # initializing stringtest_str = 'Gfg is best for all geeks' # printing original stringprint("The original string is : " + (test_str)) # initializing KK = 3 # getting splitstemp = test_str.split() # omitting K lengths# filtering using filter() and lambdares = list(filter(lambda ele: len(ele) != K, temp)) # joining resultres = ' '.join(res) # printing resultprint("Modified String : " + (res)) Output: The original string is : Gfg is best for all geeks Modified String : is best geeks nnr223442 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Python program to convert a list to string Python program to add two numbers Python | Get dictionary keys as a list Python Program for Fibonacci numbers Python Program for factorial of a number
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 107, "s": 28, "text": "Given a String, write a Python program to remove all the words with K length. " }, { "code": null, "e": 117, "s": 107, "text": "Examples:" }, { "co...
How to declare variables in C#?
Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable. To declare variables − <data_type> <variable_list>; Let us see an example to declare two integer variables − int a, b; Above the variable is of int type. Let us declare a variable for other types − Variable of float type. float f; Variable of double type. double d; Let us display a variable − Live Demo using System; using System.Collections; class Demo { static void Main() { int x = 50; Console.WriteLine("Integer variable:"+x); } } Integer variable:50
[ { "code": null, "e": 1411, "s": 1187, "text": "Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable." }, { "code": null, ...
Scan conversion of Line and Line Drawing algorithms
08 Jun, 2021 SCAN Conversion of Line : A line connects two points. It is a basic element in graphics. You’ll need two spots between which to draw a line to draw a line . A line, or line segment, can be uniquely described by two points, according to geometry. We also know from algebra that a line can be defined by a slope, commonly denoted by the letter m, and a y-axis intercept, denoted by the letter b. A line in computer graphics is usually defined by two endpoints. However, most line-drawing algorithms calculate the slope and y- intercept as intermediate outputs. Line Drawing algorithms :Given the inherent restrictions of a raster display, the purpose of every line drawing method is to produce the best feasible approximation of an ideal line. Before getting into specific line drawing algorithms, it’s a good idea to think about the needs for such algorithms in general. The primary design criteria are as follows. Straight lines appear as straight lines. Straight lines start and end accurately. Displayed lines should have constant brightness along their length, independent of the line length and orientation. Lines should be drawn rapidly. Method-1 : Direct Method :In this algorithm, we have two endpoints. We find the slope of the line by using both the points, and we put the slope in the line equation y = mx + b. Then we find the value of b by putting x and y equal to 0. After this, we have a relation between x and y. Now we increase the value of x and find the corresponding value of y.These values will be the intermediate points of the line. After finding the intermediate points we’ll plot those points and draw the line. FIG – Direct method Method-2 : DDA (Digital Differential Analyzer) Algorithm :The incremental technique is used in this algorithm. It means that we can find the next coordinates by using past coordinates as a guide. In this method, the difference of pixel point is analyzed and according to the analysis, the line can be drawn. We’ll start with the initial position and work our way to the ending position by looking for intermediate places. The slope of the line will be the ratio of difference of y-coordinates and the difference of x-coordinates. Δy = ( y2 -y1 ), Δx = (x2 - x1) where, (x1, y1) and (x2, y2) are the endpoints. The Digital Differential Analyzer algorithm is based on the values of Δx and Δy. Δy = m * Δx , Δx = Δy / m The value of the slope will be either positive or negative. If the value of the slope is positive then the values of Δx and Δy are increased otherwise their values are decreased. (i). If (m < 1): xN = x1 + 1 , yN = y1 + m (ii). If (m > 1): xN = x1 + 1 / m , yN = y1 +1 (iii). If (m = 1): xN = x1 + 1 , yN = y1 + 1 FIG = DDA algo Method-3 : Bresenham’s Line Generation :Another incremental scan conversion procedure is the Bresenham’s algorithm. The big advantage of this algorithm is that, it uses only integer calculations. This method’s calculation is incredibly quick, which is why the line is drawn swiftly. We’ll need the two endpoints in this and then we have to find the decision parameters. Let assume that (x1,y1) and (x2,y2) are the two points. So, dx = x2-x1 and dy = y2-y1 The formula for the decision parameter is: di = 2dy – dx. -> If di >= 0: Plotted points are, di +1 = di + 2dy - 2dx ( i+1 is in base of d ) xN = x1 + 1 , yN = y1 + 1 -> If di < 0: Plotted points are, di +1 = di + 2dy ( i+1 is in base of d ) xN = x1 + 1 , yN = y1 Fig = Bresenham’s line algorithm computer-graphics Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Electronic Mail Advantages and Disadvantages of OOP Communication Models in IoT (Internet of Things ) Cloud Computing Analog to Digital Conversion Hypervisor Characteristics of Cloud Computing Introduction to Deep Learning array::size() in C++ STL Bubble Sort algorithm using JavaScript
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2021" }, { "code": null, "e": 55, "s": 28, "text": " SCAN Conversion of Line :" }, { "code": null, "e": 83, "s": 55, "text": "A line connects two points." }, { "code": null, "e": 118, "s": 83,...
How to compare date part only without comparing time in JavaScript?
30 Jan, 2020 To obtain date and time in javascript, we have the Date() class. We access Date() class by creating its objects. Date() class returns date and time both combined. There are four ways of instantiating a date:Syntax: var d = new Date(); //returns the present date and time or var d = new Date(milliseconds); //to set a specific date or var d = new Date(dateString); //to set a specific date or var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); //to set a specific date: So the Date() returns function Date() { [native code] } and we can turn that into a string by using object.toString() Approach 1:When the objects get compared it gets compared both with time and date.So now we gonna make the time to 00:00:00(stop) in that way when the objects get compared only the date gets compared as the time for both date objects will be 00:00:00(stop). To set the time as 00:00:00(stop), setHours() comes in handy. Syntax; //the hour(0-23) is mandatory. dateobject.setHours(hour, min, sec, millisec) And for making the time as 0 or completely stopped, we have to make sure that all the parameters are 0 including milli-seconds. Example: <!DOCTYPE html><html> <body> <p>Below date1 and data2 are compared for older, further, and same dates.</p> <script> //Example-1 var date1 = new Date(); date1.setHours(0, 0, 0, 0) var date2 = new Date(2020, 8, 20); //stops the clock date2.setHours(0, 0, 0, 0) document.write("date1=>", date1); document.write("<br \>date2=>", date2); if (date1 > date2) { document.write("<br \>date1 is further than date2"); } else if (date1 < date2) { document.write("<br \>date1 is older than date2") } else { document.write("<br \>date1 and date2 same") } //Example-2 date2 = new Date(2019, 11, 3); document.write("<br \><br \>date1=>", date1); document.write("<br \>date2=>", date2); if (date1 > date2) { document.write("<br \>date1 is further than date2"); } else if (date1 < date2) { document.write("<br \>date1 is older than date2") } else { document.write("<br \>date1 and date2 same") } //Example-3 date1 = new Date(); date2 = new Date(); date1.setHours(0, 0, 0, 0) date2.setHours(0, 0, 0, 0) document.write("<br \><br \>date1=>", date1); document.write("<br \>date2=>", date2); if (date1 > date2) { document.write("<br \>date1 is further than date2"); } else if (date1 < date2) { document.write("<br \>date1 is older than date2") } else { document.write("<br \>date1 and date2 same.") } //Example-4 date1 = new Date(); date2 = new Date(); date1.setHours(0, 0, 0, 0) /*Due to, time didn't get stop in data2, it’s time also gets compared to data1.*/ //date2.setHours(0,0,0,0) document.write("<br \><br \>date1=>", date1); document.write("<br \>date2=>", date2); if (date1 > date2) { document.write("<br \>date1 is further than date2"); } else if (date1 < date2) { document.write("<br \>date1 is older than date2") } else { document.write("<br \>date1 and date2 same.") } </script> </body> </html> Output Below date1 and data2 are compared for older, further, and same dates. date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time) date2=>Sun Sep 20 2020 00:00:00 GMT+0530 (India Standard Time) date1 is older than date2 date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time) date2=>Tue Dec 03 2019 00:00:00 GMT+0530 (India Standard Time) date1 is further than date2 date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time) date2=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time) date1 and date2 same. date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time) date2=>Wed Dec 04 2019 05:37:26 GMT+0530 (India Standard Time) date1 is older than date2 Approach 2:Here we gonna use toDateString() to obtain the only date, but when obtaining it gets converted to a string, as the comparison is not possible for strings, we need to get then again converted to a date object, now when converting them back to object time sets to 00:00:00(stops). Syntax: var date1 = new Date(new Date().toDateString()); Breakdown of the above syntax new Date().toDateString() converts the Date object to a string containing only the date part. new Date(new Date().toDateString()); converts it back to Date object setting time to 00:00:00 Example <!DOCTYPE html><html> <body> <p>Below date1 and data2 are compared for older, further, and same dates.</p> <script> //Example-1 var date1 = new Date(new Date().toDateString()); var date2 = new Date(new Date(2018, 8, 20).toDateString()); //var date2 = new Date(2018,8,20).toDateString(); document.write("date1=>", date1); //returns only the date. document.write("<br \>date2=>", date2); if (date1 > date2) { document.write("<br \>date1 is further than date2"); } else if (date1 < date2) { document.write("<br \>date1 is older than date2") } else { document.write("<br \>date1 and date2 same") } </script></body> </html> Output Below date1 and data2 are compared for older, further, and same dates. date1=>Fri Dec 20 2019 00:00:00 GMT+0530 (India Standard Time) date2=>Thu Sep 20 2018 00:00:00 GMT+0530 (India Standard Time) date1 is further than date2 javascript-date JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 191, "s": 28, "text": "To obtain date and time in javascript, we have the Date() class. We access Date() class by creating its objects. Date() class returns date and time both combined." }, { ...
What are props in React Native ?
14 Jul, 2021 Props are used to provide properties to the components using which they can be modified and customized. These properties are passed to the components when the component is created. Props are used in both user-defined and default components to extend their functionality. These props are immutable and cannot be changed after the creation of the component. <View> // Remaining application code <Component prop1 = {some value} prop2 = {some value} ... propn = {some value} /> // Remaining application code </View> The value of the props of the component is enclosed in braces to embed the expression in JSX. Example 1: Props in Default Component: In this, we will see the usage of props inside a component that is available to us by default. Creating React Native Application: Step 1: Create the React Native application using the following command:expo init PropsDefaultDemo Step 1: Create the React Native application using the following command: expo init PropsDefaultDemo Step 2: After creating your project folder i.e. PropsDefaultDemo, move to it using the following command:cd PropsDefaultDemo Step 2: After creating your project folder i.e. PropsDefaultDemo, move to it using the following command: cd PropsDefaultDemo Project Structure: It will look like this. Implementation: Write down the following code in App.js to show the functionality of Props. Here we will display several views where each will be having different properties. App.js import { StatusBar } from 'expo-status-bar';import React from 'react';import { StyleSheet, Text, View } from 'react-native'; // Exporting default componentexport default function App() { return ( <View style={styles.container}> <View style = {styles.style1} /> <View style = {styles.style2}/> <View style = {styles.style3}/> <View style = {styles.style4}/> </View> );} // Creating stylesconst styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, style1:{ backgroundColor: "red", height: 100, width: 200 }, style2:{ backgroundColor: "green", height: 50, width: 50 }, style3:{ backgroundColor: "blue", height: 100, width: 100 }}); Step to run the application: Run the server by using the following command. npm start Output: Example 2: Props in User Component In this section, we will see the usage of props inside a component that is user-defined. Creating React Native Application: Step 1: Create the React Native application using the following command:expo init PropsUserDemo Step 1: Create the React Native application using the following command: expo init PropsUserDemo Step 2: After creating your project folder i.e. PropsUserDemo, move to it using the following command:cd PropsUserDemo Step 2: After creating your project folder i.e. PropsUserDemo, move to it using the following command: cd PropsUserDemo Project Structure: It will look like this. Implementation: Create a new component file called ImageFill.js that will display an image specified as a prop a specified number of times in a prop called count. ImageFill.js import { View, Image, StyleSheet, ScrollView } from 'react-native';import React from 'react'; function ImageFill(props) { return ( <View style={styles.contStyle}> {[...Array(props.count)].map( () => ( <Image source={props.image} style = {{height: 100,width: 100, flex:1, flexWrap:'wrap'}}/> ) )} </View> );} // Creating stylesconst styles = StyleSheet.create({ contStyle:{ flex:1, alignItems: 'center', justifyContent: 'center', width: "100%" }}); // Exporting ImageFill Componentexport default ImageFill; App.js import { StatusBar } from 'expo-status-bar';import React from 'react';import { StyleSheet, Text, View, ScrollView } from 'react-native';import ImageFill from './ImageFill'; // Exporting default componentexport default function App() { return ( <ScrollView style={styles.container}> <ImageFill image = {require('./assets/gfglogo.png')} count = {4}/> </ScrollView> );} // Creating stylesconst styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', flexDirection: 'column', flexWrap: 'wrap', },}); Step to run the application: Run the server by using the following command. npm start Output: Picked React-Native ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2021" }, { "code": null, "e": 384, "s": 28, "text": "Props are used to provide properties to the components using which they can be modified and customized. These properties are passed to the components when the component is cre...
How to Create a Cutout Text using HTML and CSS ?
09 Feb, 2022 Cutout text is used as a background header of the webpage. The cutout text creates an attractive look on the webpage. To create a cutout text we will use only HTML and CSS. We display the cutout text and then we make the text blending of an element’s background with the element’s parent. The CSS mix-blend-mode property is required to do that. Divide this article into two sections creating structure and then we will apply CSS on that structure. Creating Structure: In this section, we will only make the cutout text structure by using HTML. HTML Code: HTML <!DOCTYPE html><html> <head> <title> Creating Cutout text with HTML and CSS </title> </head> <body> <div class="container"> <!-- Cutout text --> <h1 class="text">GeeksforGeeks</h1> <p> "A Computer Science Portal<br> for Geeks" </p> </div></body> </html> Designing the Structure: In this section we will apply some CSS property on created cutout text structure. The CSS mix-blend-mode property will play the main role and other things are totally depends on your designing knowledge. CSS Code: HTML <style> /* container class styling */ .container { /* Background image */ background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/20200218123727/background8.png"); background-size: cover; height: 360px; position: relative; text-align: center; } /* Cutout text class styling */ .text { background-color: black; color: white; font-size: 68px; font-weight: bold; margin: 0 auto; padding: 15px; border: 5px solid gray; position: absolute; top: 25%; left: 23%; mix-blend-mode: multiply; } .text:hover { } /* Styling p tag element */ p { position: absolute; left: 58%; top: 58%; color: white; text-align: right; font-style:italic; }</style> Final Solution: In this section we will combine the HTML and CSS file together and create a cutout text for the header of webpage. HTML <!DOCTYPE html><html> <head> <title> Creating Cutout text with HTML and CSS </title> <style> /* container class styling */ .container { /* Background image */ background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/20200218123727/background8.png"); background-size: cover; height: 360px; position: relative; text-align: center; } /* Cutout text class styling */ .text { background-color: black; color: white; font-size: 68px; font-weight: bold; margin: 0 auto; padding: 15px; border: 5px solid gray; position: absolute; top: 25%; left: 23%; mix-blend-mode: multiply; } .text:hover { } /* Styling p tag element */ p { position: absolute; left: 58%; top: 58%; color: white; text-align: right; font-style:italic; } </style></head> <body> <div class="container"> <!-- Cutout text --> <h1 class="text">GeeksforGeeks</h1> <p> "A Computer Science Portal<br> for Geeks" </p> </div></body> </html> Output: rajeev0719singh simranarora5sos CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2022" }, { "code": null, "e": 476, "s": 28, "text": "Cutout text is used as a background header of the webpage. The cutout text creates an attractive look on the webpage. To create a cutout text we will use only HTML and CSS. We...
How to delete registry Key using PowerShell?
To delete the registry key using PowerShell, we can use the Remove-Item command. Remove-Item command removes the registry key from the path specified. For example, we have the registry key name NodeSoftware stored at the path HKLM, under the Software key. To delete the key we will use the below command. Remove-Item -Path HKLM:\SOFTWARE\NodeSoftware -Force -Verbose We can also use the Get-Item command to retrieve the Key name and then use the Remove-Item after pipeline. Get-Item HKLM:\SOFTWARE\NodeSoftware | Remove-Item -Force -Verbose
[ { "code": null, "e": 1318, "s": 1062, "text": "To delete the registry key using PowerShell, we can use the Remove-Item command. Remove-Item command removes the registry key from the path specified. For example, we have the registry key name NodeSoftware stored at the path HKLM, under the Software ke...
fill() and fill_n() functions in C++ STL - GeeksforGeeks
11 Oct, 2019 A vector, once declared, has all its values initialized to zero. Following is an example code to demonstrate the same. // C++ program for displaying the default initialization// of the vector vect[]#include<bits/stdc++.h>using namespace std; int main() { // Creating a vector of size 8 vector<int> vect(8); // Printing default values for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i];} Output : 0 0 0 0 0 0 0 0 What if we wish to initialize the vector to a specific value, say 1 ? For this, we can pass the value along with the size of the vector. // C++ program for displaying specified initialization// of the vector vect[]#include<bits/stdc++.h>using namespace std; int main () { // Creates a vector of size 8 with all initial // values as 1. vector<int> vect(8, 1); for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i];} Output : 1 1 1 1 1 1 1 1 What if we wish to initialize the first 4 values to say 100 and rest 6 values as 200 ?One way to do this is to manually provide a value to each position in the vector. The other methods as provided in STL, the Standard Template Library, are fill and fill_n. fill()The ‘fill’ function assigns the value ‘val’ to all the elements in the range [begin, end), where ‘begin’ is the initial position and ‘end’ is the last position.NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ :// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main (){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i=0; i<vect.size(); i++) cout << vect[i] << " "; return 0;}Output :0 0 4 4 4 4 4 0 NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ : // C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main (){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i=0; i<vect.size(); i++) cout << vect[i] << " "; return 0;} Output : 0 0 4 4 4 4 4 0 fill_n()In fill_n(), we specify beginning position, number of elements to be filled and values to be filled. The following code demonstrates the use of fill_n.// C++ program to demonstrate working of fil_n()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize first four values // to 7 fill_n(vect.begin(), 4, 7); for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; // calling fill to initialize 3 elements from // "begin()+3" with value 4 fill_n(vect.begin() + 3, 3, 4); for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; return 0;}Output : 7 7 7 7 0 0 0 0 7 7 7 4 4 4 0 0 // C++ program to demonstrate working of fil_n()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize first four values // to 7 fill_n(vect.begin(), 4, 7); for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; // calling fill to initialize 3 elements from // "begin()+3" with value 4 fill_n(vect.begin() + 3, 3, 4); for (int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; return 0;} Output : 7 7 7 7 0 0 0 0 7 7 7 4 4 4 0 0 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above cpp-containers-library CPP-Library cpp-vector STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Function Pointer in C Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Operator Overloading in C++ Socket Programming in C/C++
[ { "code": null, "e": 24495, "s": 24467, "text": "\n11 Oct, 2019" }, { "code": null, "e": 24614, "s": 24495, "text": "A vector, once declared, has all its values initialized to zero. Following is an example code to demonstrate the same." }, { "code": "// C++ program for di...
AngularJS | ng-show Directive - GeeksforGeeks
28 Mar, 2019 The ng-show Directive in AngluarJS is used to show or hide the specified HTML element. If given expression in ng-show attribute is true then the HTML element will display otherwise it hide the HTML element. It is supported by all HTML elements. Syntax: <element ng-show="expression"> Contents... </element> Example 1: This example uses ng-show Directive to display the HTML element after checked the checkbox. <!DOCTYPE html><html> <head> <title>ng-show Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <div ng-app="app" ng-controller="geek"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-show Directive</h2> <input id="chshow" type="checkbox" ng-model="show" /> <label for="chshow"> Show Paragraph </label> <p ng-show="show" style="background: green; color: white; font-size: 14px; width:35%; padding: 10px;"> Show this paragraph using ng-show </p> </div> <script> var myapp = angular.module("app", []); myapp.controller("geek", function ($scope) { $scope.show = false; }); </script></body> </html> Output:Before checked the checkbox:After checked the checkbox: Example 2: This example uses ng-show Directive to display entered number is multiple of 5 or not. <!DOCTYPE html><html> <head> <title>ng-show Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center"> <div ng-controller="geek" ng-init="val=0"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-show Directive</h2> Enter a number: <input type="text" ng-model="val" ng-keyup="check(val)"> <div ng-hide="show"> <h3> The number is multiple of 5 </h3> </div> <div ng-show="show"> <h3> The number is not a multiple of 5 </h3> </div> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.check = function (val) { $scope.show = val % 5 == 0 ? false : true; }; }]); </script></body> </html> Output: AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Auth Guards in Angular 9/10/11 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23860, "s": 23832, "text": "\n28 Mar, 2019" }, { "code": null, "e": 24105, "s": 23860, "text": "The ng-show Directive in AngluarJS is used to show or hide the specified HTML element. If given expression in ng-show attribute is true then the HTML element will ...
C Program for Lower Case to Uppercase and vice-versa in a file - GeeksforGeeks
10 May, 2018 Lower Case To Upper Case Given a text file(gfg.txt), our task is to convert all the lower case characters of file into upper case. Examples: Input: (content inside file (gfg.txt) Geeks Classes: An extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts Output: (content inside file (gfg.txt) GEEKS CLASSES: AN EXTENSIVE CLASSROOM PROGRAMME BY GEEKSFORGEEKS TO BUILD AND ENHANCE DATA STRUCTURES AND ALGORITHM CONCEPTS Approach :Open the file gfg.txt in read mode. Check if there is any error in opening or locating a file. If yes, then throw an error message. If the file is found, then with the help of while loop, convert all the characters using toupper of that file into upper case.Close the file using fclose() function by passing the file pointer in it. // C++ program to convert// all lower case characters of a file// into Upper Case#include <bits/stdc++.h> int main(){ // initializing the file pointer FILE* fptr; // name of the file as sample.txt char file[50] = { "gfg.txt" }; char ch; // opening the file in read mode fptr = fopen(file, "r"); ch = fgetc(fptr); // converting into upper case while (ch != EOF) { // converting char to upper case ch = toupper(ch); printf("%c", ch); ch = fgetc(fptr); } // closing the file fclose(fptr); return 0;} Output: GEEKS CLASSES: AN EXTENSIVE CLASSROOM PROGRAMME BY GEEKSFORGEEKS TO BUILD AND ENHANCE DATA STRUCTURES AND ALGORITHM CONCEPTS Upper Case to Lower Case:Similar as above only using tolower function in place of toupperExamples: Input: (content inside file (gfg.txt) Geeks Classes: AN EXTENSIVE CLASSROOM PROGRAMME BY GEEKSFORGEEKS TO BUILD AND ENHANCE DATA STRUCTURES AND ALGORITHM CONCEPTS Output: (content inside file (gfg.txt) geeks classes: an extensive classroom programme by geeksforgeeks to build and enhance data structures and algorithm concepts // C++ program to convert all upper// case characters of a file// into lower Case#include <bits/stdc++.h> int main(){ // initializing the file pointer FILE* fptr; // name of the file as gfg.txt char file[30] = { "gfg.txt" }; char ch; // opening the file in read mode fptr = fopen(file, "r"); ch = fgetc(fptr); // converting into lower case while (ch != EOF) { // converting char to lower case ch = tolower(ch); printf("%c", ch); ch = fgetc(fptr); } // closing the file fclose(fptr); return 0;} Output: geeks classes: an extensive classroom programme by geeksforgeeks to build and enhance data structures and algorithm concepts Note: 1. Run this program offline by making the file gfg.txt and store some characters in it.2. Make sure that you have made the file with the same name as that used in code and within the same folder where your program is stored. C-File Handling C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24208, "s": 24180, "text": "\n10 May, 2018" }, { "code": null, "e": 24233, "s": 24208, "text": "Lower Case To Upper Case" }, { "code": null, "e": 24339, "s": 24233, "text": "Given a text file(gfg.txt), our task is to convert all the lower ...
D3.js | d3.keys() Function - GeeksforGeeks
28 Jun, 2019 The d3.keys() function in D3.js is used to return an array containing the property names or keys of the specified object or an associative array. Syntax: d3.keys(object) Parameters: This function accepts single parameter object containing key and value in pairs. Return Value: It returns the keys of the given object. Below programs illustrate the d3.keys() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title> d3.keys() Function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <script> // Initialising an object var month = { "January": 1, "February": 2, "March": 3, "April": 4 }; // Calling the d3.keys() function A = d3.keys(month); // Getting the key values of the given object document.write(A); </script></body> </html> Output: January, February, March, April Example 2: <!DOCTYPE html><html> <head> <title> d3.keys() Function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <script> // Initialising an object var month = { "GeeksforGeeks": 0, "Geeks": 2, "Geek": 3, "gfg": 4 }; // Calling the d3.keys() function A = d3.keys(month); // Getting the key values of the given object document.write(A); </script></body> </html> Output: GeeksforGeeks, Geeks, Geek, gfg Reference: https://devdocs.io/d3~5/d3-collection#keys D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24222, "s": 24194, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24368, "s": 24222, "text": "The d3.keys() function in D3.js is used to return an array containing the property names or keys of the specified object or an associative array." }, { "co...
What is an identifier and its rules in C language?
Identifier is one of the tokens which are used in C programming language. It is a name which is used to identify the variables, constants, functions, arrays, and also user-defined data. We cannot use keywords as identifiers because keywords are reserved for special use. Once declared, we can use the identifier in later program statements which refers to the associated value. The special kind of identifier is known as a statement label and it can be used in goto statements. The rules for naming identifiers are as follows − Identifier names are unique. Identifier names are unique. Cannot use a keyword as identifiers. Cannot use a keyword as identifiers. Identifier has to begin with a letter or underscore (_). Identifier has to begin with a letter or underscore (_). It should not contain white space. It should not contain white space. Special characters are not allowed. Special characters are not allowed. Identifiers can consist of only letters, digits, or underscore. Identifiers can consist of only letters, digits, or underscore. Only 31 characters are significant. Only 31 characters are significant. They are case sensitive. They are case sensitive. Following is the C program to identify which terms are called as identifiers − Live Demo /* C Program to Count Vowels and Consonants in a String */ #include <stdio.h> int main(){ char str[100]; int i, vowels, consonants; i = vowels = consonants = 0; printf("\nEnter any String : "); gets(str); while (str[i] != '\0'){ if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'){ vowels++; } else consonants++; i++; } printf("\n no of Vowels in the given String = %d", vowels); printf("\n no of Consonants in the given String = %d", consonants); return 0; } When the above program is executed, it produces the following result − Enter any String : Tutorials Point no of Vowels in the given String = 6 no of Consonants in the given String = 9 In the above program the identifiers are − Str, i, vowels, consonants
[ { "code": null, "e": 1248, "s": 1062, "text": "Identifier is one of the tokens which are used in C programming language. It is a name which is used to identify the variables, constants, functions, arrays, and also user-defined data." }, { "code": null, "e": 1440, "s": 1248, "text...
Gradient-Free Reinforcement Learning: Neuroevolution using Numpy! | by Jacob Gursky | Towards Data Science
What if I told you that you can train neural networks without ever calculating a gradient, and only using the forward pass? Such is the magic of neuroevolution! Also, I am going to show that all this can easily be done using only Numpy! Studying statistics you learn so much about gradient-based methods, but a while back I read a really interesting article by the folks at Uber AI, who showed that a simple genetic algorithm was competitive with the most sophisticated gradient-based RL methods at solving Atari games in terms of wall-clock time. I linked the source below, I highly recommend you give it a read if you are interested in reinforcement learning. First off, for those of you that don’t already know, neuroevolution describes the application of evolutionary and/or genetic algorithms to training either the structure and/or weights of neural networks as a gradient-free alternative! We are going to use an extremely simple case of neuroevolution here, only using a fixed topology network and focusing on optimizing only weights and biases. The neuroevolutionary process can be defined by four fundamental steps that are repeated until convergence is reached, starting with a pool of randomly generated networks. 1. Evaluate fitness of the population2. Select the most fit individual to reproduce3. Repopulate using copies of the most fit network4. Introduce normally distributed mutations to the network weights Wow, this seems pretty simple! Let’s break down some of the terminology a bit: - Fitness: This simply describes how well the network performed at a certain task and allows us to determine which networks to breed. Note that because evolutionary algorithms are a form of non-convex optimization, and therefore can be used with any loss function, regardless of its differentiability (or lack thereof) - Mutation: This one is probably the easiest! In order for our child networks to improve, we have to introduce random changes to the network weights, often drawn from a uniform or normal distribution. There can be many different forms of mutation: shift mutations (which multiply the parameters by a random number), swap mutations (which replace the parameter with a random number), sign mutations (which change the sign of a parameter), etc. We are only going to be using simple additive mutations, but there is a lot of room for creativity here! We should also consider the theoretical advantages of neuroevolutionary modeling. First off, we only need to use the forward pass of the network as we only need to calculate the loss in order to determine which networks to breed. The implications of this are obvious, the backwards pass is usually the most expensive! Second, evolutionary algorithms are guaranteed to find the global minimum of a loss surface given enough iterations, whereas convex gradient-based methods can get stuck in local minima. Lastly, more sophisticated forms of neuroevolution allow us to not only optimize the weights of a network, but also the structure itself! Well, this is a complicated question but it really boils down to exact gradient descent methods being more effective when enough gradient information is available. This means that the more convex a loss surface is, the more you will want to use analytic methods like SGD rather than genetic algorithms. As a consequence, it is very rare that you will use genetic algorithms in a supervised context, as usually there is enough gradient information available that traditional gradient descent methods will work quite well. However, if you are working in a RL context, or in a case with irregular loss surfaces or low convexity (like a sequential GAN), then neuroevolution provides a viable alternative! In fact, much research has come out lately finding that parameter-for-parameter neuroevolutionary models can do better in these settings. As laid out in the introduction, we are going to try and use only numpy for this project, only defining the helper functions that we need! Yes, I know, gym is also being loaded, but only for the environment ;) import numpy as npimport gym We are going to use the classic CartPole environment from gym to test our networks. The goal is to see how long the network can keep the pole upright by shifting left and right. As a RL task, neuroevolutionary methods should be a good fit! Our network will take in 4 observations as input, and will output either left or right as an action. We first are going to define a few of the helper functions to set up our networks. First off is the relu activation function, which we will use as the activation function for our hidden layers, and the softmax function for the output of the network to get probabilistic estimates of the network output! Lastly, we need to define a function that generates one-hot encodings of our response vector for when we need to calculate categorical cross-entropy. def relu(x): return np.where(x>0,x,0)def softmax(x): x = np.exp(x — np.max(x)) x[x==0] = 1e-15 return np.array(x / x.sum()) Now comes the fun stuff! First, we are going to define a class for our individual networks within the population. We need to define an initialization method that randomly assigns weights and biases and takes the network structure as input, a prediction method so we can get probabilities given an input, and finally an evaluation method that returns the categorical cross-entropy of the network given an input and response! Again, we are only going to use functions we define or functions from numpy. Note that the initialization method can also take another network as an input, this is how we will perform mutations between generations! # Lets define a new neural network class that can interact with gymclass NeuralNet(): def __init__(self, n_units=None, copy_network=None, var=0.02, episodes=50, max_episode_length=200): # Testing if we need to copy a network if copy_network is None: # Saving attributes self.n_units = n_units # Initializing empty lists to hold matrices weights = [] biases = [] # Populating the lists for i in range(len(n_units)-1): weights.append(np.random.normal(loc=0,scale=1,size=(n_units[i],n_units[i+1]))) biases.append(np.zeros(n_units[i+1])) # Creating dictionary of parameters self.params = {'weights':weights,'biases':biases} else: # Copying over elements self.n_units = copy_network.n_units self.params = {'weights':np.copy(copy_network.params['weights']), 'biases':np.copy(copy_network.params['biases'])} # Mutating the weights self.params['weights'] = [x+np.random.normal(loc=0,scale=var,size=x.shape) for x in self.params['weights']] self.params['biases'] = [x+np.random.normal(loc=0,scale=var,size=x.shape) for x in self.params['biases']] def act(self, X): # Grabbing weights and biases weights = self.params['weights'] biases = self.params['biases'] # First propgating inputs a = relu((X@weights[0])+biases[0]) # Now propogating through every other layer for i in range(1,len(weights)): a = relu((a@weights[i])+biases[i]) # Getting probabilities by using the softmax function probs = softmax(a) return np.argmax(probs) # Defining the evaluation method def evaluate(self, episodes, max_episode_length, render_env, record): # Creating empty list for rewards rewards = [] # First we need to set up our gym environment env=gym.make('CartPole-v0') # Recording video if we need to if record is True: env = gym.wrappers.Monitor(env, "recording") # Increasing max steps env._max_episode_steps=1e20 for i_episode in range(episodes): observation = env.reset() for t in range(max_episode_length): if render_env is True: env.render() observation, _, done, _ = env.step(self.act(np.array(observation))) if done: rewards.append(t) break # Closing our enviroment env.close() # Getting our final reward if len(rewards) == 0: return 0 else: return np.array(rewards).mean() Lastly we need to define a class that manages our population, performing the four key steps in neuroevolution! We need three methods here. First, an initialization method that creates a pool of random networks and sets attributes. Next, we need a fit method that, given an input, repeatedly performs the steps outlined above: first evaluating networks, then selecting the most fit, creating child networks, and finally mutating the children! Lastly, we need a prediction method so that we can use the best network trained by the class. Let’s get down to testing! # Defining our class that handles populations of networksclass GeneticNetworks(): # Defining our initialization method def __init__(self, architecture=(4,16,2),population_size=50, generations=500,render_env=True, record=False, mutation_variance=0.02,verbose=False,print_every=1,episodes=10,max_episode_length=200): # Creating our list of networks self.networks = [NeuralNet(architecture) for _ in range(population_size)] self.population_size = population_size self.generations = generations self.mutation_variance = mutation_variance self.verbose = verbose self.print_every = print_every self.fitness = [] self.episodes = episodes self.max_episode_length = max_episode_length self.render_env = render_env self.record = record # Defining our fiting method def fit(self): # Iterating over all generations for i in range(self.generations): # Doing our evaluations rewards = np.array([x.evaluate(self.episodes, self.max_episode_length, self.render_env, self.record) for x in self.networks]) # Tracking best score per generation self.fitness.append(np.max(rewards)) # Selecting the best network best_network = np.argmax(rewards) # Creating our child networks new_networks = [NeuralNet(copy_network=self.networks[best_network], var=self.mutation_variance, max_episode_length=self.max_episode_length) for _ in range(self.population_size-1)] # Setting our new networks self.networks = [self.networks[best_network]]+new_networks # Printing output if necessary if self.verbose is True and (i%self.print_every==0 or i==0): print('Generation:',i+1,'| Highest Reward:',rewards.max().round(1),'| Average Reward:',rewards.mean().round(1)) # Returning the best network self.best_network = self.networks[best_network] As stated above, we are going to test our networks on the CartPole problem, using only 1 hidden layer with 16 nodes, and two output nodes denoting either a left or right movement. We also need to average over many episodes, so we don’t accidentally pick a bad network for the next generation! I picked many of these parameters after a little trial-and-error, so your mileage may vary! Also, we will only introduce mutations with a variance of 0.05, so as to not break the functionality of the networks. # Lets train a population of networksfrom time import timestart_time = time()genetic_pop = GeneticNetworks(architecture=(4,16,2), population_size=64, generations=5, episodes=15, mutation_variance=0.1, max_episode_length=10000, render_env=False, verbose=True)genetic_pop.fit()print('Finished in',round(time()-start_time,3),'seconds')Generation: 1 | Highest Reward: 309.5 | Average Reward: 29.2Generation: 2 | Highest Reward: 360.9 | Average Reward: 133.6Generation: 3 | Highest Reward: 648.2 | Average Reward: 148.0Generation: 4 | Highest Reward: 616.6 | Average Reward: 149.9Generation: 5 | Highest Reward: 2060.1 | Average Reward: 368.3Finished in 35.569 seconds First, let’s look at how a randomly initialized network performs on the task. Obviously, there is no strategy here and the pole falls over almost immediately. Please ignore the cursor in the gif below, recording in Gym doesn’t play nice with Windows! random_network = NeuralNet(n_units=(4,16,2))random_network.evaluate(episodes=1, max_episode_length=int(1e10), render_env=True, record=False) After only 5 generations, we can see that our network has almost completely mastered the art of the CartPole! And it only took around thirty seconds of train-time! Note that with further training, the network learns to keep it completely upright nearly 100% of the time, but for now we are just interested in speed, and 5 generations is rather short! We should consider this a good example of the power of neuroevolution. # Lets observe our best networkgenetic_pop.best_network.evaluate(episodes=3, max_episode_length=int(1e10), render_env=True, record=False) Obviously, there are quite a few things we could add in the future to further examine the effectiveness of neuroevolution. Firstly, it would be interesting to study the effects of different mutation operators such as cross-over. It would also be a smart idea to shift over to a modern deep-learning platform like TensorFlow or PyTorch. Note that genetic algorithms are highly parallelizable, as all we would have to do is run each network on a single device with one forward pass. No need to mirror weights or complicated distribution strategies! Therefore we have a nearly linear decrease in run-time with each additional unit of processing. Lastly, we should explore neuroevolution on different reinforcement learning tasks, or even other situations where gradients can be difficult to evaluate, such as in Generative Adversarial Networks or long-sequence LSTM networks. If you are interested in neuroevolution and its applications, Uber has a fantastic page on several papers showing the modern advantages of neuroevolution in reinforcement learning: eng.uber.com The source code for this project can be found at my public GitHub repository: github.com If you have any questions about this project or just want to discuss deep learning, feel free to email me at gurskyjacob@gmail.com!
[ { "code": null, "e": 833, "s": 171, "text": "What if I told you that you can train neural networks without ever calculating a gradient, and only using the forward pass? Such is the magic of neuroevolution! Also, I am going to show that all this can easily be done using only Numpy! Studying statistic...
How to Fix Cassandra Consistency Issues using Read Repair | by Andriy Zabavskyy | Towards Data Science
As many of you probably know, Cassandra is an AP big data storage. In other words, when a network partition happens, Cassandra remains available and relaxes the Consistency property. It is always said that it is eventually consistent or, in other words, it will be consistent at some point in time in future. The important things to know which is not really obvious are: The cluster does become inconsistent pretty often. Sure, there are many things influencing the stability of the cluster, such as proper configuration, dedicated resources, production load, professionalism of the ops guys etc, but the fact is the probability the nodes are going down from time to time and therefore the data become inconsistent are really high. The cluster does NOT become consistent again automatically. This is something which goes against the god feeling towards the modern and mature distributed systems. Unless you have the enterprise version of Datastax and enable one the latest feature of DSE v6 you have to fix the inconsistency issues manually. Fortunately, there are ways to fix the inconsistency issues. There a couple of options here: nodetool repair tool. This is probably the main and default method to use. Running the command on a node which was down for all the tables or specific ones. One caveat though is: all the nodes should be UP while you are running the command. read repair Cassandra feature. This is an important feature meaning, during the read requests the cluster organism is repairing itself, to be more precise it repairs the proper data replicas. If the replicas involved in a read requests are not consistent they are being aligned again As it was stated above the default and main way to fix inconsistency is nodetool repair tool, so the natural question is when and why to use read repair method. Let me answer that using the experience from one of my project. At some point we entered a period when our Cassandra cluster started to become very unstable and it took significant amount of time until all the nodes returned to the UP state again. That lead to the 2 main consequences: data became inconsistent nodetool repair tool was not possible to use to fix inconsistencies during that period Having these circumstances the best we could do was using the read repair feature to make sure at least at the majority of replicas, at the Quorum level, the data is consistent so that for all the reads which are using the Quorum consistency level the data is consistent and up to date Read repair feature fixes the consistency only on the records which are involved in the reads, so how to repair the whole table? It is possible to use the following approach: select one of narrowest column to read read the whole table using the copy command to export the data to the file So let’s consider we have a Cassandra table “event” in a keyspace “test” with one of the narrowest column called “id”; the copy command would look like this: cqlsh -e "consistency QUORUM; copy test.event(fid) to '/tmp/tid'" Alternatively, you could read whole records and send them to ‘/dev/null’: cqlsh -e "consistency QUORUM; copy test.event to '/dev/null'" And sure, when all the nodes are UP you could use consistency ALL, but in this case it’s better to use the nodetool repair tool like this: nodetool repair test event Cassandra is great big data storage but in order to leverage it to the fullest, it requires a good understanding of the main principles, how it works and, as any beautiful thing, it requires some care :)
[ { "code": null, "e": 481, "s": 172, "text": "As many of you probably know, Cassandra is an AP big data storage. In other words, when a network partition happens, Cassandra remains available and relaxes the Consistency property. It is always said that it is eventually consistent or, in other words, i...
GalleryView in Android with Example - GeeksforGeeks
13 Jul, 2021 In Android, Gallery is a view that can show items in a center locked, horizontal scrolling list, and hence the user can able to select a view, and then the user selected view will be shown in the center of the Horizontal list. “N” number of items can be added by using the Adapter. The adapter is a bridging component between UI component and data source(It can be an array of items defined in java code or from a database). The items given in the adapter will be shown in the gallery in the example. Important Point: Gallery class was deprecated in API level 16. Instead other horizontally scrolling widgets are HorizontalScrollView and ViewPager from the support library are available. XML <!-- By using android:spacing we can give spacing between images android:animationDuration="3000" -> for animation running --><Gallery android:id="@+id/languagesGallery" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:unselectedAlpha="50" android:spacing="5dp" android:animationDuration="2000" android:padding="10dp" /> Methods Description To set the duration for how long a transition animation should run (in milliseconds) whenever there is change in layout. This can be set in xml also via android:animationDuration=”3000′′ To set the spacing between items in a Gallery. This can be set in xml also via android:spacing=”5dp” To set the alpha on the items that are not selected. This can be set in xml also via android:unselectedAlpha=”0.25′′ Let us see the implementation of important methods: Java // get the reference of Gallery firstGallery simpleGallery = (Gallery) findViewById(R.id.languagesGallery); // set 3000 milliseconds for animation duration between each items of Gallery// xml equivalent -> android:animationDuration="2000"simpleGallery.setAnimationDuration(2000); // set space between the items of Gallery// xml equivalent -> android:spacing="15dp"simpleGallery.setSpacing(15); // set 0.25 value for the alpha of unselected items of Gallery// xml equivalent -> android:unselectedAlpha="0.25"simpleGallery.setUnselectedAlpha(0.25f); Attributes Description To set the background of a Gallery. For background, either we can set colors (using colors.xml) or images which are kept under drawable folder Via java code also, we can set the background color in the below way simpleGallery.setBackgroundColor(Color.GFGGreencolor); // set the desired color To set the duration for how long a transition animation should run (in milliseconds) Via java, simpleGallery.setAnimationDuration(<No of milliseconds>); To set the spacing between items in a Gallery. Via java, simpleGallery.setSpacing(10); // We can set spacing between items as per our requirement To set the alpha on the items that are not selected. Via java, simpleGallery.setUnselectedAlpha(0.25f) A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:orientation="vertical" tools:context=".MainActivity"> <!-- create a ImageView and Gallery --> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitXY" /> <!-- By using android:spacing we can give spacing between images android:animationDuration="3000" -> for animation running --> <Gallery android:id="@+id/languagesGallery" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:animationDuration="2000" android:padding="10dp" android:spacing="5dp" android:unselectedAlpha="50" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Gallery;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Gallery simpleGallery; // CustomizedGalleryAdapter is a java class which extends BaseAdapter // and implement the override methods. CustomizedGalleryAdapter customGalleryAdapter; ImageView selectedImageView; // To show the selected language, we need this // array of images, here taken 10 different kind of most popular programming languages int[] images = {R.drawable.python, R.drawable.javascript, R.drawable.java, R.drawable.python, R.drawable.r, R.drawable.python, R.drawable.javascript, R.drawable.python, R.drawable.r, R.drawable.javascript}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Our layout is activity_main // get the reference of Gallery. As we are showing languages it is named as languagesGallery // meaningful names will be good for easier understanding simpleGallery = (Gallery) findViewById(R.id.languagesGallery); // get the reference of ImageView selectedImageView = (ImageView) findViewById(R.id.imageView); // initialize the adapter customGalleryAdapter = new CustomizedGalleryAdapter(getApplicationContext(), images); // set the adapter for gallery simpleGallery.setAdapter(customGalleryAdapter); // Let us do item click of gallery and image can be identified by its position simpleGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Whichever image is clicked, that is set in the selectedImageView // position will indicate the location of image selectedImageView.setImageResource(images[position]); } }); }} Step 4: Create a new class CustomizedGalleryAdapter.java This can be in the same location as MainActivity.java for easier reference. In this step, we create a CustomizedGalleryAdapter and it is extended from BaseAdapter and implements the overridden methods. Inside the code, an ImageView is created at run time in the getView method and finally set the image in the ImageView. Java import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.Gallery;import android.widget.ImageView; public class CustomizedGalleryAdapter extends BaseAdapter { private Context context; private int[] images; public CustomizedGalleryAdapter(Context c, int[] images) { context = c; this.images = images; } // returns the number of images, in our example it is 10 public int getCount() { return images.length; } // returns the Item of an item, i.e. for our example we can get the image public Object getItem(int position) { return position; } // returns the ID of an item public long getItemId(int position) { return position; } // returns an ImageView view public View getView(int position, View convertView, ViewGroup parent) { // position argument will indicate the location of image // create a ImageView programmatically ImageView imageView = new ImageView(context); // set image in ImageView imageView.setImageResource(images[position]); // set ImageView param imageView.setLayoutParams(new Gallery.LayoutParams(200, 200)); return imageView; }} On running the android code in android studio, we can able to get the output as shown in the attached video. This is a useful feature that is used across many android apps. We need to consider the important points mentioned earlier. i.e. horizontally scrolling widgets are HorizontalScrollView and ViewPager from the support library are available and hence for the latest devices prefer them. singghakshay android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25036, "s": 25008, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25537, "s": 25036, "text": "In Android, Gallery is a view that can show items in a center locked, horizontal scrolling list, and hence the user can able to select a view, and then the user se...
cPanel - Cron Jobs
If you want to run a command or a php program on a specified time interval like once a day or once a week, you can setup cron jobs in this interface. Cron jobs allow you to run a specific command or program automatically. This is often required, if you are using a software like CRM or Billing Software. Setting up cron jobs more often may degrade your server’s performance. To add a new cron job, follow these steps − Step 1 − Open Cron Jobs by clicking Cron Jobs found in the Advanced section in cPanel. Step 2 − Scroll down to see Add New Cron Job interface. Step 3 − You can choose an existing setting from common settings. If you do that all the fields of cron execution time will automatically get filled. Or you can choose your custom runtime settings by specifying in the next text inputs accordingly. Step 4 − Enter your command to run in cron job. If you are running a php file, enter full name of php file. For example − php /home/tutorialspoint/public_html/cron.php Step 5 − Click Add New Cron Job button to add a cron job. cPanel by default sends an email each time a cron job runs. It also redirects the output of the command or file into the email. Default email for this is your system account, but you can change this email too. To change the email on which you want to receive cron email, firstly find out Cron Email interface in Cron Jobs. Then enter your new email in which you wish to get cron emails. Click Update email to update your email. If your cron runs more frequently, then you may not want to receive emails, you can disable receiving emails by redirecting your output into null by writing >/dev/null 2>&1 at the end of the command. For example − php /home/tutorialspoint/public_html/cron.php >/dev/null 2>&1 To edit or delete your existing cron jobs, you can scroll below on the Corn Jobs interface to see current cron jobs. Once you select the job, you can click either the delete link or the edit link to edit or delete a particular cron job. 10 Lectures 47 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 3432, "s": 3057, "text": "If you want to run a command or a php program on a specified time interval like once a day or once a week, you can setup cron jobs in this interface. Cron jobs allow you to run a specific command or program automatically. This is often required, if you ...
Set Up Postfix MTA and IMAP/POP3
In order to send an email from our CentOS 7 server, we will need the setup to configure a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for sending outbound mail for system users or corporate Internet Domains via SMTP. It is worth noting, this tutorial only teaches the process of setting up the daemon for local use. We do not go into detail about advanced configuration for setting up an MTA for business operations. This is a combination of many skills including but not limited to: DNS, getting a static routable IP address that is not blacklisted, and configuring advanced security and service settings. In short, this tutorial is meant to familiarize you with the basic configuration. Do not use this tutorial for MTA configuration of an Internet facing host. With its combined focus on both security and the ease of administration, we have chosen Postfix as the MTA for this tutorial. The default MTA installed in the older versions of CentOS is Sendmail. Sendmail is a great MTA. However, of the author's humble opinion, Postfix hits a sweet spot when addressing the following notes for an MTA. With the most current version of CentOS, Postfix has superseded Sendmail as the default MTA. Postfix is a widely used and well documented MTA. It is actively maintained and developed. It requires minimal configuration in mind (this is just email) and is efficient with system resources (again, this is just email). Step 1 − Install Postfix from YUM Package Manager. [root@centos]# yum -y install postfix Step 2 − Configure Postfix config file. The Postfix configuration file is located in: /etc/postfix/main.cf In a simple Postfix configuration, the following must be configured for a specific host: host name, domain, origin, inet_interfaces, and destination. Configure the hostname − The hostname is a fully qualified domain name of the Postfix host. In OpenLDAP chapter, we named the CentOS box: centos on the domain vmnet.local. Let’s stick with that for this chapter. # The myhostname parameter specifies the internet hostname of this # mail system. The default is to use the fully-qualified domain name # from gethostname(). $myhostname is used as a default value for many # other configuration parameters. # myhostname = centos.vmnet.local Configure the domain − As stated above, the domain we will be using in this tutorial is vmnet.local # The mydomain parameter specifies the local internet domain name. # The default is to use $myhostname minus the first component. # $mydomain is used as a default value for many other configuration # parameters. # mydomain = vmnet.local Configure the origin − For a single server and domain set up, we just need to uncomment the following sections and leave the default Postfix variables. # SENDING MAIL # # The myorigin parameter specifies the domain that locally-posted # mail appears to come from. The default is to append $myhostname, # which is fine for small sites. If you run a domain with multiple # machines, you should (1) change this to $mydomain and (2) set up # a domain-wide alias database that aliases each user to # user@that.users.mailhost. # # For the sake of consistency between sender and recipient addresses, # myorigin also specifies the default domain name that is appended # to recipient addresses that have no @domain part. # myorigin = $myhostname myorigin = $mydomain Configure the network interfaces − We will leave Postfix listening on our single network interface and all protocols and IP Addresses associated with that interface. This is done by simply leaving the default settings enabled for Postfix. # The inet_interfaces parameter specifies the network interface # addresses that this mail system receives mail on. By default, # the software claims all active interfaces on the machine. The # parameter also controls delivery of mail to user@[ip.address]. # # See also the proxy_interfaces parameter, for network addresses that # are forwarded to us via a proxy or network address translator. # # Note: you need to stop/start Postfix when this parameter changes. # #inet_interfaces = all #inet_interfaces = $myhostname #inet_interfaces = $myhostname, localhost #inet_interfaces = localhost # Enable IPv4, and IPv6 if supported inet_protocols = all Step 3 − Configure SASL Support for Postfix. Without SASL Authentication support, Postfix will only allow sending email from local users. Or it will give a relaying denied error when the users send email away from the local domain. Note − SASL or Simple Application Security Layer Framework is a framework designed for authentication supporting different techniques amongst different Application Layer protocols. Instead of leaving authentication mechanisms up to the application layer protocol, SASL developers (and consumers) leverage current authentication protocols for higher level protocols that may not have the convenience or more secure authentication (when speaking of access to secured services) built in. [root@centos]# yum -y install cyrus-sasl Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: repos.forethought.net * extras: repos.dfw.quadranet.com * updates: mirrors.tummy.com Package cyrus-sasl-2.1.26-20.el7_2.x86_64 already installed and latest version Nothing to do smtpd_sasl_auth_enable = yes smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination smtpd_sasl_security_options = noanonymous smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth ##Configure SASL Options Entries: smtpd_sasl_auth_enable = yes smptd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination smtp_sasl_type = dovecot smtp_sasl_path = private/auth/etc Step 4 − Configure FirewallD to allow incoming SMTP Services. [root@centos]# firewall-cmd --permanent --add-service=smtp success [root@centos]# firewall-cmd --reload success [root@centos]# Now let's check to make sure our CentOS host is allowing and responding to the requests on port 25 (SMTP). Nmap scan report for 172.16.223.132 Host is up (0.00035s latency). Not shown: 993 filtered ports PORT STATE SERVICE 20/tcp closed ftp-data 21/tcp open ftp 22/tcp open ssh 25/tcp open smtp 80/tcp open http 389/tcp open ldap 443/tcp open https MAC Address: 00:0C:29:BE:DF:5F (VMware) As you can see, SMTP is listening and the daemon is responding to the requests from our internal LAN. Dovecot is a secure IMAP and POP3 Server deigned to handle incoming mail needs of a smaller to larger organization. Due to its prolific use with CentOS, we will be using Dovecot as an example of installing and configuring an incoming mail-server for CentOS and MTA SASL Provider. As noted previously, we will not be configuring MX records for DNS or creating secure rules allowing our services to handle mail for a domain. Hence, just setting these services up on an Internet facing host may leave leverage room for security holes w/o SPF Records. Step 1 − Install Dovecot. [root@centos]# yum -y install dovecot Step 2 − Configure dovecot. The main configuration file for dovecot is located at: /etc/dovecot.conf. We will first back up the main configuration file. It is a good practice to always backup configuration files before making edits. This way id (for example) line breaks get destroyed by a text editor, and years of changes are lost. Reverting is easy as copying the current backup into production. # Protocols we want to be serving. protocols = imap imaps pop3 pop3s Now, we need to enable the dovecot daemon to listen on startup − [root@localhost]# systemctl start dovecot [root@localhost]# systemctl enable dovecot Let's make sure Dovecot is listening locally on the specified ports for: imap, pop3, imap secured, and pop3 secured. [root@localhost]# netstat -antup | grep dovecot tcp 0 0 0.0.0.0:110 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:995 0.0.0.0:* LISTEN 4368/dovecot tcp6 0 0 :::110 :::* LISTEN 4368/dovecot tcp6 0 0 :::143 :::* LISTEN 4368/dovecot tcp6 0 0 :::993 :::* LISTEN 4368/dovecot tcp6 0 0 :::995 :::* LISTEN 4368/dovecot [root@localhost]# As seen, dovecot is listening on the specified ports for IPv4 and IPv4. Now, we need to make some firewall rules. [root@localhost]# firewall-cmd --permanent --add-port=110/tcp success [root@localhost]# firewall-cmd --permanent --add-port=143/tcp success [root@localhost]# firewall-cmd --permanent --add-port=995/tcp success [root@localhost]# firewall-cmd --permanent --add-port=993/tcp success [root@localhost]# firewall-cmd --reload success [root@localhost]# Our incoming mail sever is accepting requests for POP3, POP3s, IMAP, and IMAPs to hosts on the LAN. Port Scanning host: 192.168.1.143 Open TCP Port: 21 ftp Open TCP Port: 22 ssh Open TCP Port: 25 smtp Open TCP Port: 80 http Open TCP Port: 110 pop3 Open TCP Port: 143 imap Open TCP Port: 443 https Open TCP Port: 993 imaps Open TCP Port: 995 pop3s 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2510, "s": 2257, "text": "In order to send an email from our CentOS 7 server, we will need the setup to configure a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for sending outbound mail for system users or corporate Internet Domains via SMTP."...
SQL Query to Delete Duplicate Rows - GeeksforGeeks
23 Sep, 2021 Through this article, we will learn how to delete duplicate rows from a database table. As we know that duplicity in our database tends to be a waste of memory space. It records inaccurate data and is also unable to fetch out the correct data from the database. One or more rows that have identical or the same data value are considered to be Duplicate rows. Now, we have to follow the below steps to complete the task- Step 1: First we have to create a table having named “DETAILS”- Query: CREATE TABLE DETAILS ( SN INT IDENTITY(1,1) EMPNAME VARCHAR(25), DEPT VARCHAR(20), CONTACTNO BIGINT NOT NULL, CITY VARCHAR(15) ); Step 2: Now, we have to insert values or data in the table. INSERT INTO EMPDETAIL VALUES ('VISHAL','SALES',9193458625,'GAZIABAD'), ('VIPIN','MANAGER',7352158944,'BARIELLY'), ('ROHIT','IT',7830246946,'KANPUR'), ('RAHUL','MARKETING',9635688441,'MEERUT'), ('SANJAY','SALES',9149335694,'MORADABAD'), ('VIPIN','MANAGER',7352158944,'BARIELLY'), ('VISHAL','SALES',9193458625,'GAZIABAD'), ('AMAN','IT',78359941265,'RAMPUR'); Output: we have a view of the Table after inserting the values: Step 3: In this step, we have to find how many rows are duplicated. Query: SELECT EMPNAME,DEPT,CONTACTNO,CITY, COUNT(*) FROM EMPDETAIL GROUP BY EMPNAME,DEPT,CONTACTNO,CITY HAVING COUNT(*)>1 Output: Step 4: You can also find out the unique row by using this row. SELECT EMPNAME,DEPT,CONTACTNO,CITY, COUNT(*) FROM DETAILS GROUP BY EMPNAME,DEPT,CONTACTNO,CITY Step 5: Finally we have to delete the duplicate row from the Database. DELETE FROM DETAILS WHERE SN NOT IN ( SELECT MAX(SN) FROM DETAILS GROUP BY EMPNAME,DEPT,CONTACTNO,CITY) Step 6: After deleting the duplicate row, then we have a view of the table: Output: Picked SQL-Query 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? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Convert VARCHAR to INT SQL | Subquery SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python How to Select Data Between Two Dates and Times in SQL Server? How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Compare Two Dates
[ { "code": null, "e": 26090, "s": 26062, "text": "\n23 Sep, 2021" }, { "code": null, "e": 26352, "s": 26090, "text": "Through this article, we will learn how to delete duplicate rows from a database table. As we know that duplicity in our database tends to be a waste of memory spa...
SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table. It is possible to write the INSERT INTO statement in two ways: 1. Specify both the column names and the values to be inserted: 2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows: Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement inserts a new record in the "Customers" table: The selection from the "Customers" table will now look like this: Did you notice that we did not insert any number into the CustomerID field?The CustomerID column is an auto-increment field and will be generated automatically when a new record is inserted into the table. It is also possible to only insert data in specific columns. The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically): The selection from the "Customers" table will now look like this: Insert a new record in the Customers table. Customers CustomerName, Address, City, PostalCode, Country 'Hekkan Burger', 'Gateveien 15', 'Sandnes', '4306', 'Norway'; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "The INSERT INTO statement is used to insert new records in a table." }, { "code": null, "e": 132, "s": 68, "text": "It is possible to write the INSERT INTO \nstatement in two ways:" }, { "code": null, "e": 196, "s": 132, ...
GATE | Gate IT 2008 | Question 79 - GeeksforGeeks
28 Jun, 2021 Consider the code fragment written in C below : void f (int n){ if (n <=1) { printf ("%d", n); } else { f (n/2); printf ("%d", n%2); }} What does f(173) print? (A) 010110101(B) 010101101(C) 10110101(D) 10101101Answer: (D)Explanation: (173)2 = 10101101Quiz of this Question Gate IT 2008 GATE-Gate IT 2008 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 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE CS 2019 | Question 37 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24320, "s": 24292, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24368, "s": 24320, "text": "Consider the code fragment written in C below :" }, { "code": "void f (int n){ if (n <=1) { printf (\"%d\", n); } else { f (n/2); printf (\"%d\"...
Tryit Editor v3.7
Tryit: HTML strong text
[]
Tail events, why they matter and how to model them | by Conor Mc. | Towards Data Science
How to model the unexpected and unlikely the Bayesian way. Rare events are by definition, well, rare. But, inevitably they do happen and when they do they have outsized consequences. 9/11 was a tail event. The financial crisis of 2007/08 was a tail event. Coronavirus was a tail event. Many of the every day products you use, services you engage with and companies you work for are tail events. So, yes, tail events are rare but when they happen their impact is huge. Predicting a tail event or extreme value is intrinsically hard. In fact, one of the most challenging problems I have worked on as a data scientist involved estimating the likelihood of extreme values across business critical systems. Whilst predicting rare events with precision is virtually impossible, estimating their probability is possible, but it requires a departure from business as usual modelling. Specifically, it requires using modelling approaches that allow for the possibility of values or events that lie significantly beyond the conditional mean. Principled approaches to estimating the probability of rare events can help inform decision making, risk adjustments and countermeasures. Whilst there are many ways to approach these problems, in my experience, the approach that is most interpretable, robust and pragmatic is the Bayesian approach. In this post, I’ll provide a worked example of tail events and how a Bayesian model can be used to estimate their probability. Extreme value theory (EVT) is a branch of statistics that deals with values that significantly deviate from the central tendency of a probability distribution. It’s worth noting that an extreme value problem differs fundamentally from rare event prediction problems. For example, fraud detection is a type of rare event classification problem but this is not an extreme value problem. Why? Because a rare event such as fraud is rare, but predictable, whereas the type of extreme values that EVT is concerned with are typically difficult to predict. The ultimate aim of EVT is to estimate the probability of an extreme value occurring. This has many use cases, particularly across natural sciences (e.g. extreme weather events such as earthquakes and Tsunamis), but also across many applied problems in economics, finance and engineering. An extreme value can be extremely low or high. The direction of the value doesn’t really matter. What does matter is the statistical distributions that are used to estimate their likelihood. These distributions are collectively referred to as extreme value distributions. There are many extreme value distributions, but the one that I find most straightforward and useful in practice is the Gumbel distribution. The Gumbel distribution is similar to a Normal distribution in that it is defined solely by two parameters — location and scale. But, unlike the Normal distribution it is asymmetric. This means that the tail of the distribution can skew in the direction of the extreme values. In practice this means that the Gumbel distribution assigns greater likelihood to more extreme events (i.e. events or values in the tail of the distribution) than the Normal distribution. You can see this in the plot below. np.random.seed(123)n = 100000fs = {"fontsize" : 16}plt.figure(figsize=(20, 12))sns.kdeplot(stats.distributions.gumbel_r().rvs(n), label="Gumbel") sns.kdeplot(stats.distributions.norm().rvs(n), label="Normal")plt.legend(**fs)plt.xticks(**fs)plt.yticks(**fs)plt.ylabel("Density", **fs)plt.xlabel("X", **fs); To demonstrate EVT in practice I’ll use this data set on wind speeds which includes extreme values. The data is plotted below. You can a strong seasonal pattern in this data, but also periodic values that fall significantly outside of the normal range. The first thing that we need to do is to isolate these values. To do so, we can use the block maxima approach. This method simply extracts the maximum value of the data across a range (i.e. a block). In this case we’ll extract the maximum value for each month in the data. These points are marked by the red dots in the plot. block_maxima_month = ( df .set_index("date") .resample("M") .max() .wind_speed .reset_index() .query("wind_speed > 5"))fs = {"fontsize" : 16}plt.figure(figsize=(24, 10))plt.scatter(df.date, df.wind_speed, alpha=.3)plt.plot(df.date, df.wind_speed, alpha=.7, c="b")plt.scatter(block_maxima_month.date, block_maxima_month.wind_speed, c="red", s=80)plt.xticks(**fs)plt.yticks(**fs)plt.ylabel("Wind speed", **fs)plt.xlabel("Date", **fs); The next step is to fit a distribution to the block maxima values (shown in he plot below). To do so I’ll fit a simple Bayesian model to the distribution using PyMC3. For illustration purposes I’ll fit both a Normal and Gumbel distribution to the data. The code below fits the distributions to the block maxima values. In both cases I use the same priors. The trace plots display the fit for the Gumbel (top) and Normal distribution (bottom). In both cases the distributions reliably fit the data as indicated by the consistent exploration across each parameter. It is interesting to compare both distributions given that they are defined by the same two parameters, yet have each estimated different parameter values. Let’s see how well each distribution fits the actual distribution of the extreme values. For each model we first need to sample from the posterior distribution. This essentially involves drawing independent samples from the distribution that is defined by the estimated location and scale parameters. Once, we have the posterior distributions we can compare their fit to the actual data. # Extract posterior distributionsev_post = pm.sample_posterior_predictive(ev_trace, model=ev_model)["lik"].Tnorm_post = pm.sample_posterior_predictive(norm_trace, model=norm_model)["lik"].T# Plot density plt.figure(figsize=(20, 10))pm.plot_dist(ev_post, label="Gumbel", textsize=20, hist_kwargs=fs)pm.plot_dist(norm_post, label="Normal", textsize=20, )sns.kdeplot(block_maxima_month.wind_speed, label="Actual")plt.legend(fontsize=14) The plot above shows the fitted Gumbel and Normal distributions alongside the actual distribution of the data. You can see that whilst the Normal distribution does a reasonable job in fitting the data, it does not follow the distribution as well as the Gumbel. For example, you can see that the Normal distribution misses the location of the actual distribution by quite a bit and also has a lighter tail. The Gumbel by comparison appears to fit the actual data much better. It’s also worth noting the long tail of the Gumbel distribution — the Gumbel does not discount the possibility of even more extreme events beyond what was observed in the data. This is exactly why we use these distributions! Now that we have the distributions, one thing that we might like to do is to estimate the probability of an extreme value being exceeded. This is often a very useful and important thing to quantify in practice. To do this we can use the posterior distribution of the Gumbel. The question is; What is the probability that we will see a value that exceeds a specified threshold? The code above simple iterates over specified values and uses the posterior Gumbel distribution to estimate the probability of seeing a greater value. These exceedance probabilities are plotted below. For example, there is around a 0.38 probability that wind speed will exceed 20. Extreme value prediction is an interesting, but challenging problem. This post shows a general approach that you can use to get started on these problems, but this can get much more sophisticated. Also, in this post, I haven’t conditioned the likelihood of an extreme value on any covariate. One interesting extension of this analysis would be to see if there is any value in including additional covariates in the model (e.g. the previous day or week’s wind speed or other weather patterns such as humidity). The most important takeaway is the use of extreme value distributions, such as the Gumbel. When the likelihood of a value or event falls significantly beyond the conditional mean of the distribution then you need an approach that allows for the plausibility of tail events. Thanks for reading! P.S. All code for this post can be found here.
[ { "code": null, "e": 231, "s": 172, "text": "How to model the unexpected and unlikely the Bayesian way." }, { "code": null, "e": 640, "s": 231, "text": "Rare events are by definition, well, rare. But, inevitably they do happen and when they do they have outsized consequences. 9/1...
How to remove all instances of a specific character from a column in MySQL?
Let us first create a table − mysql> create table DemoTable -> ( -> FirstName varchar(100) -> ); Query OK, 0 rows affected (0.41 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Adam^^^'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('^^^^^^^^Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Robert^^^^^^'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +---------------+ | FirstName | +---------------+ | Adam^^^ | | ^^^^^^^^Carol | | Robert^^^^^^ | +---------------+ 3 rows in set (0.00 sec) Following is the query to remove all instances of a specific character from a column in MySQL. Here, we are removing all the instances of the special character ^ − mysql> update DemoTable set FirstName=replace(FirstName,'^',''); Query OK, 3 rows affected (0.20 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check table records once again − mysql> select *from DemoTable; This will produce the following output − +-----------+ | FirstName | +-----------+ | Adam | | Carol | | Robert | +-----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1205, "s": 1092, "text": "mysql> create table DemoTable\n -> (\n -> FirstName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.41 sec)" }, { "code": null, "e"...
Count the Number of matching characters in a pair of Java string
In order to find the count of matching characters in two Java strings the approach is to first create character arrays of both the strings which make comparison simple.After this put each unique character into a Hash map. Compare each character of other string with created hash map whether it is present or not in case if present than put that character into other hash map this is to prevent duplicates.In last get the size of this new created target hash map which is equal to the count of number of matching characters in two given strings. Live Demo import java.util.HashMap; public class MatchingCharacters { public static void main(String[] args) { String str1 = "abcccdef"; String str2 = "dfgterf"; char[] arr = str1.toCharArray(); char[] arr2 = str2.toCharArray(); HashMap<Character,Integer> hMap = new HashMap<>(); HashMap<Character,Integer> hMap2 = new HashMap<>(); for(int i = 0 ; i < arr.length ; i++) { if(!hMap.containsKey(arr[i])) { hMap.put(arr[i],1); } } for(int i = 0 ;i <arr2.length ;i++) { if(hMap.containsKey(arr2[i])) { hMap2.put(arr2[i],1); } } System.out.println("Number of matching characters in a pair of Java string is : " + hMap2.size()); } } Number of matching characters in a pair of Java string is : 3
[ { "code": null, "e": 1284, "s": 1062, "text": "In order to find the count of matching characters in two Java strings the approach is to first create character arrays of both the strings which make comparison simple.After this put each unique character into a Hash map." }, { "code": null, ...